C# ASPNet核心:将[Authorize]与服务中的函数一起使用
我正在使用JWTBear身份验证来保护我的API。我在每个API上面添加了C# ASPNet核心:将[Authorize]与服务中的函数一起使用,c#,asp.net-core,C#,Asp.net Core,我正在使用JWTBear身份验证来保护我的API。我在每个API上面添加了[Authorize],它成功了 我正在使用此代码在启动中添加身份验证: services.AddAuthentication("Bearer") .AddJwtBearer("Bearer", options => { options.Authority = "http://localhost:1234"; options.Requir
[Authorize]
,它成功了
我正在使用此代码在启动中添加身份验证:
services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.Authority = "http://localhost:1234";
options.RequireHttpsMetadata = false;
options.Audience = "test";
});
我想要一种方法,将
[Authorize]
添加到服务中的函数中,或者在函数中编写与[Authorize]
相同的代码,使用[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
,可以使用。下面是一个完整的示例:
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.
}
}
}
如果要应用授权策略,可以使用。下面是一个完整的例子:
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
,您可能需要添加服务。AddHttpContextAccessor()
到您的启动.ConfigureServices
方法。您使用的.net核心版本是什么?您试图实现的概念称为AOP。net core还不支持开箱即用。PostSharp或Windsor Castle动态代理可以为您实现这一点。我建议你检查一下这个答案