我正在ASP.NET Core 2.2中开发Web API。我想随时基于HTTP请求的Authorization标头中存储的令牌对任何用户的每个请求进行身份验证,以便用户可以调用用[AuthorizeAttribute]注释的控制器和操作。这是我的中间件:
public class TokenBasedAuthenticationMiddleware
{
private RequestDelegate nextDelegate;
public TokenBasedAuthenticationMiddleware(RequestDelegate next) => nextDelegate = next;
public async Task Invoke(HttpContext httpContext, IRegistrationsRepository registrationsRepository)
{
if (registrationsRepository.IsAuthorized(httpContext.Request.Headers["Authorization"]))
{
//Code To Authenticate this request?
}
await nextDelegate.Invoke(httpContext);
}
}
如何简单地对请求进行身份验证(即将HttpContext.User.Identity.IsAuthenticated设置为true),而不会造成任何复杂性?
答案 0 :(得分:0)
您可以尝试:
private String CONN_STRING = "jdbc:mysql://localhost:3306/vmenginedatabaseT04P?serverTimezone=UTC"; // "jdbc:mysql://localhost:3306/vm_database_1";
但是,如果使用JWT承载令牌认证,则可以直接使用AddJwtBearer扩展名。 var claims = new[] { new Claim("name", "YourName"), new Claim(ClaimTypes.Role, "Admin") };
var identity = new ClaimsIdentity(claims, "JWT");
httpContext.User = new ClaimsPrincipal(identity);
await nextDelegate.Invoke(httpContext);
中间件在传入请求的HTTP授权标头中查找令牌(JSON Web令牌或JWT)。如果找到有效令牌,则请求被授权。然后,在要保护的控制器或路由上添加[Authorize]属性:
相关代码示例:
https://developer.okta.com/blog/2018/03/23/token-authentication-aspnetcore-complete-guide
https://garywoodfine.com/asp-net-core-2-2-jwt-authentication-tutorial/