Exemplo n.º 1
0
        private string GenerateJwtToken()
        {
            var claims      = new[] { new Claim(ClaimTypes.Name, "testuser") };
            var credentials = new SigningCredentials(SecurityKey, SecurityAlgorithms.HmacSha256);
            var token       = new JwtSecurityToken("FunctionalTestServer", "FunctionalTests", claims, expires: DateTime.Now.AddSeconds(5), signingCredentials: credentials);

            return(JwtTokenHandler.WriteToken(token));
        }
Exemplo n.º 2
0
    public static string GenerateJwtToken(string name)
    {
        if (string.IsNullOrEmpty(name))
        {
            throw new InvalidOperationException("Name is not specified.");
        }

        var claims      = new[] { new Claim(ClaimTypes.Name, name) };
        var credentials = new SigningCredentials(SecurityKey, SecurityAlgorithms.HmacSha256);
        var token       = new JwtSecurityToken("ExampleServer", "ExampleClients", claims, expires: DateTime.Now.AddSeconds(60), signingCredentials: credentials);

        return(JwtTokenHandler.WriteToken(token));
    }
Exemplo n.º 3
0
        public async Task <TokenResponse> CreateJwtTokenAsync([FromBody] TokenRequest request)
        {
            if (request == null)
            {
                throw new ArgumentException(nameof(TokenRequest));
            }
            TokenResponse response;

            try
            {
                DateTime          expireDateTimeUtc = DateTime.UtcNow.AddMilliseconds(QLAuthenticationOptions.TokenLifetimeMS);
                ClaimsIdentityBox identityBox       = await GetUserIdentityAsync(request.Login, request.Password, request.GrantType);

                if (identityBox != null)
                {
                    JwtSecurityToken token = JwtTokenHandler
                                             .CreateJwtSecurityToken(
                        subject: identityBox.ClaimsIdentity,
                        signingCredentials: QLAuthenticationOptions.GetSigningCredentials(),
                        audience: QLAuthenticationOptions.Audience,
                        issuer: QLAuthenticationOptions.Issuer,
                        expires: expireDateTimeUtc);
                    response = new TokenResponse(
                        token.Issuer, token.Audiences.ToList(), JwtTokenHandler.WriteToken(token), TokenType, identityBox.Sub, expireDateTimeUtc,
                        await ParseIdentityInfoFromIdentityClaimsAsync(identityBox.ClaimsIdentity.Claims.ToDictionary((item) => item.Type, (item) => item.Value)));
                }
                else
                {
                    throw new AuthorizationException("Login or password is incorrect.");
                }
            }
            catch (AuthorizationException)
            {
                Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                response            = null;
            }
            return(response);
        }