Example #1
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);
        }