Gagri Global IT services is having a team of executives who have good experience in developing applications on various platforms like SharePoint 2013/2010, Silverlight, net Framework 4.5 and Mobile tools.

Implementing bearer token in webAPIs

Published on October 18, 2023 by Srinivas & Upendra

Step 1: Install Required NuGet Packages

Install the following packages in your project using NuGet Package Manager:

  1. Microsoft.IdentityModel.Tokens
  2. Microsoft.Owin.Security.Jwt
  3. System.IdentityModel.Tokens.Jwt

Step 2: Create JwtToken Class

Create a JwtToken class in your Models folder. Add the following code to JwtToken.cs:

            using Microsoft.IdentityModel.Tokens;
            using Newtonsoft.Json;
            using System;
            using System.Collections.Generic;
            using System.IdentityModel.Tokens.Jwt;
            using System.Linq;
            using System.Security.Claims;
            using System.Web;
            using static BeartokenProject.Models.Model;

            namespace BeartokenProject.Models
            {
            public class JwtToken
            {
            //Your secret key
            private const string Secret = "Your Secret key";

            public static object GenerateToken(string Client_id)
            {
            List
                accestoken = new List
                    ();
                    var symmetricKey = Convert.FromBase64String(Secret);
                    var tokenHandler = new JwtSecurityTokenHandler();
                    var now = DateTime.UtcNow;
                    var tokenDescriptor = new SecurityTokenDescriptor
                    {
                    Subject = new ClaimsIdentity(new[]
                    {
                    new Claim(ClaimTypes.Name, Client_id)
                    }),
                    Expires = DateTime.Now.AddSeconds(600),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(symmetricKey), SecurityAlgorithms.HmacSha256Signature)
                    };
                    var stoken = tokenHandler.CreateToken(tokenDescriptor);
                    var token = tokenHandler.WriteToken(stoken);
                    response r = new response();
                    r.access_token = token;
                    r.expires_in = 600;
                    r.token_type = "Bearer";

                    var dataString = JsonConvert.SerializeObject(r);
                    return JsonConvert.DeserializeObject(dataString);
                    }

                    public static ClaimsPrincipal GetPrincipal(string token)
                    {
                    try
                    {
                    var tokenHandler = new JwtSecurityTokenHandler();
                    var jwtToken = tokenHandler.ReadToken(token) as JwtSecurityToken;

                    if (jwtToken == null)
                    return null;
                    var symmetricKey = Convert.FromBase64String(Secret);
                    var validationParameters = new TokenValidationParameters()
                    {
                    RequireExpirationTime = true,
                    ValidateIssuer = false,
                    ValidateAudience = false,
                    ClockSkew = TimeSpan.Zero,
                    IssuerSigningKey = new SymmetricSecurityKey(symmetricKey)
                    };
                    SecurityToken securityToken;
                    var principal = tokenHandler.ValidateToken(token, validationParameters, out securityToken);
                    return principal;
                    }
                    catch (Exception)
                    {
                    return null;
                    }
                    }
                    }
                    }
             

Step 3: Create BearerTokenController

Create a controller named BearerTokenController. Add the following code to BearerTokenController.cs:

            using BeartokenProject.Models;
            using BeartokenProject.Filter;
            using System;
            using System.Collections.Generic;
            using System.Linq;
            using System.Web;
            using System.Web.Http;
            using System.Net;

            namespace BeartokenProject.Controllers
            {
            [JwtAuthentication]
            public class BearerTokenController : ApiController
            {
            JwtToken jL = new JwtToken();

            [HttpPost]
            [Route("api/Token/Gettoken")]
            public object Gettoken()
            {
            var Client_id = "1";
            return JwtToken.GenerateToken(Client_id);
            }
            }
            }

Step 4: Create Filter Classes

Create a "Filter" folder and add the following four filter classes:

  1. AddChallengeOnUnauthorizedResult.cs
  2. AuthenticationFailureResult.cs
  3. HttpAuthenticationChallengeContextExtensions.cs
  4. JwtAuthenticationAttribute.cs

Add the appropriate C# code to each of these filter classes.

Step 5: Front-End Code Using Bearer Token

Implement the front-end code to make API requests using the Bearer token. Here's an example of how to call the API using the Bearer token:

            GetCategory() {
               // Call Gettoken and await its completion
            var url = "api/Token/Gettoken";
            this.generalService.GetData(url).then((data: any) => {
            if (data && data.access_token) {
            this.token = data.access_token;
            }
            this.arr = [];
            this.arr.push({
            BLID: this.loginDet.BLID,
            TokenId: this.loginDet.TokenId,
            });
            var UploadFile = new FormData();
            UploadFile.append("Param", JSON.stringify(this.arr));
            UploadFile.append("Flag", '4');
            var url = this.HomeUrl + "your API url";
            var accessToken = this.token; // Use the token obtained from GetToken
               //Set the Authorization header with the access token
            const headers = new HttpHeaders({
            'Authorization': `Bearer ${accessToken}` Prefix "Bearer" is a common convention for JWT tokens
            });
               // Use HttpHeaders in the request
            this.http.post(url, UploadFile, { headers }).subscribe(data => {
            this.dataResult = data;
            },
            err => {
            this.generalService.ShowAlert('ERROR', 'Something went wrong, please try again later', 'error');
            });
            });
            }

Step 6: How to check BearerToken in postman


foot-logo

Here we are click Authentication after that select Bearer Token

foot-logo

This is the getting sp we are not taking any params only passing url

foot-logo

Once generated the token that token will be used in crud methods shown in the above picture

Conclusion:

In this guide, we've explained how to implement Bearer tokens in WebAPIs. By following these steps, you can secure your API endpoints and enable authorization for your web applications.

foot-logo

All design and content Copyright © 2012-2018 Gagri Global IT Services Pvt.Ltd. All rights reserved

Sitemap