public void SetRsaPublicKeyInformation(Dictionary <string, object> result, OfficeDocumentJsonWebKeyResponse jsonWebKey)
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                using (var provider = new RSACryptoServiceProvider())
                {
                    provider.FromXmlStringNetCore(jsonWebKey.SerializedKey);
                    var rsaParameters = provider.ExportParameters(false);
                    // Export the modulus
                    var modulus = rsaParameters.Modulus.Base64EncodeBytes();
                    // Export the exponent
                    var exponent = rsaParameters.Exponent.Base64EncodeBytes();

                    result.Add("n", modulus);
                    result.Add("e", exponent);
                }
            }
            else
            {
                using (var provider = new RSAOpenSsl())
                {
                    provider.FromXmlStringNetCore(jsonWebKey.SerializedKey);
                    var rsaParameters = provider.ExportParameters(false);
                    // Export the modulus
                    var modulus = rsaParameters.Modulus.Base64EncodeBytes();
                    // Export the exponent
                    var exponent = rsaParameters.Exponent.Base64EncodeBytes();

                    result.Add("n", modulus);
                    result.Add("e", exponent);
                }
            }
        }
示例#2
0
        public void SetRsaPublicKeyInformation(Dictionary <string, object> result, JsonWebKey jsonWebKey)
        {
            RSAParameters rsaParameters;

#if NET461
            using (var provider = new RSACryptoServiceProvider())
            {
                provider.FromXmlString(jsonWebKey.SerializedKey);
                rsaParameters = provider.ExportParameters(false);
            }
#else
            using (var provider = new RSAOpenSsl())
            {
                provider.FromXmlString(jsonWebKey.SerializedKey);
                rsaParameters = provider.ExportParameters(false);
            }
#endif
            // Export the modulus
            var modulus = rsaParameters.Modulus.Base64EncodeBytes();
            // Export the exponent
            var exponent = rsaParameters.Exponent.Base64EncodeBytes();

            result.Add(SimpleIdentityServer.Core.Jwt.Constants.JsonWebKeyParameterNames.RsaKey.ModulusName, modulus);
            result.Add(SimpleIdentityServer.Core.Jwt.Constants.JsonWebKeyParameterNames.RsaKey.ExponentName, exponent);
        }
示例#3
0
 public static void VerifyParameterCtor()
 {
     using (RSA rsa = new RSAOpenSsl(TestData.RSA1032Parameters))
     {
         ImportExport.AssertKeyEquals(TestData.RSA1032Parameters, rsa.ExportParameters(true));
     }
 }
        public static string ToXmlStringNetCore(this RSAOpenSsl rsa, bool includePrivateParameters = false)
        {
            RSAParameters parameters = rsa.ExportParameters(includePrivateParameters);

            if (includePrivateParameters)
            {
                return(string.Format("<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent><P>{2}</P><Q>{3}</Q><DP>{4}</DP><DQ>{5}</DQ><InverseQ>{6}</InverseQ><D>{7}</D></RSAKeyValue>",
                                     Convert.ToBase64String(parameters.Modulus),
                                     Convert.ToBase64String(parameters.Exponent),
                                     Convert.ToBase64String(parameters.P),
                                     Convert.ToBase64String(parameters.Q),
                                     Convert.ToBase64String(parameters.DP),
                                     Convert.ToBase64String(parameters.DQ),
                                     Convert.ToBase64String(parameters.InverseQ),
                                     Convert.ToBase64String(parameters.D)));
            }

            return(string.Format("<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent></RSAKeyValue>",
                                 Convert.ToBase64String(parameters.Modulus),
                                 Convert.ToBase64String(parameters.Exponent)));
        }
示例#5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        /// <summary>
        ///
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            services
            .AddMvc()
            .AddJsonOptions(a => a.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver())

            .AddRazorPagesOptions(options =>
            {
                #region Razor-Convention Feature
                //options.Conventions.Add(new GlobalTemplatePageRouteModelConvention()); // Swagger etc.
                //options.Conventions.Add(new GlobalHeaderPageApplicationModelConvention()); // Swagger etc.
                //options.Conventions.ConfigureFilter(new AddHeaderWithFactory());
                #endregion
            });



            services.AddSession(options =>
            {
                //options.Cookie.HttpOnly = false;
                //options.Cookie.Name = ".ASPNetCoreSession";
                //options.IdleTimeout = TimeSpan.FromMinutes(40);
                //options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
                //options.Cookie.Path = "/";
            });

            services.AddDistributedMemoryCache();


            #region appsettings.json

            services.Configure <DatabaseSettings>(Configuration.GetSection("DatabaseSettings"));


            #endregion


            #region file location


            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                string webRootPath = _hostingEnvironment.WebRootPath;

                services.AddSingleton <IFileProvider>(
                    new PhysicalFileProvider(
                        Path.Combine(Directory.GetCurrentDirectory(), webRootPath + "\\documents")));
            }



            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                string webRootPath = _hostingEnvironment.WebRootPath;

                services.AddSingleton <IFileProvider>(
                    new PhysicalFileProvider(
                        Path.Combine(Directory.GetCurrentDirectory(), webRootPath + "/documents")));
            }
            #endregion


            #region Razor Page Indexing

            services.AddMvc()
            .AddRazorPagesOptions(options =>
            {
                options.Conventions.AuthorizePage("/Files");
                //options.Conventions.AllowAnonymousToPage("/Private/PublicPage");
                //options.Conventions.AllowAnonymousToFolder("/Private/PublicPages");
            });

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            #endregion


            #region HTTPS!

            services.Configure <MvcOptions>(options =>
            {
                options.Filters.Add(new RequireHttpsAttribute());
            });

            #endregion


            #region Swagger
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Info
                {
                    Version        = "v1",
                    Title          = ".NET Core 2.1 RESTful API Template with Swagger API Doc",
                    Description    = "This Template is based on the Northwind database, an excellent tutorial schema for a small-business ERP, with customers, orders, inventory, purchasing, suppliers, shipping, employees, and single-entry accounting.",
                    TermsOfService = "None",
                    Contact        = new Contact()
                    {
                        Name  = "Davain Pablo Edwards",
                        Email = "*****@*****.**",
                        Url   = ""
                    }
                });


                //c.IncludeXmlComments(GetXmlCommentsPath());
                //options.IncludeXmlComments(GetXmlCommentsPath());
                options.OperationFilter <AddFileParamTypesOperationFilter>();
                options.DescribeAllEnumsAsStrings();



                // 2018-06-18
                // Kommentar-Pfad für swagger JSON und UI
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                options.IncludeXmlComments(xmlPath);
            });

            services.AddSwaggerDocumentation();
            #endregion


            #region Token auth

            // Windows os support
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                RSACryptoServiceProvider rSA = new RSACryptoServiceProvider(2048);

                RSAParameters keyParam = rSA.ExportParameters(true);
                _key       = new RsaSecurityKey(keyParam);
                _tokenAuth = new TokenAuthOptions
                {
                    Audience           = "TokenAudience",
                    Issuer             = "Issuer",
                    SigningCredentials = new SigningCredentials(_key, SecurityAlgorithms.RsaSha256Signature)
                };
            }

            // Linux os support
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                RSAOpenSsl rSA = new RSAOpenSsl(2048);

                RSAParameters keyParam = rSA.ExportParameters(true);
                _key       = new RsaSecurityKey(keyParam);
                _tokenAuth = new TokenAuthOptions
                {
                    Audience           = "TokenAudience",
                    Issuer             = "Issuer",
                    SigningCredentials = new SigningCredentials(_key, SecurityAlgorithms.RsaSha256Signature)
                };
            }


            services.AddSingleton <TokenAuthOptions>(_tokenAuth);

            services.AddAuthorization(auth =>
            {
                auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
                               .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme‌​)
                               .RequireAuthenticatedUser().Build());
            });

            services.AddAuthentication()
            .AddCookie(auth => auth.SlidingExpiration = true)
            .AddJwtBearer(auth =>
            {
                auth.RequireHttpsMetadata = false;
                auth.SaveToken            = true;

                auth.TokenValidationParameters = new TokenValidationParameters
                {
                    IssuerSigningKey = _key,
                    ValidAudience    = _tokenAuth.Audience,
                    ValidIssuer      = _tokenAuth.Issuer,

                    ValidateLifetime = true,

                    ClockSkew = TimeSpan.FromMinutes(0)
                };
            });
            #endregion


            services
            .AddMvc()
            .AddJsonOptions(a => a.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver());


            services.AddEntityFrameworkMySql().AddDbContext <RESTfulAPI_DbContext>();

            services.AddScoped <IEntityMapper, RESTfulAPI_EntityMapper>();

            services.AddScoped <IRESTfulAPI_Repository, RESTfulAPI_Repository>();

            services.AddOptions();
            services.AddSingleton(Configuration);
        }