JWT授权失败.net核心

时间:2020-06-21 00:59:51

标签: c# asp.net asp.net-mvc asp.net-core

我遇到一个问题,因为我总是会遇到授权失败的问题,所以我无法导航到仪表板,我已经在登录中使用了jwt并在声明用户名和角色中传递了所有数据,但是我无法检查这是哪条规则我停止了授权工作,我需要知道错误发生在哪里,这是我的登录方法

 [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {

                var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);


                if (result.Succeeded)
                {
                    _logger.LogInformation("User logged in.");
                    ApplicationUser user = await _userManager.FindByEmailAsync(model.Email);
                    
                    var tokenvalue = createToken(user);


                    if (tokenvalue != null)
                    {
                             HttpContext.Session.SetString("JWToken", tokenvalue);
                    }

                    return RedirectToAction("Index", "DashBoard");

                }
                if (result.RequiresTwoFactor)
                {
                    return RedirectToAction(nameof(LoginWith2fa), new { returnUrl, model.RememberMe });
                }
                if (result.IsLockedOut)
                {
                    _logger.LogWarning("User account locked out.");
                    return RedirectToAction(nameof(Lockout));
                }
                else
                {
                    ModelState.AddModelError(string.Empty, _localizer["Invalidloginattempt"]);
                    return View(model);
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

我的令牌代码是

     public String createToken(ApplicationUser user)
    {

        DateTime issuedAt = DateTime.UtcNow;
        //set the time when it expires
        DateTime expires = DateTime.UtcNow.AddDays(1);

        var tokenHandler = new JwtSecurityTokenHandler();


     ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[]
     {
            new Claim("UserName", user.UserName),
            new Claim("Id", user.Id),
            new Claim("Role", "Admin"),
    });

        var sec = _configuration["Jwt:Key"];
        var now = DateTime.UtcNow;
        var securityKey = new SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(sec));
        var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);

        var token = (JwtSecurityToken)
            tokenHandler.CreateJwtSecurityToken(issuer: _configuration["Jwt:Issuer"], audience: _configuration["Jwt:Audience"],
                subject: claimsIdentity, notBefore: issuedAt, expires: expires, signingCredentials: signingCredentials);
        var tokenString = tokenHandler.WriteToken(token);

        return tokenString;
    }

这是我的创业公司

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        var options = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
        app.UseRequestLocalization(options.Value);


        app.UseStaticFiles();
        app.UseCookiePolicy();

        app.UseSession();

        app.Use(async (context, next) =>
        {
            var JWToken = context.Session.GetString("JWToken");
            if (!string.IsNullOrEmpty(JWToken))
            {
                context.Request.Headers.Add("Authorization", "Bearer " + JWToken);
            }
            await next();
        });

        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "areas",
                pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });

    }

我的仪表板是

    [Authorize(Roles = "Admin,User")]
    public IActionResult Index()
    {
     
        return View();
    }

1 个答案:

答案 0 :(得分:1)

如果身份验证如您所说顺利进行,我认为问题似乎出在ClaimName角色上。 使用默认的声明配置,例如

Subject = new ClaimsIdentity(new Claim[] 
            {
                new Claim(ClaimTypes.Name, user.Id.ToString()),
                new Claim(ClaimTypes.Role, user.Role)
            }),

您使用的默认授权中间件和数据批注被配置为知道ClaimTypes.Role而不是自定义声明名称。

有关jwt auth的更多详细信息,请阅读:https://jasonwatmore.com/post/2019/10/16/aspnet-core-3-role-based-authorization-tutorial-with-example-api