Example #1
0
        private async Task GenerateToken(HttpContext context)
        {
            _logger?.LogDebug("Attempting to get identity.");

            // Try to get identity (sign in)
            var identity = await _userFinder.GetIdentity(context);

            if (identity == null)
            {
                _logger?.LogError("Invalid username or password.");

                context.Response.StatusCode  = 500;
                context.Response.ContentType = "application/json";
                await context.Response.WriteAsync(JsonConvert.SerializeObject(
                                                      new ApiErrorResult
                {
                    Type    = ErrorType.SignInFailed,
                    Message = "Invalid username or password."
                }, Formatting.Indented,
                                                      new JsonSerializerSettings
                {
                    ContractResolver =
                        new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
                }));

                return;
            }

            var now = DateTime.UtcNow;

            // Create clamins
            var claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
            };

            if (!string.IsNullOrEmpty(_options.Subject))
            {
                claims.Add(new Claim(JwtRegisteredClaimNames.Sub, _options.Subject));
            }
            claims.AddRange(identity.Claims);

            // Create the JWT and write it to a string
            _logger?.LogDebug("Attempting to generate jwt token.");

            var jwtHeader  = new JwtHeader(_options.SigningCredentials);
            var jwtPayload = new JwtPayload(
                issuer: _options.Issuer,
                audience: _options.Audience,
                claims: claims,
                notBefore: now,
                expires: now.Add(_options.Expiration),
                issuedAt: now);

            var jwt        = new JwtSecurityToken(jwtHeader, jwtPayload);
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            _logger?.LogDebug($"Jwt token generated successful.");

            var response = new AccessToken
            {
                scheme       = "Bearer",
                access_token = encodedJwt,
                expires_in   = (int)_options.Expiration.TotalSeconds
            };

            // Serialize and return the response
            context.Response.ContentType = "application/json";
            await context.Response.WriteAsync(JsonConvert.SerializeObject(response, Formatting.Indented,
                                                                          new JsonSerializerSettings
            {
                ContractResolver =
                    new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
            }));
        }