C# 控制器ASP.net core 2.1中的Jwt角色身份验证
我正在用asp.net core 2.1编写一个协作web API,使用postgresql作为db。在用户登录后,向用户提供一个JWT令牌,该令牌将用于前端身份验证(前端将使用angular 2+实现)。我想在JWT中存储用户角色,当用户登录时,将从db读取用户角色,并将其存储(授权角色),因此我将在控制器方法上写入角色。我想使用Authorize属性C# 控制器ASP.net core 2.1中的Jwt角色身份验证,c#,asp.net-core,jwt,C#,Asp.net Core,Jwt,我正在用asp.net core 2.1编写一个协作web API,使用postgresql作为db。在用户登录后,向用户提供一个JWT令牌,该令牌将用于前端身份验证(前端将使用angular 2+实现)。我想在JWT中存储用户角色,当用户登录时,将从db读取用户角色,并将其存储(授权角色),因此我将在控制器方法上写入角色。我想使用Authorize属性 // Auth Controller [HttpGet("GetUsers")] [Authorize(Roles =
// Auth Controller
[HttpGet("GetUsers")]
[Authorize(Roles = "admin")]
public ActionResult GetUsers()
{
var users = _authRepository.GetUsers();
return Ok(users);
}
和Repository.cs
public List<User> GetUsers()
{
var users = _context.Users.ToList();
return users;
}
公共列表GetUsers()
{
var users=_context.users.ToList();
返回用户;
}
问题:我是否需要编写一个中间件来读取JWT中的每个用户角色,并将该角色放入身份主体声明中?请分享你的经验。我很高兴知道您的方法。我很高兴我解决了这个问题,我正在共享完整的中间件。在用户的每一个请求中,中间件将检查保存在JWT令牌中点的userRole
xxxx.UserInformation.yyyy
我们将获取该用户信息
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);
}
}
现在我们需要在应用程序启动时调用这个中间件,方法是转到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();
}
}
我希望这对在asp.net core所有版本中使用JWT身份验证进行身份验证和授权的每个人都有帮助 我很高兴我解决了这个问题,我正在共享完整的中间件。在用户的每一个请求中,中间件将检查保存在JWT令牌中点的userRole
xxxx.UserInformation.yyyy
我们将获取该用户信息
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);
}
}
现在我们需要在应用程序启动时调用这个中间件,方法是转到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();
}
}
我希望这对在asp.net core所有版本中使用JWT身份验证进行身份验证和授权的每个人都有帮助 现在还不清楚你在问什么。。。您尝试了哪些功能,哪些功能不起作用?我想基于JWT令牌管理用户角色。我需要中间件吗?如果您使用Microsoft ASPNET Core Jwt库/处理程序(System.IdentityModel.Tokens.Jwt),则传入的已验证Jwt中的任何角色声明都将自动提取并填充到ClaimsPrincipal(?)中,并可用于授权(Roles=“…”)]属性。我也这么做了,这对我很有用。谢谢我从JWT文档中读到的。身份原则。现在还不清楚你在问什么。。。您尝试了哪些功能,哪些功能不起作用?我想基于JWT令牌管理用户角色。我需要中间件吗?如果您使用Microsoft ASPNET Core Jwt库/处理程序(System.IdentityModel.Tokens.Jwt),则传入的已验证Jwt中的任何角色声明都将自动提取并填充到ClaimsPrincipal(?)中,并可用于授权(Roles=“…”)]属性。我也这么做了,这对我很有用。谢谢我从JWT文档中读到的。身份原则。即使您可以在角色中添加两个值。即使您可以在角色中添加两个值。