コード例 #1
0
        public async Task Invoke(HttpContext context, JwtOptions options)
        {
            if (TryGetUserFromRequest(context, out var user) && await _authenticator.TryAuthenticateUserAsync(user, out var identity))
            {
                var claims = new List <Claim>(identity.Claims)
                {
                    new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
                    new Claim(JwtRegisteredClaimNames.Jti, await options.IssuerOptions.JtiGenerator()),
                    new Claim(JwtRegisteredClaimNames.Iat, options.IssuerOptions.IssuedAt.ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64)
                };


                var jwt = new JwtSecurityToken(
                    issuer: options.IssuerOptions.Issuer,
                    audience: options.IssuerOptions.Audience,
                    claims: claims,
                    notBefore: options.IssuerOptions.NotBefore.LocalDateTime,
                    expires: options.IssuerOptions.Expiration.LocalDateTime,
                    signingCredentials: options.SigningCredentials
                    );

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

                var response = new TokenModel
                {
                    AccessToken = encodedJwt,
                    ExpiresIn   = (int)options.IssuerOptions.ValidFor.TotalSeconds
                };

                await context.WriteModelAsync(response);

                return;
            }

            await context.WriteModelAsync(new { message = "Impossible to authenticate the request" }, HttpStatusCode.Unauthorized);
        }