Token Based Authentication in ASP.NET Web API (2024)

Token-Based Authentication in ASP.NET Web API: An Overview

In a Web API Tutorial, token-based authentication involves a client application sending credentials to the server (usually a username and password) in exchange for a unique token. This token acts as proof of identity for subsequent requests, removing the need to provide sensitive credentials repeatedly, making it a valuable concept to learn in ASP.NET Core Training.

Why Do We Need Token-Based Authentication in ASP.NET Web API?

The ASP.NET Web API is an excellent framework provided by Microsoft for developing Web APIs, i.e., HTTP-based services on top of the .NET Framework. Once we have developed the services using Web API, they will be used by a wide range of customers, including

  • Browsers
  • Mobile applications
  • Desktop applications
  • IOTs, etc.

How Does The Token-Based Authentication work?

Token Based Authentication in ASP.NET Web API (1)

Token-Based Authentication operates as follows:

  • The user inserts his credentials (i.e., username and password) into the client (here, the client refers to the browser or mobile device, for example).
  • After that, the client sends these credentials (username and password) to the Authorization Server.
  • After that, the Authorization Server validates the client credentials (username and password) and generates and returns an access token. This Access Token contains sufficient information to identify a user and the token expiry time.
  • The Access Token is then included in the Authorization header of the HTTP request by the client application toaccess the restricted resources from the Resource Server until the token expires.

Implementation of Token-Based Authentication

Step 1

Open Visual Studio 2017 => create a new Web API project => Name the project, in my case, I named it Token_Auth_Web_API, and set the Authentication to an Individual User Account as shown in the below figure.

Token Based Authentication in ASP.NET Web API (2)

Step 2

Go to Startup.cs file under the App_Start folder in the solution

// Configure the application for OAuth based flow PublicClientId = "self"; OAuthOptions = new OAuthAuthorizationServerOptions { TokenEndpointPath = new PathString("/Token"), Provider = new ApplicationOAuthProvider(PublicClientId), AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"), AccessTokenExpireTimeSpan = TimeSpan.FromDays(14), // In production mode set AllowInsecureHttp = false AllowInsecureHttp = true }; 

Install the Owin using the below command in the package manager console

Install-Package Owin -Version 1.0.0

Owin: open web interface for .NET is a middleware that defines the interface between the web server and application.

TokenEndPointPath: This is a kind of request path client applications that communicate with the server directly as part of the OAuth protocol. It must begin with a slash “/”

  1. Provider: The object provided by the application to process the event raised by the authorization server middleware.

  2. AuthorizeEndpointPath: The request path where the client application will redirect the client/user to obtain a user account to issue a token

  3. AccessTokenExpireTimeSpan: Defines the validity of the token

  4. AllowInsecureHttp: It will allow a normal http request to authorize, if it is set to false, it will process only HTTP requests.

Step 3

To register the user, we are going to use the api/Account/Register Endpoint from a client which is available in AccountController of our WEB API project, as shown below.

 // POST api/Account/Register [AllowAnonymous] public async Task<IHttpActionResult> Register(RegisterBindingModel model) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var user = new ApplicationUser() { UserName = model.Email, Email = model.Email }; IdentityResult result = await UserManager.CreateAsync(user, model.Password); if (!result.Succeeded) { return GetErrorResult(result); } return Ok(); }

Go to the Index View of the home controller, as shown below figure, and add the code

Home=> Index.cshtml

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <h4> Registration Form</h4> <div id="loginDiv" style="width:50%"> <div style="width:50%"> <div class="form-group"> <label for="txtEmail">First Name </label> <input type='email' name="email" id="txtEmail" class="form-control"> </div> <div class="form-group"> <label>Password</label> <input type="password" id="textPwd" class="form-control"> </div> <div class="form-group"> <label>Confrim Password</label> <input type="password" id="txtConfirmPwd" class="form-control"> </div> </div> <button id="register" class="btn btn-default">Submit</button> </div> <h4>Login </h4> <div id="loginDiv" style="width:50%"> <div class="form-group"> <label for="txtEmail">First Name </label> <input type='email' name="email" id="loginEmail" class="form-control"> </div> <div class="form-group"> <label>Password</label> <input type="password" id="loginPwd" class="form-control"> </div> <button id="btnLogin" class="btn btn-default">Submit</button> </div> <div> <label id="msg"></label> </div> <script> $(document).ready(function () { $("#register").on('click', function () { var data = { Email: $("#txtEmail").val().trim(), Password: $("#textPwd").val().trim(), ConfirmPassword: $("#txtConfirmPwd").val().trim() }; $.ajax({ url: "http://localhost:49501/api/Account/Register", type: 'POST', data: data, success: function (resp) { window.location.href = '/Home/Index'; } }) }); $("#btnLogin").on('click', function () { //var data = { Email: $("#loginEmail").val().trim(), Password: $("#textPwd").val().trim(), ConfirmPassword: $("#loginPwd").val().trim() }; $.ajax( { url: "/TOKEN", type: "POST", data: $.param({ grant_type: 'password', username: $("#loginEmail").val(), password: $("#loginPwd").val() }), headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, success: function (resp) { sessionStorage.setItem('userName', resp.userName); sessionStorage.setItem('accessToken', resp.access_token); var authHeaders = {}; authHeaders.Authorization = 'Bearer ' + resp.access_token; $.ajax({ url: "http://localhost:49501/api/values", type: "GET", headers: authHeaders, success: function (response) { $("#loginEmail").val(""); $("#loginPwd").val(""); $("#msg").text(response); } }); }, error: function () { $("#msg").text("Authentication failed"); } }) }); }) </script> 

From the above HTML code, it is obvious we have two form

  • Registration Form

  • Login Form

Registration Form: The registration formused to register the user using the /api/Account/Register API Service which doesn’t require any authentication

Login Form: In this user requests to give their credential, once they submit the form /TOKEN post service is fired, once the service validates the user it will generate an access token and send it as a response to a server with a username as shown in below figure.

Token Based Authentication in ASP.NET Web API (3)

In Login Ajax call success, we are saving the token and user details, and making another API call /api/values, this function definition is decorated with the [Authorize] attribute. we need to pass the access token as an authorization header whenever this HTTP service request happens from the client side.

 // GET api/values [EnableCors(origins: "*", headers: "*", methods: "*", exposedHeaders: "X-My-Header")] [Authorize] public IEnumerable<string> Get() { return new string[] {"You are successfully Authenticated to Access the Service"}; }

[EnableCors(origins: "*", headers: "*", methods: "*", exposedHeaders: "X-My-Header")]: Enabled the CROS origin, so that it can be accessed from any domain

[Authorize]: It is used to authenticate the token sent from the client side, once the authentication is successfully the Get() will be fired

Client-side HTTP request with Authorization Header

$("#btnLogin").on('click', function () { $.ajax( { url: "/TOKEN", type: "POST", data: $.param({ grant_type: 'password', username: $("#loginEmail").val(), password: $("#loginPwd").val() }), headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, success: function (resp) { sessionStorage.setItem('userName', resp.userName); sessionStorage.setItem('accessToken', resp.access_token); var authHeaders = {}; authHeaders.Authorization = 'Bearer ' + resp.access_token; $.ajax({ url: "http://localhost:49501/api/values", type: "GET", headers: authHeaders, success: function (response) { $("#loginEmail").val(""); $("#loginPwd").val(""); $("#msg").text(response); } }); }, error: function () { $("#msg").text("Authentication failed"); } })

authHeaders.Authorization = 'Bearer ' + resp.access_token: We are defining the authorization header with the access token when the /api/values HTTP call happens. On the server side, the token is validated, once its success it will return a message “You are successfully Authenticated to Access the Service”

Note: we need to send grant_type: 'password' as the data along with the user name and password through the body of the HTTP request which accesses the URL /TOKEN

Token Based Authentication in ASP.NET Web API (4)

Header with /api/values HTTP call

Token Based Authentication in ASP.NET Web API (5)

Success

Token Based Authentication in ASP.NET Web API (6)

From the above figures, it is obvious the token is validated, and the service returns a message.

Token Based Authentication in ASP.NET Web API (7)

Invalid Credential Entry

Token Based Authentication in ASP.NET Web API (8)

If the credential is wrong the service /TOKEN will return the error message which is shown above

Advantages of using Token-Based Authentication in ASP.NET Web API

  1. Server Scalability: The token provided by the client to the server is self-contained, which means it contains enough data to identify the person required for authentication. As a result, you can simply expand your web farm without relying on shared session stores.
  2. Loosely associated: The client application is not connected to or associated with any particular authentication system. The server only performs authentication when the token has been generated and confirmed.
  3. Mobile-Friendly: Cookies and browsers get along well, but managing cookies on native platforms such as Android, iOS, and Windows Phone is difficult. The token-based technique greatly simplifies this.
  4. Statelessness: Tokens are self-contained and contain all necessary information for authentication, allowing the server to be stateless. This scalability advantage enables horizontal scaling and simplified load balancing.
  5. Security: Tokens are often signed or encrypted, making them tamper-proof. They can also have short expiration durations, limiting attackers' window of opportunity.
  6. Decoupling: Token-based authentication allows for Single Sign-On (SSO) across various applications or services without requiring users to provide their credentials.
  7. Flexibility: Tokens can be used for a variety of purposes, such as user authentication, authorization, and granting specific permissions (for example, OAuth2 authorization tokens).
  8. Cross-Origin Resource Sharing (CORS): Tokens can be used with Cross-Origin Resource Sharing headers to secure API access from different domains.
Summary

Token-based authentication reduces the need to communicate sensitive credentials with each request, which improves security and scalability. Clients exchange credentials in return for a temporary token, which is then utilized for subsequent requests with minimal overhead. This method is suitable for a wide range of clients (browsers, mobile devices, etc.) and streamlines server-side activities. Signed/encrypted tokens, short expirations, and decoupling from session stores are all security benefits.

Token Based Authentication in ASP.NET Web API (2024)

FAQs

Why we use token-based authentication in Web API? ›

To increase the security of your interactions with the Digital Platform API, we've implemented a signed token-based authentication system. This system uses JSON Web Tokens (JWT) to help ensure your sessions are as secure as possible.

How do I pass an API authentication token? ›

The second way to pass your API token is via a query parameter called key in the URL like below. Use of the X-Dataverse-key HTTP header form is preferred to passing key in the URL because query parameters like key appear in URLs and might accidentally get shared, exposing your API token. (Again it's like a password.)

How is authentication token better than server side sessions? ›

If your application handles sensitive data or requires rapid revocation, session-based authentication may be the better choice. If your application needs fast, efficient authorization or requires more interaction between the client and server, token-based authentication may be more suitable.

What is the limitation of token authentication? ›

One of the major cons of relying on tokens is that it relies on just one key. Yes, JWT uses only one key, which if handled poorly by a developer/administrator, would lead to severe consequences that can compromise sensitive information.

What are the advantages and disadvantages of token based authentication? ›

This approach enhances security by eliminating the need to transmit sensitive credentials. Tokens serve as temporary authentication keys, granting access to protected resources. They offer advantages like enhanced security, reduced credential exposure, scalability, and the capability for single sign-on.

How token is validated in Web API? ›

Token-Based Authentication operates as follows:

After that, the client sends these credentials (username and password) to the Authorization Server. After that, the Authorization Server validates the client credentials (username and password) and generates and returns an access token.

What is an example of API token authentication? ›

Depending upon the API token authentication process adopted, the process can also use the SSO or Single-Sign-on token. The best example of this is using Facebook login details for 3rd party services. Such tokens remain active only for a limited time and prevent creating different login details for different services.

Where is the token stored in the web API? ›

These can be stored server-side or in a session cookie. The cookie needs to be encrypted and have a maximum size of 4 KB. If the data to be stored is large, storing tokens in the session cookie is not a viable option.

How do I verify my API token? ›

Send a POST request to the /introspect API endpoint to validate your token. The request must provide the token and a basic authorization header that contains the client ID and secret. The server checks the expiry and signature of the token and returns a JSON object that tells whether the token is active or inactive.

Why should we choose token-based authentication? ›

Tokens add a barrier to prevent hackers: A 2FA barrier to prevent hackers from accessing user data and corporate resources. Using passwords alone makes it easier for hackers to intercept user accounts, but with tokens, users can verify their identity through physical tokens and smartphone applications.

Can I use session and JWT together? ›

By combining JWTs with server sessions, we can create a more secure, scalable, and flexible session management system that is suitable for modern web applications. This hybrid approach represents a balanced solution, harnessing the strengths of both JWTs and traditional server-side sessions.

What is the difference between API key authentication and token authentication? ›

The main distinction between these two is: API keys identify the calling project — the application or site — making the call to an API. Authentication tokens identify a user — the person — that is using the app or site.

What is the purpose of token based authentication? ›

It enables users to verify their identity to websites, which then generates a unique encrypted authentication token. That token provides users with access to protected pages and resources for a limited period of time without having to re-enter their username and password.

Why do we need token in API? ›

API calls requires an access token because they provide access a protected resource. Whereas ID tokens are used to provide information about the authenticated user. An example of an API call is making a request with the Management API.

What is the difference between API key and token based authentication? ›

The main distinction between these two is: API keys identify the calling project — the application or site — making the call to an API. Authentication tokens identify a user — the person — that is using the app or site.

Top Articles
How Much Should I Keep in Stocks, Bonds and Cash in Retirement?
Digital Gift Cards VS Virtual Gift Cards: Understanding the Differences
English Bulldog Puppies For Sale Under 1000 In Florida
Katie Pavlich Bikini Photos
Gamevault Agent
Pieology Nutrition Calculator Mobile
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Compare the Samsung Galaxy S24 - 256GB - Cobalt Violet vs Apple iPhone 16 Pro - 128GB - Desert Titanium | AT&T
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Craigslist Dog Kennels For Sale
Things To Do In Atlanta Tomorrow Night
Non Sequitur
Crossword Nexus Solver
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Energy Healing Conference Utah
Geometry Review Quiz 5 Answer Key
Hobby Stores Near Me Now
Icivics The Electoral Process Answer Key
Allybearloves
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Pearson Correlation Coefficient
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Marquette Gas Prices
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Vera Bradley Factory Outlet Sunbury Products
Pixel Combat Unblocked
Movies - EPIC Theatres
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Mia Malkova Bio, Net Worth, Age & More - Magzica
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Topos De Bolos Engraçados
Sand Castle Parents Guide
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Hello – Cornerstone Chapel
Stoughton Commuter Rail Schedule
Nfsd Web Portal
Selly Medaline
Latest Posts
Article information

Author: Errol Quitzon

Last Updated:

Views: 5986

Rating: 4.9 / 5 (79 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Errol Quitzon

Birthday: 1993-04-02

Address: 70604 Haley Lane, Port Weldonside, TN 99233-0942

Phone: +9665282866296

Job: Product Retail Agent

Hobby: Computer programming, Horseback riding, Hooping, Dance, Ice skating, Backpacking, Rafting

Introduction: My name is Errol Quitzon, I am a fair, cute, fancy, clean, attractive, sparkling, kind person who loves writing and wants to share my knowledge and understanding with you.