简体   繁体   English

控制器ASP.net Core 2.1中的Jwt角色身份验证

[英]Jwt Role authentication in controller ASP.net core 2.1

I am writing a cooperative web API with asp.net core 2.1 using postgresql as db. 我正在使用postgresql作为db用asp.net core 2.1编写协作式Web API。 after the user sign in user is given a JWT token that will be use for the front end side authentication (Front end will be implemented with angular 2+). 在用户登录后,为用户提供了JWT令牌,该令牌将用于前端侧身份验证(前端将使用angular 2+实现)。 I want to store the user role in JWT and when the user sign In, user role will be read from the db and it will be store (authorize Role) So I will write Roles on the controller method. 我想将用户角色存储在JWT中,当用户登录时,将从数据库读取用户角色并将其存储(授权角色),因此我将在控制器方法上编写角色。 I want to use the Authorize attribute. 我想使用Authorize属性。

   // Auth Controller
    [HttpGet("GetUsers")]
    [Authorize(Roles = "admin")]
    public ActionResult GetUsers()
    {
        var users = _authRepository.GetUsers();
        return Ok(users);
    }

and Repository.cs 和Repository.cs

public List<User> GetUsers()
{
    var users = _context.Users.ToList();
    return users;
}

Question: Do I need to write a middleware to read each user role from JWT and a put that role to the Identity Principal Claims? 问题:我是否需要编写中间件来从JWT读取每个用户角色,并将该角色放入身份委托人声明中? Please share your experince. 请分享您的经验。 I will be glad to know your approch. 我很高兴知道您的要求。

I am glad I solved this question I am sharing the complete middleware. 我很高兴解决了这个问题,我正在共享完整的中间件。 In every request by the user the middleware will check the userRole that is embadded in JWT token middle point xxxx.UserInformation.yyyyy we will take that user information. 在用户的每个请求中,中间件都将检查嵌入在JWT令牌中间点xxxx.UserInformation.yyyyy我们将获取该用户信息。

public class AuthenticationMiddleware
{
    private readonly RequestDelegate _next;

    // Dependency Injection
    public AuthenticationMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        //Read the Header
        string authHeader = context.Request.Headers["Authorization"];
        // If header is not null
        if (authHeader != null)
        {   //Fixing the start point and end point           
            int startPoint = authHeader.IndexOf(".") + 1;               
            int endPoint = authHeader.LastIndexOf(".");

            var tokenString = authHeader.Substring(startPoint, endPoint - startPoint).Split(".");
            var token = tokenString[0].ToString()+"==";

            var credentialString = Encoding.UTF8
                .GetString(Convert.FromBase64String(token));

            // Splitting the data from Jwt
            var credentials = credentialString.Split(new char[] { ':',',' });

            // Trim this string.
            var userRule = credentials[5].Replace("\"", ""); 
            var userName = credentials[3].Replace("\"", "");

             // Identity Principal
            var claims = new[]
            {
                new Claim("name", userName),
                new Claim(ClaimTypes.Role, userRule),
            };
            var identity = new ClaimsIdentity(claims, "basic");
            context.User = new ClaimsPrincipal(identity);
        } //will move to the next middlware
        await _next(context);
    }


}

Now we need to call this middleware when the application start by goint to Startup.cs 现在,当应用程序通过Goint启动Startup.cs时,我们需要调用此中间件

  public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        // Authorization Middleware
        app.UseMiddleware<AuthenticationMiddleware>();
     //   Other Middleware will come here

        app.UseMvc();


    }
}

Now Go to controller and Put an attribute on Methods.If the Role is admin it will execute the method or else it will return 403 Status Code. 现在进入控制器并在方法上放置一个属性,如果角色是admin,它将执行该方法,否则将返回403状态代码。

[HttpGet("GetUsers")]
[Authorize(Roles = "admin")]
    public ActionResult GetUsers()
    {
        var users = _authRepository.GetUsers();
        return Ok(users);
    }

I wish this helped for everyone who will Work with Authentication and Authorization using JWT Authentication in asp.net core all versions. 我希望这对将使用asp.net core所有版本中的JWT身份验证进行身份验证和授权的所有人有所帮助。

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

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