Validating ADAL JWT token in C# REST service

僤鯓⒐⒋嵵緔 提交于 2020-01-03 09:03:09

问题


I have a web application which uses the ADAL library for authentication through Azure Active Directory.

This web application makes a call to a C# REST service by passing the ADAL token string as a parameter. In my REST service, I want to validate this token. If the token is valid only then the service will perform the operation.

I searched a lot but could not find a way to validate the JWT token in my rest service. Can you guys please help me on this?


回答1:


You have two options:

1. Use OWIN middleware

Use middleware that will handle token validation for you. A common case will be the OWIN middleware, which does all the magic for you. Usually, this is the best approach, as it allows you to focus your code on the business logic for your API, not on low-level token validation. For a sample REST API that uses OWIN, check out these two samples:

  • https://github.com/Azure-Samples/active-directory-dotnet-webapp-webapi-openidconnect
  • https://github.com/Azure-Samples/active-directory-dotnet-webapp-webapi-openidconnect-aspnet5

2. Manual JWT validation

You can use the JSON Web Token Handler for ASP.NET to do manual JWT token validation. (Ok, so it's not entirely manual, but it is manually invoked.) There's also a sample for this:

  • https://github.com/Azure-Samples/active-directory-dotnet-webapi-manual-jwt-validation (the actual JWT validation happens in Global.asax.cs and looks something like this:

    JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
    
    TokenValidationParameters validationParameters = new TokenValidationParameters
    {
        ValidAudience = audience,
        ValidIssuer = issuer,
        IssuerSigningTokens = signingTokens,
        CertificateValidator = X509CertificateValidator.None
    };
    
    try
    {
        // Validate token.
        SecurityToken validatedToken = new JwtSecurityToken();
        ClaimsPrincipal claimsPrincipal = tokenHandler.ValidateToken(jwtToken, validationParameters, out validatedToken);
    
        // Do other validation things, like making claims available to controller...
    }
    catch (SecurityTokenValidationException)
    {
        // Token validation failed
        HttpResponseMessage response = BuildResponseErrorMessage(HttpStatusCode.Unauthorized);
        return response;
    }
    


来源:https://stackoverflow.com/questions/35606482/validating-adal-jwt-token-in-c-sharp-rest-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!