我正在使用JwtBearer身份验证来保护我的API。我在每个API上方添加了[Authorize]
,它可以正常工作。
我正在使用以下代码在启动时添加身份验证:
services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.Authority = "http://localhost:1234";
options.RequireHttpsMetadata = false;
options.Audience = "test";
});
我想要一种将[Authorize]
添加到服务中的函数或在函数中编写与[Authorize]
相同的代码的方法。
答案 0 :(得分:4)
在不传递任何参数的情况下使用[Authorize]
会归结为检查用户是否已获得身份验证的调用。从服务内部看,像这样:
// If any of the properties being accessed are null, assume that the user
// is not authenticated.
var isAuthenticated = httpContext?.User?.Identity?.IsAuthenticated ?? false;
要访问服务内部的HttpContext
,可以使用IHttpContextAccessor
。这是一个完整的示例:
public class Service
{
private readonly IHttpContextAccessor httpContextAccessor;
public Service(IHttpContextAccessor httpContextAccessor)
{
this.httpContextAccessor = httpContextAccessor;
}
public void ServiceFunction()
{
var httpContext = httpContextAccessor.HttpContext;
var isAuthenticated = httpContext?.User?.Identity?.IsAuthenticated ?? false;
if (isAuthenticated)
{
// The user is authenticated.
}
}
}
如果要应用授权策略,则可以使用IAuthorizationService
。这是一个完整的示例:
public class Service
{
private readonly IHttpContextAccessor httpContextAccessor;
private readonly IAuthorizationService authzService;
public Service(IHttpContextAccessor httpContextAccessor,
IAuthorizationService authzService)
{
this.httpContextAccessor = httpContextAccessor;
this.authzService = authzService;
}
public async Task ServiceFunction()
{
var httpContext = httpContextAccessor.HttpContext;
var isAuthenticated = httpContext?.User?.Identity?.IsAuthenticated ?? false;
if (isAuthenticated)
{
// The user is authenticated.
var authzResult = await authzService.AuthorizeAsync(
httpContext.User,
"PolicyName");
if (authzResult.Succeeded)
{
// The user is authorised.
}
}
}
}
注意:要使用IHttpContextAccessor
,您可能需要在services.AddHttpContextAccessor();
方法中添加Startup.ConfigureServices
。