Jwt validation in C#

I’m trying to validate auth0 JWT in my .net framework web api‏

and have no luck by now‏

my JWT is created by auth0 since I’m using facebook/linkedin/etc verification‏

and posting that token in authorization header under 'bearer’‏

in all of my requests to api‏

in my api i have this class:‏

    public class ScopeAuthorizeAttribute : AuthorizeAttribute

{
private readonly string scope;

public ScopeAuthorizeAttribute(string scope)
{
    this.scope = scope;
}




public override void OnAuthorization(HttpActionContext actionContext)
{
    base.OnAuthorization(actionContext);

    // Get the Auth0 domain, in order to validate the issuer
    var domain = $"https://{ConfigurationManager.AppSettings["Auth0Domain"]}/";

    // Get the claim principal
    ClaimsPrincipal principal = actionContext.ControllerContext.RequestContext.Principal as ClaimsPrincipal;

    // Get the scope clain. Ensure that the issuer is for the correcr Auth0 domain
    var scopeClaim = principal?.Claims.FirstOrDefault(c => c.Type == "scope" || c.Issuer == domain);
    if (scopeClaim != null)
    {
        // Split scopes
        var scopes = scopeClaim.Value.Split(' ');

        // Succeed if the scope array contains the required scope
        if (scopes.Any(s => s == scope))
            return;
    }

    HandleUnauthorizedRequest(actionContext);
}

}

but i’m getting null in this line:
ClaimsPrincipal principal = actionContext.ControllerContext.RequestContext.Principal as
ClaimsPrincipal;

what am i doing wrong?

Hi @naama,

Have you looked at our quickstart? There is a section that shows how to validate an access token.

I’m not an expert with .NET, but it looks like you might be missing the audience. Have you looked at your token to confirm it is a JWT that can be decoded by your API?

hi, thanks for the quick answer,
I have an angular application and .net framework web api.
I worked according to this for the angular and this for the web api.
but no success.

I think my interceptor might not be correct
what am I missing to make it work?

my interceptor:

intercept(req: HttpRequest<any>, next: HttpHandler) : Observable<HttpEvent<any>>{
const token = this.storageService.get('accessToken');
req = req.clone({
 url:  req.url,
 setHeaders: {
Authorization: `Bearer ${token}`
 }
});
return next.handle(req);
 }

accessToken:

auth.getAccessTokenSilently().subscribe(res => {
          this.storageService.set('accessToken', res);
         
        })

Have you set the audience requested by your angular app as the API identifier for your .net API?

audience: '{YOUR_API_IDENTIFIER}',

I think I did, maybe I did it wrong though
image

Does the request to your .net API include the token? And have you decoded the token (you can use jwt.io) and confirmed it includes the correct scopes and audience?

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.