How to secure ASP.NET Web API with OAuth 2.0 bearer tokens (OWIN)?
Securing ASP.NET Web API with OAuth bearer tokens through OWIN, covering token endpoints, external JWT issuers, bearer validation, claims, and authorization roles.
How to secure ASP.NET Web API with OAuth 2.0 bearer tokens (OWIN)?
An Application Programming Interface (API) which can be called by anyone is not a healthy API when it handles customer or business data. We need to authenticate the caller and authorize what that caller is allowed to do. Otherwise, an exposed endpoint becomes a blind spot, and an attacker or an accidental client can read or change information.
OAuth 2.0 bearer tokens provide a way for a client to present an access token to ASP.NET Web API. In this article, we are going to see how to protect Web API using Open Web Interface for .NET (OWIN)/Katana middleware, either with our own token endpoint or with tokens from an external issuer validated as JSON Web Token (JWT).
We can protect an API through two common identity approaches:
| Approach | Pros | Cons |
|---|---|---|
| Self-hosted authorization server with OWIN | + Full control of token endpoint<br>+ Fits a trusted first-party application | − Team owns credentials and token lifecycle<br>− More security responsibility |
| External token issuer with JWT | + Identity platform manages issuing tokens<br>+ Good fit for many clients and APIs | − Depends on issuer availability and configuration<br>− Requires correct issuer key and audience validation |
TL;DR Summary
- OAuth 2.0 access tokens represent delegated authorization to call a resource.
- The API must validate issuer, audience, signature and expiry before accepting a token.
- OWIN/Katana middleware can validate bearer tokens before Web API actions run.
- Authentication tells us who or what presented a token, authorization decides what it can do.
- Use HTTPS for every token request and API request.
- Never log the bearer token, because possession of it can be enough to call the API.
Challenges
Unprotected front door
An API without authentication depends on every consumer behaving correctly. A news article endpoint may be read by many clients, but an editorial update endpoint must be limited. If the boundary is not protected, the business will discover the problem only after data has changed.
Token trust
A token is only useful when the API knows who issued it and for which API it was created. Checking that a token is present is not validation. We must validate the signature, issuer, audience and lifetime, otherwise a token created for another service may be accepted.
Permission boundaries
A valid token does not automatically mean the caller can perform every operation. A reader may view an article while an editor can publish it. We should use scopes or claims for this distinction, because authentication and authorization are different responsibilities.
What is an OAuth 2.0 bearer token?
An OAuth 2.0 bearer token is a credential which a client presents to a resource server to access a protected resource.
In simple terms, the API receives a token in the Authorization header and asks the OWIN middleware whether the token is valid. The API then uses the resulting identity and claims to make an authorization decision. Anyone holding a bearer token can use it, so the token must be protected like a password.
Why bearer token security is important?
The API is a front door used by browsers, mobile applications or other services. We should keep authentication concerns in middleware so every endpoint receives the same baseline validation. The controller then concentrates on business rules, not on parsing a token in every action.
How to configure OWIN bearer authentication?
The following diagram depicts a client sending a token through OWIN middleware to Web API,

Option1: Self-hosted authorization server with OWIN
Steps to Implement:
Follow the following instructions to create a token endpoint and protect an ASP.NET Web API 2 application.
-
Create an ASP.NET Web API 2 project targeting .NET Framework 4.5 or later.
-
Install the Katana OAuth package from NuGet.
Install-Package Microsoft.Owin Install-Package Microsoft.Owin.Security.OAuth -
Add an OWIN startup class to the application.
[assembly: OwinStartup(typeof(MyApi.Startup))] -
Configure the token endpoint and bearer authentication in the startup class.
public void Configuration(IAppBuilder app) { app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions { TokenEndpointPath = new PathString("/token"), Provider = new NewsOAuthProvider(), AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30), AllowInsecureHttp = false }); app.UseOAuthBearerAuthentication( new OAuthBearerAuthenticationOptions()); HttpConfiguration configuration = new HttpConfiguration(); WebApiConfig.Register(configuration); app.UseWebApi(configuration); } -
Add the provider and validate the client application and resource owner credentials. Replace the input place holders with actual user validation code.
public class NewsOAuthProvider : OAuthAuthorizationServerProvider { public override Task ValidateClientAuthentication( OAuthValidateClientAuthenticationContext context) { context.Validated(); return Task.FromResult<object>(null); } public override Task GrantResourceOwnerCredentials( OAuthGrantResourceOwnerCredentialsContext context) { if (!ValidateUser(context.UserName, context.Password)) { context.SetError("invalid_grant", "The user name or password is incorrect."); return Task.FromResult<object>(null); } ClaimsIdentity identity = new ClaimsIdentity( OAuthDefaults.AuthenticationType); identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName)); identity.AddClaim(new Claim(ClaimTypes.Role, "reader")); context.Validated(identity); return Task.FromResult<object>(null); } } -
Protect a controller or action with the authorization attribute and check a role claim for an operation which needs stronger permission.
[Authorize] [RoutePrefix("api/articles")] public class ArticlesController : ApiController { [HttpGet] [Route("{id:int}")] public IHttpActionResult Get(int id) { return Ok(repository.Find(id)); } [Authorize(Roles = "editor")] [HttpPost] public IHttpActionResult Publish(PublishArticleRequest request) { return Ok(); } } -
Request a token from the token endpoint using HTTPS.
POST /token HTTP/1.1 Host: <api-host> Content-Type: application/x-www-form-urlencoded grant_type=password&username=<user-name>&password=<password> -
Send the access token in a later HTTPS request.
GET /api/articles/42 HTTP/1.1 Host: <api-host> Authorization: Bearer <access-token> -
Just to pulse check, call the endpoint without a token, with a token having the wrong role and with a valid token.
No token -> 401 Unauthorized Wrong role -> 403 Forbidden Valid token -> expected API responseNote:
AllowInsecureHttp = falseis intentional. Do not use the Resource Owner Password Credentials grant for an untrusted third-party application, and do not store real passwords in logs or test scripts.
Option2: External token issuer with JWT
When the organization already has an identity provider, we normally prefer receiving signed JWT access tokens instead of owning the password and token endpoint. Follow the following instructions to configure the Web API resource server,
-
Install the JWT middleware packages.
Install-Package Microsoft.Owin.Security.Jwt Install-Package System.IdentityModel.Tokens.Jwt -
Configure issuer, audience and signing key validation in the OWIN startup class.
public void Configuration(IAppBuilder app) { app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions { AuthenticationMode = AuthenticationMode.Active, AllowedAudiences = new[] { "<api-audience>" }, IssuerSecurityTokenProviders = new[] { new SymmetricKeyIssuerSecurityTokenProvider( "<token-issuer>", "<signing-key>") } }); } -
If the issuer is Azure Active Directory, the Katana integration (Microsoft.Owin.Security.ActiveDirectory) can use
UseWindowsAzureActiveDirectoryBearerAuthenticationwithWindowsAzureActiveDirectoryBearerAuthenticationOptionsinstead of managing the signing keys directly. -
Just to pulse check, test an expired token, a token issued for another audience and a valid token.
Expired token -> 401 Unauthorized Wrong audience -> 401 Unauthorized Valid token -> expected API responseInfo: External issuer is usually for the rescue when many applications need one identity boundary, but the API is still responsible for issuer, audience, signature and expiry validation.
Token validation and authorization
The resource server should validate the token’s signature, issuer, audience and expiration. It should also check the requested scope or role before changing a resource. A token with read:articles should not be enough to execute a publish operation, otherwise the permission model is only documentation.
Use HTTPS and avoid writing the Authorization header to logs. Keep token lifetimes short enough for the risk, and define a refresh or re-issue process with the identity provider. If a token is revoked before expiry, the architecture must define how the API learns about that event, because a self-contained JWT is not automatically recalled.
For the difference between OAuth authorization and OpenID Connect authentication, refer the upcoming What is OAuth 2.0 and OpenID Connect? article for detailed information. The broader comparison with Forms and Windows Authentication is discussed in the upcoming What is Authentication and Authorization in ASP.NET? article.
Must Do and Don’ts
- Must Do: Validate the token before the controller is running, because a controller-level check can be missed on a new endpoint.
- Must Do: Keep scopes small and make each role meaningful to the business.
- Don’t: Treat an
id_tokenas an API access token, because its audience and purpose can be different. - Don’t: Log bearer tokens, client secrets or passwords.
- Be mindful: A
401means authentication is missing or invalid, while403means the authenticated caller is not allowed.
Wrap up
In this article, we have looked at a self-hosted OWIN token endpoint, an external JWT issuer, bearer authentication, claims and authorization roles. I appreciate your time and efforts to read this article. In the next article, I will walk you through setting up continuous integration with Visual Studio Online.
Related Posts
What is Authentication and Authorization in ASP.NET?
ASP.NET authentication and authorization explained through Forms Authentication, Windows Authentication, OAuth 2.0, JWT bearer tokens, and security approach selection.
How to document ASP.NET Web API with Swagger?
Documenting ASP.NET Web API 2 with Swagger and Swashbuckle, XML comments, response contracts, and Swagger UI for an explicit API contract.
What is OAuth 2.0 and OpenID Connect?
OAuth 2.0 and OpenID Connect explained through roles, grant types, access tokens, authorization versus authentication, and the purpose of an id_token.