.NET Web API Authentication and Authorization

Daneesha Bartholomeusz
5 min readSep 11, 2021

In this article I will be talking about the 4 most common REST API authentication methods and a little on Auth0.

Sometimes people mix up authentication and authorization but actually they’re two different things.

Authentication means checking who the user is. Authorization means giving him privileges. When we ask for the username and password from the user we’re authenticating him. Then we define in our application what areas are open to him and what he can do. This is authorization.

4 Most Common REST API authentication methods

  1. HTTP Authentication Schemes

2. API Keys

3. OAuth(2.0)

4. OpenID Connect

We can consider these as protocols. (There are a lot of terms thrown about when you study about .NET web API authentication. It’s hard to see what are the differences between these sets of terms. Therefore I have included what these are, protocols, specifications or products etc. and what kind of an organization is maintaining them).

1. HTTP Authentication Schemes

First implemented as an RFC (RFCs are Request For Comments. It’s a paper maintained by the IETF, Internet Engineering Task Force. A lot of technologies we use today started off as RFCs) now maintained by IANA (an organization). HTTP Authentication Schemes has several sub categories under it.

1.Basic

2.Bearer

3.Digest

4.OAuth

…other

I will be discussing about the 2 most common out of these, basic authentication and bearer authentication.

Basic Authentication

In this method username and password are sent in the request header. They’re encoded with Base64 characterization. This does not require cookies, session IDs, login pages, etc. and no handshakes are necessary.

Bearer Authentication

Bearer authentication is a token based authentication. It uses a token called a bearer token. The client sends this token in the authorization header when making requests. It is recommended to use it over HTTPS.

(What are tokens? In this article I’ll be discussing about tokens in several places. A token can be a physical token or a non-physical token. An example for a physical token is a small file. A non-physical token is held in the memory. The simplest token can be a string).

2. API Keys

API keys are maintained by an organization called RestCase. Here a unique value is generated and assigned to the user. Upon re-entry it is checked whether it’s the same user as before by this key. You can see people using API keys in several places.

  • Authorization Header
  • Basic Auth
  • Body Data
  • Custom Header
  • Query String

API keys are a simple mechanism. But the downside is that if it is captured by a malicious user it exposes the entire network. (The issue of security risks applies to the other technologies we have discussed so far too. HTTP authentication schemes are also not considered very high in security).

3. OAuth 2.0

This is an RFC. It has two forms of tokens. Access tokens, like API keys, and refresh tokens, which are generated if a token expires. In this method the user requests authentication from an authentication server. The authentication server issues a token to the user.

It has several scenarios called “flows”.

  • Authorization code, can be used for web applications
  • Implicit, used in situations where credentials cannot be saved in the client
  • Resource owner password, which should be used for trusted clients, because credentials are part of the request
  • Client credentials, for server to server authentication

4. OpenID Connect

Maintained by the Open ID Foundation. This is built on top of OAuth 2.0. There’s an authorization server in use. This method uses a JWT (Jason Web Token).

OpenAPI Security Schemes

OpenAPI Security Schemes is a specification. It was started by a company called Swagger, but now maintained as a separate initiative. This method can be configured with the above described 4 technologies. (That means there’re 4 ways to implement this specification).

Auth0

Auth0 is a product. (What we have discussed so far are protocols and specifications. This is a product).

Auth0 uses several protocols. (It can be configured in any of these ways).

  • Open Authorization (OAuth) 1
  • Open Authorization (OAuth) 2
  • OpenID Connect (OIDC)
  • Lightweight Directory Access Protocol (LDAP)
  • JSON Web Tokens (JWTs)
  • Security Assertion Markup Language (SAML)
  • WS-Federation (WS-Fed)
  • Open API Security Scheme ? (This was not mentioned under protocols in the documentation. But there was a tutorial in the same website which uses this method).

I’m going to discuss two examples for using Auth0. One uses Open API Security Schemes and is for ASP.NET. And the other uses OpenID Connect and is for .NET Core.

(I won’t be describing the whole process of configuring Auth0 under these 2 examples because of the limitation of space. I will only explain the Configure Services and Configure methods in the Startup.cs class to give an idea how to use the technologies we have discussed so far. This is not a complete tutorial on how to use Auth0. I wanted to show some examples of how to use different protocols only).

Auth0 (Using Open API Security Schemes — Swagger)

public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.Authority = $"https://{Configuration["Auth0:Domain"]}/";
options.Audience = Configuration["Auth0:Audience"];
});
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "MyProject", Version = "v1.0.0" });
var securitySchema = new OpenApiSecurityScheme
{
Description = "Implementing the Authorization header with the Bearer scheme.",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.Http,
Scheme = "bearer",
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
};
c.AddSecurityDefinition("Bearer", securitySchema);
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{ securitySchema, new[] { "Bearer" } }
});
});
}

In the ConfigureServices method in the Startup.cs class we have set up things to use the OpenAPI Security Schemes with the bearer tokens. First the services object is set up with the authentication scheme and the challenge scheme. It is JWT tokens that are used for this. Where this happens authority and audience is set to integrate with Auth0. Swagger is used to document. Then the AddSecurityDefinition and AddSecurityRequirement methods are called on the services object.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Test"));
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}

In the Configure method in the StartUp.cs class things are set for the development environment. Then several methods are called on the Application Builder object. Then the controllers are mapped.

Auth0 (Using OpenID Connect)

Now let’s look at another example to understand how to implement things with another technology.

Here is the ConfigureServices method in the StartUp.cs class for this example.

public void ConfigureServices(IServiceCollection services)
{
services.ConfigureSameSiteNoneCookies();
services.AddAuthentication(options => {
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect("Auth0", options => {
options.Authority = $"https://{Configuration["Auth0:Domain"]}";
options.ClientId = Configuration["Auth0:ClientId"];
options.ClientSecret = Configuration["Auth0:ClientSecret"];
options.ResponseType = OpenIdConnectResponseType.Code;
options.Scope.Clear();
options.Scope.Add("openid");
options.CallbackPath = new PathString("/callback");
options.ClaimsIssuer = "Auth0";
});
services.AddControllersWithViews();
}

Here a cookie based approach is used. Services object is set the authentication scheme and the challenge scheme. Then Auth0 is configured to use OpenID Connect.

Here’s the Configure method in the StartUp.cs class.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}

Here the development environment is set up. And exception handlers are defined. Then the Application Builder object is called on by several methods. And then the controllers are mapped.

That brings us to the end of the article on .NET API authentication and authorization. For more detailed tutorials on how to use authentication and authorization you can search the web. Thank you!

--

--