MBS
MBS

Reputation: 707

ASPNet Core: Use [Authorize] with function in service

I am using JwtBearer authentication to secure my API. I am adding [Authorize] above each API and it worked.

I am using this code to add the authentication in the startup:

services.AddAuthentication("Bearer")
        .AddJwtBearer("Bearer", options =>
        {
            options.Authority = "http://localhost:1234";
            options.RequireHttpsMetadata = false;
            options.Audience = "test";
        });

I want a way to add the [Authorize] to a function in a service, or write a code in the function that works the same as [Authorize].

Upvotes: 4

Views: 1219

Answers (1)

Kirk Larkin
Kirk Larkin

Reputation: 93093

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.

Upvotes: 3

Related Questions