woensdag 30 juli 2014

Authenticate Json Web Token in ASP.Net Web API

public class JwtMessageHandler : DelegatingHandler
{
   protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   {
      var authorizationParameter = request.Headers.Authorization.Parameter;

      var handler = new JwtSecurityTokenHandler();


      var x509Certificate2 = new X509Certificate2(@"c:\temp\ADFS Signing.cer");


      var x509SecurityToken = new X509SecurityToken(x509Certificate2);


      var tokenValidationParameters = new TokenValidationParameters

      {
         SigningToken = x509SecurityToken,
         AllowedAudience = "[relyingparty identifier]",
         ValidIssuer = "[Federation Service identifier]"
      };

      ClaimsPrincipal res;


      res = handler.ValidateToken(authorizationParameter, 

                                  tokenValidationParameters);

      HttpContext.Current.User = res;

      Thread.CurrentPrincipal = res;

      return base.SendAsync(request, cancellationToken);
   }
}

The JwtMesssageHandler can be configured in the global.asax:

public class WebApiApplication : System.Web.HttpApplication
{
   protected void Application_Start()
   {
      // other configuration

      GlobalConfiguration.Configuration.MessageHandlers.Add(new JwtMessageHandler());

   }

}

Geen opmerkingen:

Een reactie plaatsen