如何在ASP.NET CORE标识中配置JWT标记?

时间:2018-05-30 18:52:58

标签: asp.net-core asp.net-identity jwt

新的。花了很多时间。我正在尝试将JWT发行者添加到现有网站,以便我可以开发移动应用程序。我已将此添加到Startup:

services.AddAuthorization(auth =>
        {
            auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
                .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme‌​)
                .RequireAuthenticatedUser().Build());
        });
        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(options => {
            options.TokenValidationParameters =
                   new TokenValidationParameters
                   {
                       ClockSkew = TimeSpan.FromMinutes(5),
                       ValidateIssuer = false,
                       ValidateAudience = true,
                       ValidateLifetime = true,
                       ValidateIssuerSigningKey = true,
                       RequireSignedTokens = true,
                       RequireExpirationTime = true,

                       ValidIssuer = "https://URL",
                       ValidAudience = "https://URL",
                       IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("fbsghfdgjdgfjdbjgbjdbgjdbgjbdfjgbdfgjdbgjbfjdgbjdfgb"))
                   };

            options.Events = new JwtBearerEvents
            {
                OnAuthenticationFailed = context =>
                {
                    Console.WriteLine("OnAuthenticationFailed: " + context.Exception.Message);
                    return Task.CompletedTask;
                },
                OnTokenValidated = context =>
                {
                    Console.WriteLine("OnTokenValidated: " + context.SecurityToken);
                    return Task.CompletedTask;
                }
            };
        });

我在帐户控制器中有这个标记了。我对它应该如何工作有点困惑,我是否应该使用登录操作使用的相同登录逻辑,通过usermanager?或者只是检查用户名和密码并发回令牌?

    [HttpPost]
    [Route("/token3")]
    [AllowAnonymous]
    public async Task<IActionResult> Token3(TokenRequest model)
    {
        if (ModelState.IsValid)
        {
            var user = await UserManager.FindByEmailAsync(model.username);
            if (user != null)
            {

                var result = await _signInManager.CheckPasswordSignInAsync
                                (user, model.password, lockoutOnFailure: false);

                if (!result.Succeeded)
                {
                    return Unauthorized();
                }

                var claims = new[]
                {
                    new Claim(JwtRegisteredClaimNames.Sub, model.username),
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
                };

                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("fbsghfdgjdgfjdbjgbjdbgjdbgjbdfjgbdfgjdbgjbfjdgbjdfgb"));
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                var token = new JwtSecurityToken(
                    issuer: "https:/URL",
                    audience: "https://URL",
                    claims: claims,
                    expires: DateTime.Now.AddDays(7),
                    signingCredentials: creds);
                return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) });

                //return new JwtSecurityTokenHandler().WriteToken(token);
            }
        }
        return BadRequest("Could not verify username and password");
    }

现在,如果我在标题中使用用户名/密码调用它,则会返回一个令牌。但是,如果我尝试使用令牌,我会收到错误并重定向到登录。来自远程调试器的主要信息给了我:

Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler:Information:   Failed to validate the token <TOKEN>
IDX10503: Signature validation failed. Keys     tried: 'Microsoft.IdentityModel.Tokens.SymmetricSecurityKey
Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:Information: Authorization failed for user: (null).

我的测试行动:

    [HttpGet]
    [Route("/test")]
    [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
    public IActionResult Test()
    {
        return Ok("ok");
    }

0 个答案:

没有答案