简体   繁体   English

JWT 授权失败 .net 核心

[英]JWT Authorization Failed .net core

I am facing a problem which I can't navigate to the dashboard as I always got Authorization Failed i have used jwt in login and pass all data in claims username and role but I can't check which rules is it in case I stop Authorization it works I need to know where is the error happen this is my login method我遇到了一个问题,我无法导航到仪表板,因为我总是得到授权失败我在登录时使用了 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);
        }

my token code is我的令牌代码是

     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;
    }

and this my startup这是我的创业公司

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?}");
        });

    }

my dashboard is我的仪表板是

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

If the authentication goes well as you said, i think the problem seem to be the role ClaimName.如果身份验证如您所说顺利,我认为问题似乎出在角色 ClaimName 上。 Use the default claim configuration like使用默认声明配置,例如

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

The default authorization middleware and the data annotations that you are using are configured to know ClaimTypes.Role instead of custom claim names.您使用的默认授权中间件和数据注释被配置为知道 ClaimTypes.Role 而不是自定义声明名称。

For more details about jwt auth read this: https://jasonwatmore.com/post/2019/10/16/aspnet-core-3-role-based-authorization-tutorial-with-example-api有关 jwt 身份验证的更多详细信息,请阅读: https://jasonwatmore.com/post/2019/10/16/aspnet-core-3-role-based-authorization-tutorial-with-example-api

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM