Esempio n. 1
0
        private string CreatToken(User user)
        {
            var handler = new JwtSecurityTokenHandler();

            string jti = Guid.NewGuid().ToString();

            var claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.Jti, jti),
                new Claim("userId", user.Id.ToString()),
                new Claim("role", user.Role.Code)
            };
            ClaimsIdentity identity = new ClaimsIdentity(new GenericIdentity(user.Code, "TokenAuth"), claims);

            var token = handler.CreateEncodedJwt(new SecurityTokenDescriptor
            {
                Issuer             = tokenOptions.Issuer,
                Audience           = tokenOptions.Audience,
                SigningCredentials = new SigningCredentials(tokenOptions.SecretKey, SecurityAlgorithms.HmacSha256),
                Expires            = DateTime.Now.Add(tokenOptions.Expiration),
                Subject            = identity
            });

            return(token);
        }
        public static string CreateJwtToken(DateTime expires, IEnumerable <Claim> claims)
        {
            //从配置文件中读取 jwt的issuer 发行者 audience 受众  expires 过期时间  key 加密证书
            var issuer   = "mecode";
            var audience = "mywebapp";
            var jti      = audience + expires.Millisecond + "postman_code";

            jti = MD5Util.GetMD5(jti);
            RSAUtil.TryGetKeyParameters(AppDomain.CurrentDomain.BaseDirectory, true, out RSAParameters rsaPrivatekey);
            //获取签名证书
            //包含用于生成数字签名的加密密钥
            var rsakey             = new RsaSecurityKey(rsaPrivatekey);
            var signingCredentials = new SigningCredentials(rsakey, SecurityAlgorithms.RsaSha256Signature);
            var handler            = new JwtSecurityTokenHandler();
            var claimsIdentity     = new ClaimsIdentity(claims, "JWTTest");

            claimsIdentity.AddClaim(new Claim("jti", jti));
            claimsIdentity.AddClaim(new Claim("now", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));

            var jwt = handler.CreateEncodedJwt(new SecurityTokenDescriptor()
            {
                Subject            = claimsIdentity, //声明的身份
                Audience           = audience,
                Expires            = expires,
                Issuer             = issuer,
                SigningCredentials = signingCredentials
            });

            return(jwt);
        }
Esempio n. 3
0
        public async Task When_Adding_Permission_Then_TicketId_Is_Returned()
        {
            var handler = new JwtSecurityTokenHandler();
            var idtoken = handler.CreateEncodedJwt(
                "test",
                "test",
                new ClaimsIdentity(new[] { new Claim("sub", "tester") }),
                null,
                null,
                null,
                null);
            const string resourceSetId          = "resource_set_id";
            var          addPermissionParameter = new PermissionRequest
            {
                ResourceSetId = resourceSetId,
                Scopes        = new[] { "scope" },
                IdToken       = idtoken
            };
            var resources = new[] { new ResourceSet {
                                        Id = resourceSetId, Scopes = new[] { "scope" }
                                    } };

            InitializeFakeObjects(resources);
            _ticketStoreStub.Setup(r => r.Add(It.IsAny <Ticket>(), It.IsAny <CancellationToken>())).ReturnsAsync(true);

            var ticket = (await _requestPermissionHandler
                          .Execute("tester", CancellationToken.None, addPermissionParameter)
                          .ConfigureAwait(false) as Option <Ticket> .Result) !.Item;

            Assert.NotEmpty(ticket.Requester);
        }
        public async Task WhenResourceSetDoesNotExistThenReturnsNotAuthorized()
        {
            var handler    = new JwtSecurityTokenHandler();
            var jsonWebKey = await _inMemoryJwksRepository.GetDefaultSigningKey().ConfigureAwait(false);

            var token = handler.CreateEncodedJwt(
                "test",
                "test",
                new ClaimsIdentity(),
                null,
                null,
                null,
                jsonWebKey);
            var ticket = new Ticket {
                Lines = new[] { new TicketLine {
                                    ResourceSetId = "resource_set_id"
                                } }
            };

            _resourceSetRepositoryStub
            .Setup(r => r.Get(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <CancellationToken>()))
            .Returns(() => Task.FromResult((ResourceSet)null));

            var result = await _authorizationPolicyValidator.IsAuthorized(
                ticket,
                new Client { ClientId = "client_id" },
                new ClaimTokenParameter { Format = UmaConstants.IdTokenType, Token = token },
                CancellationToken.None)
                         .ConfigureAwait(false);

            Assert.Equal(AuthorizationPolicyResultKind.NotAuthorized, result.Result);
        }
        private static string CreateJws(string id, string audience, string issuer,
                                        DateTime expires, DateTime issuedAt, DateTime notBefore,
                                        string module, string device, string iothub,
                                        X509SecurityKey issuerSigningKey)
        {
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Audience           = audience,
                Expires            = expires,
                IssuedAt           = issuedAt,
                Issuer             = issuer,
                NotBefore          = notBefore,
                SigningCredentials = new SigningCredentials(issuerSigningKey, SecurityAlgorithms.RsaSha256)
            };

            tokenDescriptor.Claims = new Dictionary <string, object>
            {
                ["jti"]    = id,
                ["module"] = module,
                ["device"] = device,
                ["iothub"] = iothub
            };

            return(jwtHandler.CreateEncodedJwt(tokenDescriptor));
        }
Esempio n. 6
0
        public async Task <string> GetToken(UserLoginRequest loginDataDto)
        {
            var user = await _userManager.FindByEmailAsync(loginDataDto.Email);

            if (user == null)
            {
                return(null);
            }

            bool passwordCorrect = await _userManager.CheckPasswordAsync(user, loginDataDto.Password);

            if (!passwordCorrect)
            {
                return(null);
            }

            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_configuration["JwtToken:Key"]);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.NameIdentifier, user.Id)
                }),
                Expires = DateTime.UtcNow.AddMinutes(
                    _configuration.GetValue <int>("JwtToken:ExpirationMinutes")),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key),
                                                            SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateEncodedJwt(tokenDescriptor);

            return(token);
        }
Esempio n. 7
0
        private async Task <(string clientSecret, DateTimeOffset expiresAt)> GenerateNewSecretAsync(
            [NotNull] AppleGenerateClientSecretContext context)
        {
            var expiresAt = _clock.UtcNow.Add(context.Options.ClientSecretExpiresAfter).UtcDateTime;
            var subject   = new Claim("sub", context.Options.ClientId);

            _logger.LogDebug(
                "Generating new client secret for subject {Subject} that will expire at {ExpiresAt}.",
                subject.Value,
                expiresAt);

            var tokenDescriptor = new SecurityTokenDescriptor()
            {
                Audience = context.Options.TokenAudience,
                Expires  = expiresAt,
                Issuer   = context.Options.TeamId,
                Subject  = new ClaimsIdentity(new[] { subject }),
            };

            byte[] keyBlob = await _keyStore.LoadPrivateKeyAsync(context);

            string clientSecret;

            using (var algorithm = CreateAlgorithm(keyBlob))
            {
                tokenDescriptor.SigningCredentials = CreateSigningCredentials(context.Options.KeyId !, algorithm);

                clientSecret = _tokenHandler.CreateEncodedJwt(tokenDescriptor);
            }

            _logger.LogTrace("Generated new client secret with value {ClientSecret}.", clientSecret);

            return(clientSecret, expiresAt);
        }
Esempio n. 8
0
        private dynamic CreateToken(Account user, string audience)
        {
            ClaimsIdentity cliaims = new ClaimsIdentity(new Claim []
            {
                new Claim("uid", user.Id),
                new Claim("uname", user.DisplayName)
            });
            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(JwtSettings.Key);
            var authTime        = DateTime.UtcNow;
            var expiresAt       = authTime.AddDays(JwtSettings.Expires);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = cliaims,
                Issuer             = JwtSettings.Issuer,
                Audience           = audience,
                Expires            = expiresAt,
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };

            return(new
            {
                access_token = tokenHandler.CreateEncodedJwt(tokenDescriptor),
                token_type = "Bearer",
                profile = new
                {
                    auth_time = new DateTimeOffset(authTime).ToUnixTimeSeconds(),
                    expires_at = new DateTimeOffset(expiresAt).ToUnixTimeSeconds()
                }
            });
        }
Esempio n. 9
0
        /// <summary>
        /// 生成一个新的 Token
        /// </summary>
        /// <param name="user">用户信息实体</param>
        /// <param name="expire">token 过期时间</param>
        /// <param name="audience">Token 接收者</param>
        /// <returns></returns>
        private string CreateToken(dynamic user, DateTime expire, string audience)
        {
            var    handler = new JwtSecurityTokenHandler();
            string jti     = audience + user.USER + new TimeSpan(expire.Ticks).TotalMilliseconds;

            jti = jti.GetMd5(); // Jwt 的一个参数,用来标识 Token
            var claims = new[]
            {
                new Claim(ClaimTypes.Role, string.Empty),                 // 添加角色信息
                new Claim(ClaimTypes.NameIdentifier, user.ID.ToString()), // 用户 Id ClaimValueTypes.Integer32),
                new Claim("jti", jti, ClaimValueTypes.String),            // jti,用来标识 token
                new Claim("userInfo", JsonHelper.ToJson(user))
            };
            ClaimsIdentity identity = new ClaimsIdentity(new GenericIdentity(user.USER, "TokenAuth"), claims);
            var            token    = handler.CreateEncodedJwt(new SecurityTokenDescriptor
            {
                Issuer             = ApplicationConfig.Issuer, // 指定 Token 签发者,也就是这个签发服务器的名称
                Audience           = audience,                 // 指定 Token 接收者
                SigningCredentials = _tokenOptions.Credentials,
                Subject            = identity,
                Expires            = expire
            });

            return(token);
        }
Esempio n. 10
0
        public string GenerateToken()
        {
            var signingCredentials = new SigningCredentials(appSettings.TokenSigningKey, SecurityAlgorithms.HmacSha256);
            var ec = new EncryptingCredentials(appSettings.TokenEncryptionKey, JwtConstants.DirectKeyUseAlg, SecurityAlgorithms.Aes256CbcHmacSha512);

            var handler = new JwtSecurityTokenHandler();

            IList <Claim> claims = new List <Claim>();

            claims.Add(new Claim(Constants.Claims.ObjectId, ObjectId, ClaimValueTypes.String, appSettings.IdTokenIssuer));
            claims.Add(new Claim(Constants.Claims.TransactionReference, TransactionReference, ClaimValueTypes.String, appSettings.IdTokenIssuer));
            claims.Add(new Claim(Constants.Claims.IsVerified, IsVerified.ToString(), ClaimValueTypes.String, appSettings.IdTokenIssuer));
            claims.Add(new Claim(Constants.Claims.Message, Message ?? string.Empty, ClaimValueTypes.String, appSettings.IdTokenIssuer));

            var jwt = handler.CreateEncodedJwt(
                appSettings.IdTokenIssuer,
                appSettings.IdTokenAudience,
                new ClaimsIdentity(claims),
                DateTime.Now,
                DateTime.Now.AddDays(1),
                DateTime.Now,
                signingCredentials,
                ec);

            return(jwt);
        }
Esempio n. 11
0
        public AuthDto GenerateToken(User user)
        {
            var claims = new[]
            {
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Name, user.FirstName),
                new Claim(ClaimTypes.Email, user.Email),
                new Claim("mobileNumber", user.MobileNumber),
                new Claim("points", user.Points.ToString()),
                new Claim("isSubscribedMail", user.IsSubscribedMail.ToString()),
                new Claim("isSubscribedSms", user.IsSubscribedSms.ToString())
            };
            var appKey = Encoding.UTF8.GetBytes(_configuration.GetSection("AppSetting:Token").Value);

            var key = new SymmetricSecurityKey(appKey);

            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

            var tokenDescriptor = new SecurityTokenDescriptor()
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.Now.AddHours(5),
                SigningCredentials = creds
            };
            var tokenHandler = new JwtSecurityTokenHandler();
            var token        = tokenHandler.CreateEncodedJwt(tokenDescriptor);

            return(new AuthDto()
            {
                Token = token
            });
        }
Esempio n. 12
0
        public void InboundFilterTest()
        {
            var handler = new JwtSecurityTokenHandler();

            handler.OutboundClaimTypeMap.Clear();
            var claims = ClaimSets.DefaultClaims;

            string encodedJwt = handler.CreateEncodedJwt(Default.AsymmetricSignSecurityTokenDescriptor(claims));

            handler.InboundClaimTypeMap.Clear();
            handler.InboundClaimFilter.Add("aud");
            handler.InboundClaimFilter.Add("exp");
            handler.InboundClaimFilter.Add("iat");
            handler.InboundClaimFilter.Add("iss");
            handler.InboundClaimFilter.Add("nbf");

            SecurityToken   validatedToken;
            ClaimsPrincipal claimsPrincipal = handler.ValidateToken(encodedJwt, Default.AsymmetricSignTokenValidationParameters, out validatedToken);
            var             context         = new CompareContext {
                IgnoreType = true
            };

            IdentityComparer.AreEqual(claimsPrincipal.Claims, claims, context);
            TestUtilities.AssertFailIfErrors(context.Diffs);
        }
Esempio n. 13
0
        private string GetToken(User user)
        {
            var symmetricKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_options.SecretKey));

            var claimsIdentity = new ClaimsIdentity(new List <Claim>()
            {
                new Claim(ClaimTypes.Name, user.UserName),
                new Claim(ClaimTypes.Email, user.Email),
                new Claim(ClaimTypes.NameIdentifier, user.Id)
            });

            var tokenDescriptor = new SecurityTokenDescriptor()
            {
                Audience           = _options.Audience,
                Issuer             = _options.Issuer,
                IssuedAt           = DateTime.UtcNow,
                NotBefore          = DateTime.UtcNow,
                Subject            = claimsIdentity,
                Expires            = DateTime.UtcNow.AddDays(_options.ExpirationDays),
                SigningCredentials = new SigningCredentials(symmetricKey, SecurityAlgorithms.HmacSha256)
            };

            var handler = new JwtSecurityTokenHandler();

            return(handler.CreateEncodedJwt(tokenDescriptor));
        }
        private string GetJwt(OAuth2Params oauthParams)
        {
            _fileReader.Open(oauthParams.CertificateFilePath);
            var pemReader = new PemReader(_fileReader.Reader);
            var keyPair   = (AsymmetricCipherKeyPair)pemReader.ReadObject();
            var rsaParams = DotNetUtilities.ToRSAParameters((RsaPrivateCrtKeyParameters)keyPair.Private);

            var rsa = new RSACryptoServiceProvider(2048);

            rsa.ImportParameters(rsaParams);

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

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[]
                {
                    new Claim("scope", oauthParams.ScopesAsString())
                }),
                Issuer             = oauthParams.ClientId,
                Audience           = oauthParams.Audience,
                Expires            = now.AddHours(1),
                SigningCredentials = new SigningCredentials(new RsaSecurityKey(rsa), "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256")
            };

            return(tokenHandler.CreateEncodedJwt(tokenDescriptor));
        }
Esempio n. 15
0
        public void TestJwtTokenCreationAndValidation()
        {
            IdentityModelEventSource.ShowPII = true;
            var handler = new JwtSecurityTokenHandler();

            handler.InboundClaimTypeMap.Clear();
            var jwt      = handler.CreateEncodedJwt(Default.AsymmetricSignSecurityTokenDescriptor(null));
            var jwtToken = new JwtSecurityToken(jwt)
            {
                SigningKey = Default.AsymmetricSigningKey
            };
            SecurityToken token = null;

            handler.ValidateToken(jwt, Default.AsymmetricSignTokenValidationParameters, out token);
            var context = new CompareContext
            {
                PropertiesToIgnoreWhenComparing = new Dictionary <Type, List <string> >
                {
                    { typeof(JwtHeader), new List <string> {
                          "Item"
                      } },
                    { typeof(JwtPayload), new List <string> {
                          "Item"
                      } }
                }
            };

            if (!IdentityComparer.AreJwtSecurityTokensEqual(jwtToken, token as JwtSecurityToken, context))
            {
                TestUtilities.AssertFailIfErrors("TestJwtTokenCreationAndValidation", context.Diffs);
            }
        }
Esempio n. 16
0
        public IActionResult Authenticate(UserLoginModel model)
        {
            var key                     = Encoding.ASCII.GetBytes(_appSetting.Jwt.Secret);
            var tokenHandler            = new JwtSecurityTokenHandler();
            var securityTokenDescriptor = new SecurityTokenDescriptor()
            {
                Audience = _appSetting.Jwt.Audience,
                Subject  = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.NameIdentifier, model.UserName)
                }),
                Expires            = DateTime.Now.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256),
                Issuer             = _appSetting.Jwt.Issuer,
                IssuedAt           = DateTime.Now
            };
            //var token = tokenHandler.CreateToken(securityTokenDescriptor);
            //var tokenString = tokenHandler.WriteToken(token);

            var tokenString2 = tokenHandler.WriteToken(tokenHandler.CreateJwtSecurityToken(securityTokenDescriptor));


            var tokenString3 = tokenHandler.CreateEncodedJwt(securityTokenDescriptor);

            return(Ok(new { token = tokenString2 }));
        }
Esempio n. 17
0
        /// <summary>
        /// 创建Jwt令牌
        /// </summary>
        /// <param name="expire">过期时间</param>
        /// <param name="audience">接收jwt者</param>
        /// <param name="credentials">签名证书</param>
        public static string CreateJwtToken(Identity identity, DateTime expire, string audience, SigningCredentials credentials)
        {
            var    handler = new JwtSecurityTokenHandler();
            string jti     = audience + identity.Name + expire.Millisecond;

            jti = MD5Util.GetMD5(jti); // Jwt 的一个参数,用来标识 Token
            var claims = new[]
            {
                new Claim(ClaimTypes.Role, string.Empty),                     // 添加角色信息
                new Claim(ClaimTypes.NameIdentifier, identity.Id.ToString()), // 用户 Id
                new Claim("jti", jti, ClaimValueTypes.String)                 // jti,用来标识 token
            };
            //一个基于声明的标识
            var cid   = new ClaimsIdentity(new GenericIdentity(identity.Name, "TokenAuth"), claims);
            var token = handler.CreateEncodedJwt(new SecurityTokenDescriptor
            {                                      //包含用于创建安全令牌的一些信息。
                Issuer             = "TestIssuer", // 指定 Token 签发者,也就是这个签发服务器的名称
                Audience           = audience,     // 指定 Token 接收者
                SigningCredentials = credentials,  //签名证书
                Subject            = cid,          //该JWT所面向的用户,是否使用是可选的
                Expires            = expire        //jwt 过期时间
            });

            return(token);
        }
Esempio n. 18
0
        public async Task WhenTokenIsForDifferentAudienceThenTokenIsNotValid()
        {
            var handler = new JwtSecurityTokenHandler();

            using var rsa = new RSACryptoServiceProvider(2048);
            var jwk           = rsa.CreateSignatureJwk("1", true);
            var keyset        = new JsonWebKeySet().AddKey(rsa.CreateSignatureJwk("1", false));
            var jwksStoreMock = new Mock <IJwksStore>();

            jwksStoreMock.Setup(x => x.GetSigningKey(jwk.Alg, It.IsAny <CancellationToken>()))
            .ReturnsAsync(new SigningCredentials(jwk, jwk.Alg));
            jwksStoreMock.Setup(x => x.GetPublicKeys(It.IsAny <CancellationToken>())).ReturnsAsync(keyset);
            var token = handler.CreateEncodedJwt(
                "http://localhost",
                "test",
                new ClaimsIdentity(new[] { new Claim("sub", "tester"), }),
                DateTime.UtcNow,
                DateTime.UtcNow.AddYears(1),
                DateTime.UtcNow,
                new SigningCredentials(jwk, jwk.Alg));
            var grantedToken = new GrantedToken
            {
                ClientId       = "fake",
                AccessToken    = token,
                ExpiresIn      = 10000,
                CreateDateTime = DateTimeOffset.UtcNow
            };
            var result = await grantedToken.CheckGrantedToken(jwksStoreMock.Object).ConfigureAwait(false);

            Assert.False(result.IsValid);
        }
        public async Task When_Policy_Does_Not_Exist_Then_RequestSubmitted_Is_Returned()
        {
            var handler = new JwtSecurityTokenHandler();
            var key     = await _inMemoryJwksRepository.GetDefaultSigningKey().ConfigureAwait(false);

            var token = handler.CreateEncodedJwt(
                "test",
                "test",
                new ClaimsIdentity(new[] { new Claim("test", "test") }),
                null,
                DateTime.UtcNow.AddYears(1),
                DateTime.UtcNow,
                key);
            var ticket = new Ticket {
                Lines = new[] { new TicketLine {
                                    ResourceSetId = "1"
                                } }
            };
            var resourceSet = new[] { new ResourceSet {
                                          Id = "1"
                                      } };

            _resourceSetRepositoryStub.Setup(r => r.Get(It.IsAny <CancellationToken>(), It.IsAny <string[]>()))
            .ReturnsAsync(resourceSet);

            var result = await _authorizationPolicyValidator.IsAuthorized(
                ticket,
                new Client { ClientId = "client_id" },
                new ClaimTokenParameter { Format = "access_token", Token = token },
                CancellationToken.None)
                         .ConfigureAwait(false);

            Assert.Equal(AuthorizationPolicyResultKind.RequestSubmitted, result.Result);
        }
Esempio n. 20
0
        private string getToken(StudentUser user)
        {
            if (user == null)
            {
                throw new ArgumentNullException("Cannot Generate Token on a null user");
            }

            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_appSettings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim("userId", user.Id),
                    new Claim("sid", user.StudentId.ToString()),
                    new Claim(ClaimTypes.Role, "Student")
                }),
                Expires            = DateTime.UtcNow.AddHours(1),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key),
                                                            SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateEncodedJwt(tokenDescriptor);

            return(token);
        }
Esempio n. 21
0
        public IActionResult Login([FromBody] Login model)
        {
            var user = _userService.GetUser(model.Email, model.Password);

            if (user == null)
            {
                return(BadRequest(new ErrorResponse(new List <Error> {
                    new Error("User cannot be verified")
                })));
            }
            var key             = Encoding.UTF8.GetBytes(_appSettings.Secret);
            var tokenHandler    = new JwtSecurityTokenHandler();
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, user.Id.ToString())
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateEncodedJwt(tokenDescriptor);

            return(Ok(new
            {
                User = user,
                Token = token
            }));
        }
Esempio n. 22
0
        internal string GetToken(AuthInfo authInfo)
        {
            var handler   = new JwtSecurityTokenHandler();
            var signCreds = new SigningCredentials(new SymmetricSecurityKey(authInfo.SecureKey), SecurityAlgorithms.HmacSha256);
            var identity  = GetIdentity();
            var token     = handler.CreateEncodedJwt(authInfo.Issuer, authInfo.Audience, identity, notBefore: DateTime.Now, expires: null, issuedAt: DateTime.Now, signCreds);

            return(token);
        }
        When_Generating_AuthorizationResponse_With_AccessToken_And_ThereIs_A_GrantedToken_Then_Token_Is_Added_To_The_Parameters()
        {
            const string clientId               = "clientId";
            const string scope                  = "openid";
            var          claimsIdentity         = new ClaimsIdentity("fake");
            var          claimsPrincipal        = new ClaimsPrincipal(claimsIdentity);
            var          authorizationParameter = new AuthorizationParameter
            {
                ResponseType = ResponseTypeNames.Token,
                ClientId     = clientId,
                Scope        = scope
            };
            var       handler           = new JwtSecurityTokenHandler();
            var       issuedAt          = DateTime.UtcNow;
            const int expiresIn         = 20000;
            var       defaultSigningKey = await _inMemoryJwksRepository.GetDefaultSigningKey().ConfigureAwait(false);

            var accessToken = handler.CreateEncodedJwt(
                "test",
                clientId,
                claimsIdentity,
                null,
                issuedAt.AddSeconds(expiresIn),
                issuedAt,
                defaultSigningKey);
            var grantedToken = new GrantedToken
            {
                ClientId       = clientId,
                AccessToken    = accessToken,
                CreateDateTime = issuedAt,
                ExpiresIn      = expiresIn
            };

            _tokenStore.Setup(
                x => x.GetToken(
                    It.IsAny <string>(),
                    It.IsAny <string>(),
                    It.IsAny <JwtPayload>(),
                    It.IsAny <JwtPayload>(),
                    It.IsAny <CancellationToken>()))
            .ReturnsAsync(grantedToken);

            var actionResult = await _generateAuthorizationResponse.Generate(
                new EndpointResult { RedirectInstruction = new RedirectInstruction() },
                authorizationParameter,
                claimsPrincipal,
                new Client { ClientId = clientId },
                "test",
                CancellationToken.None)
                               .ConfigureAwait(false);

            Assert.Equal(
                grantedToken.AccessToken,
                actionResult.RedirectInstruction !.Parameters
                .First(x => x.Name == StandardAuthorizationResponseNames.AccessTokenName)
                .Value);
        }
Esempio n. 24
0
        public string Generate()
        {
            var tokenHandler = new JwtSecurityTokenHandler();

            byte[] key        = Encoding.ASCII.GetBytes(secret);
            var    descriptor = CreateDescriptor(key);

            return(tokenHandler.CreateEncodedJwt(descriptor));
        }
Esempio n. 25
0
        public async Task <string> CreateJwt(JwtEnpoint endpoint, string issuer, string audience, ClaimsIdentity subject, DateTime?notBefore, DateTime?expires, DateTime?issuedAt)
        {
            //生成生成时用到的签名密钥
            var signingCredentials = await _jwtGenerateCreateSignKeyService.Generate(endpoint, endpoint.CreateSignKeyType, endpoint.CreateSignKeyConfiguration);

            //生成Jwt字符串
            JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();

            return(handler.CreateEncodedJwt(issuer, audience, subject, notBefore, expires, issuedAt, signingCredentials));
        }
        public async Task When_AuthorizationPolicy_Is_Correct_Then_Authorized_Is_Returned()
        {
            var handler = new JwtSecurityTokenHandler();
            var key     = await _inMemoryJwksRepository.GetDefaultSigningKey().ConfigureAwait(false);

            var token = handler.CreateEncodedJwt(
                "test",
                "test",
                new ClaimsIdentity(new[] { new Claim("test", "test") }),
                null,
                DateTime.UtcNow.AddYears(1),
                DateTime.UtcNow,
                key);

            _clientStoreStub.Setup(x => x.GetById(It.IsAny <string>(), It.IsAny <CancellationToken>()))
            .Returns <string, CancellationToken>(
                (s, c) => Task.FromResult(new Client {
                ClientId = s
            }));

            var ticket = new Ticket {
                Lines = new[] { new TicketLine {
                                    ResourceSetId = "1"
                                } }
            };
            var resourceSet = new[]
            {
                new ResourceSet
                {
                    Id = "1",
                    AuthorizationPolicies = new[]
                    {
                        new PolicyRule
                        {
                            ClientIdsAllowed = new[] { "client_id" },
                            Claims           = new[] { new ClaimData {
                                                           Type = "test", Value = "test"
                                                       } }
                        }
                    }
                }
            };

            _resourceSetRepositoryStub.Setup(r => r.Get(It.IsAny <CancellationToken>(), It.IsAny <string[]>()))
            .ReturnsAsync(resourceSet);

            var result = await _authorizationPolicyValidator.IsAuthorized(
                ticket,
                new Client { ClientId = "client_id" },
                new ClaimTokenParameter { Token = token, Format = UmaConstants.IdTokenType },
                CancellationToken.None)
                         .ConfigureAwait(false);

            Assert.Equal(AuthorizationPolicyResultKind.Authorized, result.Result);
        }
Esempio n. 27
0
        private async Task GenerateToken(HttpContext context)
        {
            var appUser = await _accountService.FindUserAsync(context.Request.Form["userName"], context.Request.Form["password"]);

            if (appUser == null)
            {
                context.Response.StatusCode  = 200;
                context.Response.ContentType = "application/json";
                var result = new
                { token_result = "fail",
                  msg          = "Invalid username or password" };
                await context.Response.WriteAsync(JsonConvert.SerializeObject(result, new JsonSerializerSettings {
                    Formatting = Formatting.Indented, ContractResolver = new CamelCasePropertyNamesContractResolver()
                }));
            }
            else
            {
                var identity = await _accountService.GetClaimsPrincipleForUser(appUser);

                var userData = _accountService.GetUserInfo(identity.FindFirstValue(ClaimTypes.NameIdentifier)).Result;

                var now = DateTime.UtcNow;

                var _issuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_options.HmacSecretKey));

                //Generate Token
                var jwtHandler = new JwtSecurityTokenHandler();
                var jws        = jwtHandler.CreateEncodedJwt(new SecurityTokenDescriptor
                {
                    Issuer             = _options.Issuer,
                    IssuedAt           = now,
                    NotBefore          = now,
                    Audience           = _options.Audience,
                    SigningCredentials = new SigningCredentials(_issuerSigningKey, SecurityAlgorithms.HmacSha256),
                    Subject            = ((ClaimsIdentity)identity.Identity),
                    Expires            = now.Add(_options.ExpiresSpan)
                });

                var response = new
                {
                    access_token = jws,
                    token_result = "success",
                    user         = userData,
                    expires_in   = (int)_options.ExpiresSpan.TotalMinutes
                };
                // Serialize and return the response
                context.Response.ContentType = "application/json";
                await context.Response.WriteAsync(JsonConvert.SerializeObject(response, new JsonSerializerSettings {
                    Formatting = Formatting.Indented, ContractResolver = new CamelCasePropertyNamesContractResolver()
                }));

                //return new OkObjectResult(response);
            }
        }
Esempio n. 28
0
 public string CreateEncoded(string userName)
 {
     return(_tokenHandler.CreateEncodedJwt(new SecurityTokenDescriptor
     {
         Subject = new ClaimsIdentity(new GenericIdentity(userName)),
         Expires = DateTime.UtcNow.AddDays(_settings.TokenExpiration),
         SigningCredentials = new SigningCredentials(_settings.SecurityKey, SecurityAlgorithms.HmacSha256Signature),
         Audience = _settings.Audience,
         Issuer = _settings.Issuer
     }));
 }
Esempio n. 29
0
        private string GetAuthState()
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var securityKey  = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_settings.ClientSecret));

            return(tokenHandler.CreateEncodedJwt(new SecurityTokenDescriptor
            {
                Expires = DateTime.UtcNow + TimeSpan.FromMinutes(10),
                SigningCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature)
            }));
        }
Esempio n. 30
0
        public static string CreateToken <TUser>(TUser user, IEnumerable <Claim> userClaims, SecurityOptions security, PublicApiOptions api) where TUser : IUserIdProvider
        {
            var now     = DateTimeOffset.Now;
            var expires = now.AddSeconds(security.Tokens.TimeToLiveSeconds);

            /*
             *  See: https://tools.ietf.org/html/rfc7519#section-4.1
             *  All claims are optional, but since our JSON conventions elide null values,
             *  We need to ensure any optional claims are emitted as empty strings.
             */

            // JWT.io claims:
            var sub = user.Id ?? string.Empty;
            var jti = $"{Guid.NewGuid()}";
            var iat = now.ToUnixTimeSeconds().ToString();
            var exp = expires.ToUnixTimeSeconds().ToString();
            var nbf = now.ToUnixTimeSeconds().ToString();
            var iss = security.Tokens?.Issuer ?? string.Empty;
            var aud = security.Tokens?.Audience ?? string.Empty;

            var claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub, sub, ClaimValueTypes.String),
                new Claim(JwtRegisteredClaimNames.Jti, jti, ClaimValueTypes.String),
                new Claim(JwtRegisteredClaimNames.Iat, iat, ClaimValueTypes.Integer64),
                new Claim(JwtRegisteredClaimNames.Nbf, nbf, ClaimValueTypes.Integer64),
                new Claim(JwtRegisteredClaimNames.Exp, exp, ClaimValueTypes.Integer64)
            };

            claims.AddRange(userClaims);

            claims.TryAddClaim(security.Claims.ApplicationIdClaim, api.ApiVersion);
            claims.TryAddClaim(security.Claims.ApplicationNameClaim, api.ApiName);

            _signing    = _signing ?? BuildSigningCredentials(security);
            _encrypting = _encrypting ?? BuildEncryptingCredentials(security);

            var handler = new JwtSecurityTokenHandler();

            if (security.Tokens.Encrypt)
            {
                var descriptor = new SecurityTokenDescriptor
                {
                    Audience = aud,
                    Issuer   = iss,
                    Subject  = new ClaimsIdentity(claims),
                    EncryptingCredentials = _encrypting
                };

                return(handler.CreateEncodedJwt(descriptor));
            }

            return(handler.WriteToken(new JwtSecurityToken(iss, aud, claims, now.UtcDateTime, expires.UtcDateTime, _signing)));
        }