private static void RegisterTokenAuthorizationOptions(IServiceCollection services) {
			//in production keep RSACryptoServiceProvider in save place
			RSACryptoServiceProvider keyService = new RSACryptoServiceProvider(2048);
			var xmlString = String.Empty;
			var path = @"C:\Users\marcianno\Documents\Key\RsaProvider.txt";
			using (StreamReader sw = new StreamReader(path)) {
				xmlString = sw.ReadToEnd();
			}

			keyService.FromXmlString(xmlString);
			RsaSecurityKey key = new RsaSecurityKey(keyService.ExportParameters(true));

			var tokenOptions = new TokenAuthorizationOptions {
				Audience = "MobileSecondHandApp",
				Issuer = "MarcinSzyszka",
				SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256Signature)
			};
			services.AddSingleton<TokenAuthorizationOptions>(tokenOptions);
		}
        public void CanValidateRS256()
        {
            const string token = "eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.cC4hiUPoj9Eetdgtv3hF80EGrhuB__dzERat0XF9g2VtQgr9PJbu3XOiZj5RZmh7AAuHIm4Bh-0Qc_lF5YKt_O8W2Fp5jujGbds9uJdbF9CUAr7t1dnZcAcQjbKBYNX4BAynRFdiuB--f_nZLgrnbyTyWzO75vRK5h6xBArLIARNPvkSjtQBMHlb1L07Qe7K0GarZRmB_eSN9383LcOLn6_dO--xi12jzDwusC-eOkHWEsqtFZESc6BfI7noOPqvhJ1phCnvWh6IeYI2w9QOYEUipUTI8np6LbgGY9Fs98rqVt5AXLIhWkWywlVmtVrBp0igcN_IoypGlUPQGe77Rw";
            var          n     = Base64Url.DeserializeBytes("ofgWCuLjybRlzo0tZWJjNiuSfb4p4fAkd_wWJcyQoTbji9k0l8W26mPddxHmfHQp-Vaw-4qPCJrcS2mJPMEzP1Pt0Bm4d4QlL-yRT-SFd2lZS-pCgNMsD1W_YpRPEwOWvG6b32690r2jZ47soMZo9wGzjb_7OMg0LOL-bSf63kpaSHSXndS5z5rexMdbBYUsLA9e-KXBdQOS-UTo7WTBEMa2R2CapHg665xsmtdVMTBQY4uDZlxvb3qCo5ZwKh9kG4LT6_I5IhlJH7aGhyxXFvUK-DWNmoudF8NAco9_h9iaGNj8q2ethFkMLs91kzk2PAcDTW9gb54h4FRWyuXpoQ", "n");
            var          e     = Base64Url.DeserializeBytes("AQAB", "e");

            var key = new RsaSecurityKey(new RSAParameters {
                Exponent = e, Modulus = n
            });

            IdentityModelEventSource.ShowPII = true;

            var result = new JsonWebTokenHandler().ValidateToken(token, new TokenValidationParameters
            {
                IssuerSigningKey = key,
                ClockSkew        = TimeSpan.FromDays(4000),
                ValidIssuer      = "joe",
                ValidateAudience = false
            });

            result.IsValid.ShouldBeTrue();
        }
Ejemplo n.º 3
0
        /// <summary>
        /// 向容器注入Jupiter Token检查服务
        /// </summary>
        /// <param name="services"></param>
        /// <param name="Configuration"></param>
        /// <returns></returns>
        public static IServiceCollection AddJwtBearerAuthentication(this IServiceCollection services, IConfiguration Configuration)
        {
            var appSettingSection = Configuration.GetSection("AppSetting");

            services.Configure <JupiterKeys>(appSettingSection);
            var keys = appSettingSection.Get <JupiterKeys>();

            if (!TryGetKeyParameters(keys, out RSAParameters keyParams))
            {
                throw new UnauthorizeException();
            }

            var key = new RsaSecurityKey(keyParams);

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })

            .AddCookie(cfg => cfg.SlidingExpiration = true)
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = true;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = key,
                    ValidateIssuer           = true,
                    ValidIssuer      = "Jupiter",
                    ValidateAudience = false,
                };
            });

            services.AddHttpClient();

            return(services);
        }
        private SecurityKey GetAsymmetricSecurityKey(string keyPairId)
        {
            if (_publicKeyStore == null)
            {
                _logger.LogError("Public Key store not available");
                return(null);
            }

            // get key by keyPairId or latest
            var key = _publicKeyStore.GetKey(keyPairId);

            if (key == null)
            {
                _logger.LogError("Couldn't retrieve public key");
                return(null);
            }

            var securityKey = new RsaSecurityKey(new OpenSSLPublicKeyDecoder().DecodeParameters(key));

            _logger.LogError("Created security key {SecurityKeyId}", securityKey.KeyId);
            return(securityKey);
        }
        public ActionResult <string> Login([FromBody] LoginDto dto)
        {
            if (!dto.UserName.Equals(dto.Password))
            {
                return(string.Empty);
            }

            var user = new User
            {
                Id          = 1,
                Name        = dto.UserName,
                Email       = "*****@*****.**",
                Birthday    = DateTime.Now.AddYears(-10),
                PhoneNumber = "18888888888"
            };

            var tokenHandler = new JwtSecurityTokenHandler();

            var rsaPrivateKey  = System.IO.File.ReadAllText(Path.Combine(_env.ContentRootPath, "private.key"));
            var rSAParameters  = JsonConvert.DeserializeObject <RSAParameters>(rsaPrivateKey);
            var rsaSecurityKey = new RsaSecurityKey(rSAParameters);

            var tokenDescriptor = new SecurityTokenDescriptor()
            {
                Subject = new ClaimsIdentity(new Claim[] {
                    new Claim(JwtClaimTypes.Id, user.Id.ToString()),
                    new Claim(JwtClaimTypes.Name, user.Name),
                    new Claim(JwtClaimTypes.Email, user.Email),
                    new Claim(JwtClaimTypes.PhoneNumber, user.PhoneNumber),
                }),
                Expires            = DateTime.UtcNow.AddMinutes(15),
                SigningCredentials = new SigningCredentials(rsaSecurityKey, SecurityAlgorithms.RsaSha256Signature),
                Audience           = "aspnetcoreweb",
                Issuer             = "jjj",
            };
            var token = tokenHandler.CreateEncodedJwt(tokenDescriptor);

            return(token);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Creates a new RSA security key.
        /// </summary>
        /// <returns></returns>
        public static RsaSecurityKey CreateRsaSecurityKey()
        {
            var            rsa = RSA.Create();
            RsaSecurityKey key;

            if (rsa is RSACryptoServiceProvider)
            {
                rsa.Dispose();
                var cng = new RSACng(2048);

                var parameters = cng.ExportParameters(includePrivateParameters: true);
                key = new RsaSecurityKey(parameters);
            }
            else
            {
                rsa.KeySize = 2048;
                key         = new RsaSecurityKey(rsa);
            }

            //key.KeyId = CryptoRandom.CreateUniqueId(16);
            return(key);
        }
Ejemplo n.º 7
0
        public void ConfigureServices(IServiceCollection services)
        {
            var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
            var json          = File.ReadAllText("oauth_puk.txt");
            var dic           = JsonConvert.DeserializeObject <Dictionary <string, string> >(json);
            var rsaParameters = new RSAParameters
            {
                Modulus  = dic.TryGet(RSAFields.Modulus),
                Exponent = dic.TryGet(RSAFields.Exponent)
            };
            var oauthRsaSecurityKey = new RsaSecurityKey(rsaParameters);

            services.AddMvc();
            services.AddLogging();
            services.AddAuthorization(opts => opts.AddDefaultSCIMAuthorizationPolicy());
            services.AddAuthentication(SCIMConstants.AuthenticationScheme)
            .AddJwtBearer(SCIMConstants.AuthenticationScheme, cfg =>
            {
                cfg.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidIssuer    = "http://localhost:60000",
                    ValidAudiences = new List <string>
                    {
                        "scimClient"
                    },
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = oauthRsaSecurityKey
                };
            });
            services.AddSIDScim(_ =>
            {
                _.IgnoreUnsupportedCanonicalValues = false;
            });
            services.AddScimStoreEF(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("db"), o => o.MigrationsAssembly(migrationsAssembly));
            });
        }
Ejemplo n.º 8
0
        internal static License ValidateKey(string licenseKey)
        {
            if (!String.IsNullOrWhiteSpace(licenseKey))
            {
                var handler = new JwtSecurityTokenHandler();

                try
                {
                    var rsa = new RSAParameters
                    {
                        Exponent = Convert.FromBase64String("AQAB"),
                        Modulus  = Convert.FromBase64String("tAHAfvtmGBng322TqUXF/Aar7726jFELj73lywuCvpGsh3JTpImuoSYsJxy5GZCRF7ppIIbsJBmWwSiesYfxWxBsfnpOmAHU3OTMDt383mf0USdqq/F0yFxBL9IQuDdvhlPfFcTrWEL0U2JsAzUjt9AfsPHNQbiEkOXlIwtNkqMP2naynW8y4WbaGG1n2NohyN6nfNb42KoNSR83nlbBJSwcc3heE3muTt3ZvbpguanyfFXeoP6yyqatnymWp/C0aQBEI5kDahOU641aDiSagG7zX1WaF9+hwfWCbkMDKYxeSWUkQOUOdfUQ89CQS5wrLpcU0D0xf7/SrRdY2TRHvQ=="),
                    };

                    var key = new RsaSecurityKey(rsa)
                    {
                        KeyId = "IdentityServerLicensekey/7ceadbb78130469e8806891025414f16"
                    };

                    var parms = new TokenValidationParameters
                    {
                        ValidIssuer      = "https://duendesoftware.com",
                        ValidAudience    = "IdentityServer",
                        IssuerSigningKey = key,
                        ValidateLifetime = false
                    };

                    var validateResult = handler.ValidateToken(licenseKey, parms, out _);
                    return(new License(validateResult));
                }
                catch (Exception ex)
                {
                    _logger.LogCritical(ex, "Error validating Duende IdentityServer license key");
                }
            }

            return(null);
        }
    public async Task ResolveAuthorityAndKeysAsync_SetsUpAuthorityAndKeysOnTheTokenValidationParametersAsync()
    {
        // Arrange
        var localApiDescriptor = new Mock <IIdentityServerJwtDescriptor>();

        localApiDescriptor.Setup(lad => lad.GetResourceDefinitions())
        .Returns(new Dictionary <string, ResourceDefinition>
        {
            ["TestAPI"] = new ResourceDefinition {
                Profile = ApplicationProfiles.IdentityServerJwt
            }
        });

        var credentialsStore = new Mock <ISigningCredentialStore>();
        var key = new RsaSecurityKey(RSA.Create());

        credentialsStore.Setup(cs => cs.GetSigningCredentialsAsync())
        .ReturnsAsync(new SigningCredentials(key, "RS256"));

        var context = new DefaultHttpContext();

        context.Request.Scheme  = "https";
        context.Request.Host    = new HostString("localhost");
        context.RequestServices = new ServiceCollection()
                                  .AddSingleton(new IdentityServerOptions())
                                  .AddSingleton(credentialsStore.Object)
                                  .BuildServiceProvider();

        var options = new JwtBearerOptions();
        var args    = new MessageReceivedContext(context, new AuthenticationScheme("TestAPI", null, Mock.Of <IAuthenticationHandler>().GetType()), options);

        // Act
        await IdentityServerJwtBearerOptionsConfiguration.ResolveAuthorityAndKeysAsync(args);

        // Assert
        Assert.Equal("https://localhost", options.TokenValidationParameters.ValidIssuer);
        Assert.Equal(key, options.TokenValidationParameters.IssuerSigningKey);
    }
Ejemplo n.º 10
0
        public void ConfigureServices(IServiceCollection services)
        {
            // *** CHANGE THIS FOR PRODUCTION USE ***
            // Here, we're generating a random key to sign tokens - obviously this means
            // that each time the app is started the key will change, and multiple servers
            // all have different keys. This should be changed to load a key from a file
            // securely delivered to your application, controlled by configuration.
            //
            // See the RSAKeyUtils.GetKeyParameters method for an examle of loading from
            // a JSON file.
            RSAParameters keyParams = RSAKeyUtils.GetRandomKey();

            // Create the key, and a set of token options to record signing credentials
            // using that key, along with the other parameters we will need in the
            // token controlller.
            key          = new RsaSecurityKey(keyParams);
            tokenOptions = new TokenAuthOptions()
            {
                Audience           = TokenAudience,
                Issuer             = TokenIssuer,
                SigningCredentials = new SigningCredentials(key,
                                                            SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest)
            };

            // Save the token options into an instance so they're accessible to the
            // controller.
            services.AddInstance <TokenAuthOptions>(tokenOptions);

            // Enable the use of an [Authorize("Bearer")] attribute on methods and classes to protect.
            services.AddAuthorization(auth =>
            {
                auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
                               .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme‌​)
                               .RequireAuthenticatedUser().Build());
            });

            services.AddMvc();
        }
Ejemplo n.º 11
0
        internal static void GetPublicKey()
        {
            while (true)
            {
                try
                {
                    if (ServerUrl.EndsWith("/") == false)
                    {
                        ServerUrl += "/";
                    }
                    var serverContnt = Way.Lib.HttpClient.GetContent($"{ServerUrl}.well-known/openid-configuration", 8000).FromJson <Dictionary <string, object> >();
                    var keyContent   = Way.Lib.HttpClient.GetContent(serverContnt["jwks_uri"].ToString(), 8000);


                    JsonWebKeySet exampleJWKS = new JsonWebKeySet(keyContent);
                    JsonWebKey    exampleJWK  = exampleJWKS.Keys.First();


                    /* Create RSA from Elements in JWK */
                    RSAParameters rsap = new RSAParameters
                    {
                        Modulus  = WebEncoders.Base64UrlDecode(exampleJWK.N),
                        Exponent = WebEncoders.Base64UrlDecode(exampleJWK.E),
                    };
                    System.Security.Cryptography.RSA rsa = System.Security.Cryptography.RSA.Create();
                    rsa.ImportParameters(rsap);
                    rsaSecurityKey = new RsaSecurityKey(rsa);

                    Thread.Sleep(RefreshPublicKeySeconds * 1000);
                }
                catch (Exception ex)
                {
                    _logger?.LogError(ex, "");
                    Thread.Sleep(1000);
                    continue;
                }
            }
        }
Ejemplo n.º 12
0
        public ActionResult <string> Login()
        {
            var user = new User
            {
                Id          = 1,
                Name        = "jjj",
                Email       = "*****@*****.**",
                Birthday    = DateTime.Now.AddYears(-10),
                Password    = "******",
                PhoneNumber = "18888888888"
            };

            var tokenHandler   = new Saml2SecurityTokenHandler();
            var privateKey     = System.IO.File.ReadAllText(Path.Combine(_env.ContentRootPath, "private.key"));
            var rsaParameters  = JsonConvert.DeserializeObject <RSAParameters>(privateKey);
            var rsaSecurityKey = new RsaSecurityKey(rsaParameters);

            var tokenDescriptor = new SecurityTokenDescriptor()
            {
                Issuer             = "https://www.jjj.me",
                Audience           = "https://api.jjj.me",
                NotBefore          = DateTime.Now,
                Expires            = DateTime.UtcNow.AddMinutes(15),
                SigningCredentials = new SigningCredentials(rsaSecurityKey, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest),
                Subject            = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                    new Claim(ClaimTypes.Name, user.Name),
                    new Claim(ClaimTypes.Email, user.Email),
                    new Claim(ClaimTypes.MobilePhone, user.PhoneNumber),
                    new Claim(ClaimTypes.Role, "Manager")
                })
            };

            var token = tokenHandler.WriteToken(tokenHandler.CreateToken(tokenDescriptor));

            return(token);
        }
Ejemplo n.º 13
0
        static void Main(string[] args)
        {
            String privateKeyPath = @"E:\dev\java\intellijws\e2e-microservice\demo\demo\target\test-classes\privateKey.pem";

            using (var rsa = PrivateKeyFromPemFile(privateKeyPath))
            {
                RsaSecurityKey rsaSecurityKey = new RsaSecurityKey(rsa);
                ClaimsIdentity subject        = new ClaimsIdentity();
                subject.AddClaim(new Claim("a", "b"));
                SigningCredentials rsaSigningCredentials =
                    new SigningCredentials(
                        rsaSecurityKey,
                        SecurityAlgorithms.RsaSha256,
                        SecurityAlgorithms.Sha256Digest);

                JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
                //var token = tokenHandler.CreateEncodedJwt(issuer: "abc",
                //    audience: "default",
                //    subject: subject,
                //    notBefore: DateTime.UnixEpoch,
                //    expires: DateTime.UnixEpoch + TimeSpan.FromHours(1),
                //    issuedAt: DateTime.UnixEpoch,
                //    signingCredentials: rsaSigningCredentials);
                //Console.WriteLine(token);

                JwtSecurityToken jwt = tokenHandler.CreateJwtSecurityToken(
                    issuer: "abc",
                    audience: "default",
                    subject: subject,
                    notBefore: DateTime.UnixEpoch,
                    expires: DateTime.UnixEpoch + TimeSpan.FromHours(1),
                    signingCredentials: rsaSigningCredentials);
                Console.WriteLine(tokenHandler.WriteToken(jwt));
                //Console.WriteLine(jwt.RawData);
            }

            Console.ReadLine();
        }
        public SigningConfigurations()
        {
            using (var provider = new RSACryptoServiceProvider(2048))
            {
                /*
                 *           var pubKey = provider.ExportParameters(true);
                 *
                 *           string pubKeyString;
                 *           {
                 *               //we need some buffer
                 *               var sw = new System.IO.StringWriter();
                 *               //we need a serializer
                 *               var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
                 *               //serialize the key into the stream
                 *               xs.Serialize(sw, pubKey);
                 *               //get the string from the stream
                 *               pubKeyString = sw.ToString();
                 *           }
                 *
                 *           Console.WriteLine(pubKeyString);*/
                var           signKey = File.ReadAllText("Configuration/signkey.xml");
                RSAParameters pubKey;
                //converting it back
                {
                    //get a stream from the string
                    var sr = new System.IO.StringReader(signKey);
                    //we need a deserializer
                    var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
                    //get the object back from the stream
                    pubKey = (RSAParameters)xs.Deserialize(sr);
                }

                Key = new RsaSecurityKey(pubKey);
            }

            SigningCredentials = new SigningCredentials(
                Key, SecurityAlgorithms.RsaSha256Signature);
        }
Ejemplo n.º 15
0
        public string Build()
        {
            SigningCredentials signingCredentials;
            string?            kid = null;

            if (PublicPrivateKey == null)
            {
                Certificate.Verify(nameof(Certificate)).IsNotNull();
                var securityKey = new X509SecurityKey(Certificate);
                signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.RsaSha512);
            }
            else
            {
                kid = PublicPrivateKey.Kid.ToString();
                var privateSecurityKey = new RsaSecurityKey(PublicPrivateKey.GetPrivateKey());

                signingCredentials = new SigningCredentials(privateSecurityKey, SecurityAlgorithms.RsaSha512);
            }

            var header = new JwtHeader(signingCredentials);

            header["kid"] = kid ?? header["kid"];

            var addClaims = new List <Claim>();

            if (!WebKey.IsEmpty())
            {
                addClaims.Add(new Claim(JwtStandardClaimNames.WebKeyName, WebKey));
            }
            ;

            var payload = new JwtPayload(Issuer, Audience, Claims.Concat(addClaims), NotBefore, Expires, IssuedAt);

            var jwtToken     = new JwtSecurityToken(header, payload);
            var tokenHandler = new JwtSecurityTokenHandler();

            return(tokenHandler.WriteToken(jwtToken));
        }
Ejemplo n.º 16
0
        public string GenerateToken(User user)
        {
            var            tokenHandler = new JwtSecurityTokenHandler();
            RsaSecurityKey securityKey  = new RsaSecurityKey(RSACertificateExtensions.GetRSAPrivateKey(_certificate));

            securityKey.KeyId = _tenantData.KeyID;
            var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.RsaSha256);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim("sub", user.Subject),
                    new Claim("subType", "user"),
                    new Claim("name", user.DisplayName),
                    new Claim("email", user.Email),
                    new Claim("email_verified", "true", ClaimValueTypes.Boolean)
                }),
                Expires            = DateTime.UtcNow.AddHours(3),
                Issuer             = _tenantData.Issuer,
                Audience           = "qlik.api/login/jwt-session",
                SigningCredentials = signingCredentials
            };

            if (user.HasImageURL())
            {
                tokenDescriptor.Subject.AddClaim(new Claim("picture", user.ImageURL));
            }
            for (int i = 0; i < user.Groups.Length; i++)
            {
                tokenDescriptor.Subject.AddClaim(new Claim("groups", user.Groups[i]));
            }

            var    token    = tokenHandler.CreateToken(tokenDescriptor);
            string jwtToken = tokenHandler.WriteToken(token);

            return(jwtToken);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Add JWT support on authentication
        /// </summary>
        /// <param name="services"></param>
        public static void AddAuth(this IServiceCollection services, bool hasIdentityServer)
        {
            config = LightConfigurator.Config <AuthConfiguration>("Auth");
            var rsaConfig = LightConfigurator.Config <SigningCredentialsConfig>("SigningCredentials");

            RSAParameters rsaParameters = new RSAParameters
            {
                D        = Convert.FromBase64String(rsaConfig.D),
                DP       = Convert.FromBase64String(rsaConfig.DP),
                DQ       = Convert.FromBase64String(rsaConfig.DQ),
                Exponent = Convert.FromBase64String(rsaConfig.Exponent),
                InverseQ = Convert.FromBase64String(rsaConfig.InverseQ),
                Modulus  = Convert.FromBase64String(rsaConfig.Modulus),
                P        = Convert.FromBase64String(rsaConfig.P),
                Q        = Convert.FromBase64String(rsaConfig.Q)
            };
            SecurityKey key = new RsaSecurityKey(rsaParameters);

            key.KeyId = rsaConfig.KeyId;

            if (!hasIdentityServer)
            {
                services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(jwtOpt =>
                {
                    jwtOpt.Authority = config.Authority;
                    jwtOpt.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer   = true,
                        ValidIssuer      = config.Authority,
                        ValidateAudience = true,
                        ValidAudiences   = config.Audiencies.Split(','),
                        IssuerSigningKey = key
                    };
                    jwtOpt.Events = new JwtBearerEvents();
                    jwtOpt.RequireHttpsMetadata = config.RequireHttpsMetadata;
                });
            }
        }
        public string GenerateJWT()
        {
            DateTime UnixEpoch           = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            // Provide proper private key
            string privateSecretKey = "OfED+KgbZxtu4e4+JSQWdtSgTnuNixKy1nMVAEww8QL3IN33XusJhrz9HXmIrdyX2F41xJHG4uj5/2Dzv3xjYYvqxexm3X3X5TOf3WoM1VNloJ7UnbqUJOiEjgK8sRdJntgfomO4U8s67cpysk0h9rc0He4xRspEjOapFfDg+VG8igidcNgbNDSSaV4491Fo3sq2aGSCtYvekzs7JwXJnNAyvDSJjfK/7M8MpxSMnm1vMscBXyiYFXhGC4wqWlYBE828/5DNyw3QZW5EjD7hvDrY5OlYd4smCTa53helNnJz5NT9HQaDbE2sMwIDAQABAoIBAEs63TvT94njrPDP3A/sfCEXg1F2y0D/PjzUhM1aJGcRiOUXnGlYdViGhLnnJoNZTZm9qI1LT0NWcDA5NmBN6gcrk2EApyTt1D1i4AQ66rYoTF9iEC4Wye28v245BYESA6IIelgIxXGsVyllERsbTkaphzibbYfHmvwMxkn135Zfzd/NOXl/O32vYIomzrNEP+tN2WXhhG8c8+iZ8PErBV3CqrYogYy97d2CeQbXcpd5unPiU4TK0nnzeBAXdgeYuJHFC45YHl9UvShRoe6CHR47ceIGp6WMc5BTyyTkZpctuYJTwaChdj/QuRSkTYmn6jFL+MRfYQJ8VVwSVo5DbkECgYEA4/YIMKcwObYcSuHzgkMwH645CRDoy9M98eptAoNLdJBHYz23U5IbGL1+qHDDCPXxKs9ZG7EEqyWezq42eoFoebLA5O6/xrYXoaeIb094dbCF4D932hAkgAaAZkZVsSiWDCjYSV+JoWX4NVBcIL9yyHRhaaPVULTRbPsZQWq9+hMCgYEA48j4RGO7CaVpgUVobYasJnkGSdhkSCd1VwgvHH3vtuk7/JGUBRaZc0WZGcXkAJXnLh7QnDHOzWASdaxVgnuviaDi4CIkmTCfRqPesgDR2Iu35iQsH7P2/o1pzhpXQS/Ct6J7/GwJTqcXCvp4tfZDbFxS8oewzp4RstILj+pDyWECgYByQAbOy5xB8GGxrhjrOl1OI3V2c8EZFqA/NKy5y6/vlbgRpwbQnbNy7NYj+Y/mV80tFYqldEzQsiQrlei78Uu5YruGgZogL3ccj+izUPMgmP4f6+9XnSuN9rQ3jhy4k4zQP1BXRcim2YJSxhnGV+1hReLknTX2IwmrQxXfUW4xfQKBgAHZW8qSVK5bXWPjQFnDQhp92QM4cnfzegxe0KMWkp+VfRsrw1vXNx";

            rsa = DecodeRSAPrivateKey(FromBase64Url(privateSecretKey));
            //convert to csp format
            var bytes     = rsa.ExportCspBlob(false);
            var publicKey = Convert.ToBase64String(bytes);
            //
            RsaSecurityKey _signingKey = new RsaSecurityKey(rsa);

            Microsoft.IdentityModel.Tokens.SigningCredentials signingCredentials =
                new Microsoft.IdentityModel.Tokens.SigningCredentials(_signingKey, SecurityAlgorithms.RsaSha256);
            JwtHeader head = new JwtHeader(signingCredentials);

            head.Add("kid", "lzo-firstpublickey");

            string sNewGuid = Guid.NewGuid().ToString("n");
            var    claims   = new[]
            {
                new Claim(JwtRegisteredClaimNames.Iss, "s6BhdRkqt3"),
                new Claim(JwtRegisteredClaimNames.Sub, "s6BhdRkqt3"),
                new Claim(JwtRegisteredClaimNames.Aud, "https://cis.ncrs/connect/token"),
                new Claim(JwtRegisteredClaimNames.Jti, sNewGuid),
                new Claim(JwtRegisteredClaimNames.Exp, ((Int64)DateTime.Now.AddMinutes(55).Subtract(UnixEpoch).TotalSeconds).ToString(System.Globalization.CultureInfo.InvariantCulture), ClaimValueTypes.Integer64),
                new Claim(JwtRegisteredClaimNames.Iat, ((Int64)DateTime.Now.Subtract(UnixEpoch).TotalSeconds).ToString(System.Globalization.CultureInfo.InvariantCulture), ClaimValueTypes.Integer64)
            };
            JwtPayload       payload = new JwtPayload(claims);
            JwtSecurityToken jwt     = new JwtSecurityToken(head, payload);

            jwt.SigningKey = _signingKey;
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            return(encodedJwt);
        }
        /// <summary>
        /// 生成Shop授权JWT
        /// </summary>
        private string GenerateShopAuthorizationJWT(string sid, string userName, string shopId, List <Operation> opList)
        {
            var claims = new List <Claim>();

            claims.Add(new Claim("sid", sid));
            claims.Add(new Claim("shopId", shopId));

            string opData = string.Empty;

            if (opList != null && opList.Count > 0)
            {
                List <string> opStr = new List <string>();
                foreach (var item in opList)
                {
                    opStr.Add(item.Name);
                }
                opData = string.Join("_", opStr);
            }
            claims.Add(new Claim("opList", opData));

            ClaimsIdentity identity = new ClaimsIdentity(new GenericIdentity(userName, "TokenAuth"), claims);

            RsaSecurityKey     rsaSecurityKey = new RsaSecurityKey(AuthRSAUtils.Singleton.PrivateKeys);
            SigningCredentials creds          = new SigningCredentials(rsaSecurityKey, SecurityAlgorithms.RsaSha256Signature);
            var authTime  = DateTime.UtcNow;
            var expiresAt = authTime.AddMinutes(10);

            var token = new SecurityTokenDescriptor
            {
                Issuer             = GalaxyAuthExtensions.Issuer,
                Audience           = GalaxyAuthExtensions.Audience,
                SigningCredentials = creds,
                Subject            = identity,
                Expires            = expiresAt
            };

            return(new JwtSecurityTokenHandler().CreateEncodedJwt(token));
        }
        public string CreateAccessToken(UserDetails userDetails)
        {
            var privateKeyBytes = Convert.FromBase64String(PrivateKey.Replace("-----BEGIN PRIVATE KEY-----", "").Replace("-----END PRIVATE KEY-----", ""));
            var rsa             = RSA.Create();

            rsa.ImportPkcs8PrivateKey(privateKeyBytes, out _);

            var key = new RsaSecurityKey(rsa);

            var handler = new JwtSecurityTokenHandler();
            var now     = DateTime.UtcNow;

            JwtSecurityToken jwtSecurityToken = new JwtSecurityToken(
                issuer: "me",
                audience: "you",
                notBefore: now,
                expires: now.AddMinutes(5),
                signingCredentials: new SigningCredentials(key, SecurityAlgorithms.RsaSha256),
                claims: GetClaims(userDetails)
                );

            return(handler.WriteToken(jwtSecurityToken));
        }
Ejemplo n.º 21
0
        private void InitializeRsa()
        {
            RSA publicRsa = RSA.Create();

            var publicKeyXml = File.ReadAllText(_settings.RsaPublicKeyXML);

            publicRsa.FromXmlString(publicKeyXml);
            _issuerSigningKey = new RsaSecurityKey(publicRsa);


            if (string.IsNullOrWhiteSpace(_settings.RsaPrivateKeyXML))
            {
                return;
            }

            RSA privateRsa    = RSA.Create();
            var privateKeyXml = File.ReadAllText(_settings.RsaPrivateKeyXML);

            privateRsa.FromXmlString(privateKeyXml);
            var privateKey = new RsaSecurityKey(privateRsa);

            _signingCredentials = new SigningCredentials(privateKey, SecurityAlgorithms.RsaSha256);
        }
Ejemplo n.º 22
0
        public static String Create(UserDTO User, String issuer)
        {
            var key = new RsaSecurityKey(CryptoHelper.Instance.Rsa);

            var claims = new Claim[]
            {
                new Claim("username", User.Username),
                new Claim("mail", User.Mail),
                new Claim("sn", User.Sn),
                new Claim("gn", User.Gn),
                new Claim("cn", User.Cn),
                new Claim("account_type", User.AccountType)
            };
            var token = new JwtSecurityToken(
                issuer,
                issuer,
                claims,
                DateTime.UtcNow.AddMinutes(-1d),
                DateTime.UtcNow.AddHours(8),
                new SigningCredentials(key, SecurityAlgorithms.RsaSha256));

            return(new JwtSecurityTokenHandler().WriteToken(token));
        }
Ejemplo n.º 23
0
        private void AttachUserToContext(HttpContext context, string token)
        {
            var tokenHandler = new JwtSecurityTokenHandler();

            var rsa       = RSA.Create();
            var pemString = File.ReadAllText(Path.Combine(Directory.GetCurrentDirectory(), "Keys", _configuration["Jwt:PublicKey"]));

            rsa.ImportFromPem(pemString);
            var signingKey = new RsaSecurityKey(rsa);

            tokenHandler.ValidateToken(token, new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = signingKey,
                ValidateIssuer           = true,
                ValidateAudience         = true,
                ClockSkew = TimeSpan.Zero
            }, out var validatedToken);

            var jwtToken = (JwtSecurityToken)validatedToken;

            context.Items["UserToken"] = jwtToken;
        }
        Task <D2LSecurityToken> IPrivateKeyProvider.GetSigningCredentialsAsync()
        {
            RSAParameters privateKey;

            using (var csp = new RSACryptoServiceProvider(Constants.GENERATED_RSA_KEY_SIZE)
            {
                PersistKeyInCsp = false
            }) {
                privateKey = csp.ExportParameters(includePrivateParameters: true);
            }

            D2LSecurityToken result = m_d2lSecurityTokenFactory.Create(() => {
                var csp = new RSACryptoServiceProvider()
                {
                    PersistKeyInCsp = false
                };
                csp.ImportParameters(privateKey);
                var key = new RsaSecurityKey(csp);
                return(new Tuple <AsymmetricSecurityKey, IDisposable>(key, csp));
            });

            return(Task.FromResult(result));
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Retrieves the signing credential (override to load key from alternative locations)
        /// </summary>
        /// <returns>The signing credential</returns>
        protected virtual async Task <AzureKeyVaultSigningCredentials> GetSigningCredentialsAsync()
        {
            if (_keyVaultKeyExponent == null && _keyVaultKeyModulus == null)
            {
                var keyVaultClient = new KeyVaultClient(KeyVaultClientAuthenticationCallback);
                var keyBundle      = await keyVaultClient.GetKeyAsync(_options.KeyIdentifier).ConfigureAwait(false);

                _keyVaultKeyExponent = keyBundle.Key.E;
                _keyVaultKeyModulus  = keyBundle.Key.N;
            }

            var rsa = RSA.Create();

            rsa.ImportParameters(new RSAParameters
            {
                Exponent = _keyVaultKeyExponent,
                Modulus  = _keyVaultKeyModulus,
            });

            var securityKey = new RsaSecurityKey(rsa);

            return(new AzureKeyVaultSigningCredentials(securityKey, SecurityAlgorithms.Sha256Digest));
        }
Ejemplo n.º 26
0
        public static SecurityToken ValidateToken(string token, string validIssuer, string validAudience)
        {
            var publicKey = RSAKeyGenerator.GetPublicKeyAsXml();

            var test = RSA.Create();

            test.FromXmlString(publicKey);

            var securityKey = new RsaSecurityKey(test.ExportParameters(false));

            var handler          = new JwtSecurityTokenHandler();
            var validationParams = new TokenValidationParameters
            {
                RequireSignedTokens = true,
                IssuerSigningKey    = securityKey,
                ValidAudience       = validAudience,
                ValidIssuer         = validIssuer
            };

            var claimsPrincipal = handler.ValidateToken(token, validationParams, out var validatedToken);

            return(validatedToken);
        }
        public void Configure(AuthenticationBuilder builder)
        {
            RsaSecurityKey signingKey = CryptoHelper.CreateRsaSecurityKey();

            builder.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, jwt =>
            {
                jwt.Audience = "nop_api";
                jwt.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateActor  = false,
                    ValidateIssuer = false,
                    NameClaimType  = JwtClaimTypes.Name,
                    RoleClaimType  = JwtClaimTypes.Role,
                    // Uncomment this if you are using an certificate to sign your tokens.
                    // IssuerSigningKey = new X509SecurityKey(cert),
                    IssuerSigningKeyResolver = (string token, SecurityToken securityToken, string kid,
                                                TokenValidationParameters validationParameters) =>
                                               new List <RsaSecurityKey> {
                        signingKey
                    }
                };
            });
        }
Ejemplo n.º 28
0
        internal static SecurityKey CreateTestKey(string id = "Test")
        {
            var rsa = RSA.Create();

            if (rsa.KeySize < 2048)
            {
                rsa.KeySize = 2048;
                if (rsa.KeySize < 2048 && rsa is RSACryptoServiceProvider)
                {
                    rsa.Dispose();
                    rsa = new RSACryptoServiceProvider(2048);
                }
            }

            SecurityKey key;
            var         parameters = rsa.ExportParameters(includePrivateParameters: true);

            rsa.Dispose();

            key       = new RsaSecurityKey(parameters);
            key.KeyId = id;
            return(key);
        }
Ejemplo n.º 29
0
        private RsaSecurityKey GetRSAPrivateKey()
        {
            var physicalPath = PrivateKeySavePath.Replace("~", ServerRootPath);

            if (File.Exists(physicalPath))
            {
                var content = File.ReadAllText(physicalPath);
                privateKey = content;
                RSAParameters rp = ((FrameDLRObject)FrameDLRObject.CreateInstance(content, FrameDLRFlags.SensitiveCase)).ToModel <RSAParameters>(Encoding.Unicode);
                privateSK = new RsaSecurityKey(rp);
            }
            else
            {
                GlobalCommon.Logger.WriteLog(LoggerLevel.INFO, $"Rest验证读取PrivateKey文件失败,原因是目录文件{PrivateKeySavePath}不存在,请给出正确的秘钥钥文件路径(请在验证的Logic中重载PrivateKeySavePath的get方法),没有密钥会导致token生成失败甚至出现异常");
            }

            if (string.IsNullOrEmpty(privateKey))
            {
                GlobalCommon.Logger.WriteLog(LoggerLevel.INFO, $"Rest创建token密钥不存在,没有密钥会导致创建失败甚至出现异常,如果本API服务提供生成Token的功能则请不要重载PublicKeySavePath和PrivateKeySavePath两个属性的get方法或在get时返回空串,如果不是则请提供正确的PrivateKeySavePath路径值");
            }

            return(privateSK);
        }
Ejemplo n.º 30
0
        //public object GetAuthToken(Usuario user)
        //{
        //    var token = GenerateToken(user);

        //    return new
        //    {
        //        accessToken = token
        //    };
        //}

        public string GenerateToken(Usuario user)
        {
            ClaimsIdentity identity = new ClaimsIdentity(
                new GenericIdentity(user.NombreUsuario, "TokenAuth"),
                new[]
            {
                new Claim("NombreUsuario", user.NombreUsuario),
                new Claim("Contrasena", user.Contrasena),
            }
                );

            RsaSecurityKey Key = new RsaSecurityKey(RSAKeyHelper.GenerateKey());

            var securityToken = handler.CreateToken(new SecurityTokenDescriptor
            {
                Issuer             = user.NombreUsuario,
                Audience           = user.Contrasena,
                SigningCredentials = new SigningCredentials(Key, SecurityAlgorithms.RsaSha256Signature),
                Subject            = identity
            });

            return(handler.WriteToken(securityToken));
        }
Ejemplo n.º 31
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            var rsa = new RSACryptoServiceProvider(2048);
            var key = new RsaSecurityKey(rsa.ExportParameters(true));

            services.AddSingleton <RsaSecurityKey>(key);
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
            {
                options.TokenValidationParameters.ValidAudience    = "api";
                options.TokenValidationParameters.ValidIssuer      = "http://localhost:5000";
                options.TokenValidationParameters.IssuerSigningKey = key;
            });
            var optionsMonitor = services.BuildServiceProvider().GetService <IOptionsMonitor <JwtBearerOptions> >();
            var configuration  = optionsMonitor.Get(JwtBearerDefaults.AuthenticationScheme);
        }
Ejemplo n.º 32
0
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            RSACryptoServiceProvider myRSA = new RSACryptoServiceProvider(2048);
            RSAParameters publicKey = myRSA.ExportParameters(true);
            key = new RsaSecurityKey(publicKey);

            tokenOptions = new TokenAuthOptions
            {
                Audience = "http://localhost:5000/",
                Issuer = "http://localhost:5000/",
                SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256Signature)
            };

            services.AddSingleton<TokenAuthOptions>(tokenOptions);

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

            services.Configure<MvcJsonOptions>(options =>
            {
                if (_hostingEnv.IsDevelopment())
                {
                    options.SerializerSettings.Formatting = Formatting.Indented;
                }

                options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            });

            services.Configure<MvcOptions>(options =>
            {
                options.CacheProfiles.Add("IndexPage",
                    new CacheProfile
                    {
                        Duration = 60 * 60 * 24
                    });
            });

            services
                .AddIdentity<User, string>()
                .AddEF()
                .AddDefaultTokenProviders();

            services.AddCors();
            services.AddMvc();

            services.AddSingleton(_ => _configuration);

            services.AddEF();

            services.AddScoped<ITrainingService, TrainingService>();
            services.AddSingleton<IDateTimeService, DateTimeService>();
            services.AddScoped<ITrainingWordProvider, TrainingWordProvider>();
            services.AddScoped<ITrainingSessionFactory, TrainingSessionFactory>();
        }