For protecting a WebApi, how do I choose between UseWindowsAzureActiveDirectoryBearerAuthentication vs. UseJwtBearerAuthentication vs.

Viewed 2073

There are many code samples showing how to protect a WebApi by registering authentication in Startup.cs, and they all use any one of the Owin Middlewares of UseWindowsAzureActiveDirectoryBearerAuthentication, UseJwtBearerAuthentication, UseOpenIdConnectAuthentication, or UseOAuth2Authentication. But I cannot find any documentation explain how to choose which of these. They all seem to set ClaimsPrincipal based on a Bearer token.

Are there times when one is appropriate over the others, or is it a random choice?

2 Answers

Nan Yu is right, but there is another dimension in addition to .NET/.NET core and V1.0 vs V2.0: is it to protect a Web API or a Web Application:

  • UseWindowsAzureActiveDirectoryBearerAuthentication is used in ASP.NET Web APIs, using the Azure AD V1 endpoint (it requires V1 metadata)
  • UseJwtBearerAuthentication is used in ASP.NET Core Web API (V1 endpoint indeed)
  • UseOpenIdConnectAuthentication is used in ASP.NET Web Apps.
  • UseOAuth2Authentication can be used in full.NET when talking to the V2 endpoint.

In my opinion , to protect web api by using bearer tokens from Azure AD , generally we can use both UseWindowsAzureActiveDirectoryBearerAuthentication extension method and UseJwtBearerAuthentication extension method in the OWN startup class .

In asp.net core ,you can directly use the Microsoft.AspNet.Authentication.JwtBearer package . This package provides middleware that enables the application to receive OpenID Connect bearer tokens.Code sample here is for your reference .

The usual WindowsAzureActiveDirectoryBearerAuthenticaitonMiddleware uses a metadata endpoint which is not supported by the v2.0 endpoint . You could use UseJwtBearerAuthentication if using v2.0 endpoint . See code sample here . In the code sample , it uses UseOAuthBearerAuthentication ,in asp.net core , it was renamed/replaced by the JWT bearer middleware .

Summary :

  1. In .Net Framework using the Azure AD v1.0 endpoint, you'd better use UseWindowsAzureActiveDirectoryBearerAuthentication(code sample) .

  2. In Asp.net Core using the Azure AD v1.0 endpoint, you should use UseJwtBearerAuthentication(code sample).

  3. In .Net Framework using the Azure AD v2.0 endpoint , you could use UseOAuthBearerAuthentication(code sample) or UseJwtBearerAuthentication .

  4. In Asp.net Core using the Azure AD v2.0 endpoint , you should use UseJwtBearerAuthentication .

Related