Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASPNet Core: Use [Authorize] with function in service

Tags:

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].

like image 559
MBS Avatar asked Jun 26 '19 07:06

MBS


People also ask

How do I Authorize a user in .NET Core?

Add the UseAuthentication middleware after UseRouting in the Configure method in the Startup file. This will enable us to authenticate using ASP.NET Core Identity. With all of this in place, the application Is all set to start using Identity.

How do I use authentication and authorization in web API?

The ASP.NET Web API Framework provides a built-in authorization filter attribute i.e. AuthorizeAttribute and you can use this built-in filter attribute to checks whether the user is authenticated or not. If not, then it simply returns the HTTP status code 401 Unauthorized, without invoking the controller action method.


1 Answers

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.

like image 103
Kirk Larkin Avatar answered Oct 13 '22 22:10

Kirk Larkin