Search code examples
asp.net-core-mvcauth0asp.net-core-2.2

auth0 authorisation in asp.net core app (MVC)


I'am trying to get Auth0 to work in my MVC app. Although the authentication is working, I cannot seem to get the authorization working.

I've followed this tutorial: https://auth0.com/docs/quickstart/webapp/aspnet-core

my code:

public static IServiceCollection AddAuth0(this IServiceCollection services, IConfiguration configuration)
{
    var auth0Options = configuration.GetSection(nameof(Auth0Config))
        .Get<Auth0Config>();

    services.Configure<CookiePolicyOptions>(options =>
    {
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });

    services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;

        //                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        //                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    }) //do i need this for access_token?
       //                .AddJwtBearer(options =>
       //                {
       //                    options.Authority = auth0Options.Domain;
       //                    options.Audience = auth0Options.ApiIdentifier;
       //
       //                    options.SaveToken = true;
       //                    options.RequireHttpsMetadata = false;
       //                })
        .AddCookie()
        .AddOpenIdConnect(Auth0Constants.Auth0Scheme, options =>
        {
            options.Authority = $"https://{auth0Options.Domain}";

            options.ClientId = auth0Options.ClientId;
            options.ClientSecret = auth0Options.ClientSecret;

            options.ResponseType = Auth0Constants.ResponseTypeCode;

            options.SaveToken = true;

            options.Scope.Clear();
            options.Scope.Add(Auth0Constants.Auth0Scope.openid.ToString());
            options.Scope.Add(Auth0Constants.Auth0Scope.email.ToString());
            options.Scope.Add(Auth0Constants.Auth0Scope.profile.ToString());
            options.Scope.Add("read:cars");

            options.CallbackPath = new PathString("/callback");

            options.ClaimsIssuer = Auth0Constants.Auth0Scheme;

            options.Events = new OpenIdConnectEvents
            {
                OnRedirectToIdentityProviderForSignOut = context => OnRedirectToIdentityProviderForSignOut(context, auth0Options),
                OnRedirectToIdentityProvider = context => OnRedirectToIdentityProvider(context, auth0Options)
            };
        });

    services.AddAuthorization(options =>
    {
        options.AddPolicy("read:cars", policy => policy.Requirements.Add(new HasScopeRequirement("read:cars", auth0Options.Domain)));
    });

    services.AddSingleton<IAuthorizationHandler, HasScopeHandler>();

    return services;
}

private static Task OnRedirectToIdentityProvider(RedirectContext context, Auth0Config config)
{
    context.ProtocolMessage.SetParameter("audience", config.ApiIdentifier);

    return Task.CompletedTask;
}

private static Task OnRedirectToIdentityProviderForSignOut(RedirectContext context, Auth0Config auth0Options)
{
    var logoutUri = $"https://{auth0Options.Domain}/v2/logout?client_id={auth0Options.ClientId}";

    var postLogoutUri = context.Properties.RedirectUri;
    if (!string.IsNullOrEmpty(postLogoutUri))
    {
        if (postLogoutUri.StartsWith("/"))
        {
            var request = context.Request;
            postLogoutUri = request.Scheme + "://" + request.Host + request.PathBase + postLogoutUri;
        }

        logoutUri += $"&returnTo={Uri.EscapeDataString(postLogoutUri)}";
    }

    context.Response.Redirect(logoutUri);
    context.HandleResponse();

    return Task.CompletedTask;
}

When i look at my charles session, i do see the correct scopes and permissions coming back in the token:

"scope": "openid profile email read:cars",
"permissions": [
  "read:cars"
]

But for instance, I cannot get the access_token like they say I can:

var accessToken = await HttpContext.GetTokenAsync("access_token");

this returns null; It is also not in the claims.

On one of my controllers I have: [Authorize("read:cars")] And I get an access denied, do i remove that permission and only use the Authorize, then I am good.

To check if the scope is present:

public class HasScopeRequirement : IAuthorizationRequirement
{
    public string Issuer { get; }
    public string Scope { get; }

    public HasScopeRequirement(string scope, string issuer)
    {
        Scope = scope;
        Issuer = issuer;
    }
}

public class HasScopeHandler : AuthorizationHandler<HasScopeRequirement>
{
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, HasScopeRequirement requirement)
    {
        // If user does not have the scope claim, get out of here
        if (!context.User.HasClaim(c => c.Type == "scope" && c.Issuer == requirement.Issuer))
            return Task.CompletedTask;

        // Split the scopes string into an array
        var scopes = context.User.FindFirst(c => c.Type == "scope" && c.Issuer == requirement.Issuer).Value.Split(' ');

        // Succeed if the scope array contains the required scope
        if (scopes.Any(s => s == requirement.Scope))
            context.Succeed(requirement);

        return Task.CompletedTask;
    }
}

But I guess this is not my problem, I think it lies within my access_token that i cannot even to read. So I am thinking that I am missing something. Is it due to the DefaultAuthenticationScheme/ChallengeScheme or ...?


Solution

  • thnx to Kirk!

    fixed a bit different then my original idea; now i am using roles.

    in auth0 I have users, and assign them the desired roles;

    Auth0-user-role

    and as a rule:

    function (user, context, callback) {
      context.idToken['http://schemas.microsoft.com/ws/2008/06/identity/claims/roles'] = context.authorization.roles;
    
      callback(null, user, context);
    }
    

    I am using http://schemas.microsoft.com/ws/2008/06/identity/claims/roles as a default claim, because .net core maps to that by default.

    in my setup I've added:

    options.TokenValidationParameters= new TokenValidationParameters
    {
        RoleClaimType = "http://schemas.microsoft.com/ws/2008/06/identity/claims/roles"
    };
    

    Now i can use the Authorize attribute on my controllers

    just to be clear; I only have one webapp.If I would go to a different API then I would have to use the access_token off course.