【问题标题】:JWT Authorization Failed .net coreJWT授权失败.net核心
【发布时间】:2020-06-21 00:59:51
【问题描述】:

我遇到了一个问题,我无法导航到仪表板,因为我总是得到授权失败我在登录时使用了 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();
    }

【问题讨论】:

  • 您可能想去 jwt.io 并使用它来解码您的令牌并查看声明。您可以使用 F12 开发人员工具从 auth 标头获取令牌。

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


【解决方案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

【讨论】:

    猜你喜欢
    • 2020-02-16
    • 1970-01-01
    • 2018-03-13
    • 2022-10-13
    • 2019-08-04
    • 2021-07-23
    • 2017-06-26
    • 1970-01-01
    • 2023-03-20
    相关资源
    最近更新 更多