Using [Authorize]
without passing any parameters boils down to a call that checks whether or not the user is authenticated. From inside a service, that would look something like this:
// If any of the properties being accessed are null, assume that the user
// is not authenticated.
var isAuthenticated = httpContext?.User?.Identity?.IsAuthenticated ?? false;
To access HttpContext
inside of a service, you can use IHttpContextAccessor
. Here's a complete example:
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.
}
}
}
If you want to apply an authorisation policy, you can use IAuthorizationService
. Here's a complete example of that:
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.
}
}
}
}
Note: To use IHttpContextAccessor
, you might need to add services.AddHttpContextAccessor();
to your Startup.ConfigureServices
method.