[英]Jwt Role authentication in controller ASP.net core 2.1
我正在使用postgresql作為db用asp.net core 2.1編寫協作式Web API。 在用戶登錄后,為用戶提供了JWT令牌,該令牌將用於前端側身份驗證(前端將使用angular 2+實現)。 我想將用戶角色存儲在JWT中,當用戶登錄時,將從數據庫讀取用戶角色並將其存儲(授權角色),因此我將在控制器方法上編寫角色。 我想使用Authorize屬性。
// 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;
}
問題:我是否需要編寫中間件來從JWT讀取每個用戶角色,並將該角色放入身份委托人聲明中? 請分享您的經驗。 我很高興知道您的要求。
我很高興解決了這個問題,我正在共享完整的中間件。 在用戶的每個請求中,中間件都將檢查嵌入在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);
}
}
現在,當應用程序通過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();
}
}
現在進入控制器並在方法上放置一個屬性,如果角色是admin,它將執行該方法,否則將返回403狀態代碼。
[HttpGet("GetUsers")]
[Authorize(Roles = "admin")]
public ActionResult GetUsers()
{
var users = _authRepository.GetUsers();
return Ok(users);
}
我希望這對將使用asp.net core所有版本中的JWT身份驗證進行身份驗證和授權的所有人有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.