Forum Discussion

saralbreak's avatar
saralbreak
Copper Contributor
Feb 25, 2024

.Net 8 web API with identity Bearer token

I am using .NET 8 Bearer Token not JWT token and I want to check if it is expired from my client app. Is there any way I can decode it or at least check if it is expired or not? Is there a way I can create a service that decode the token or check it is expired or no? Also, how can I know what is the secret key of the token?

Program.cs:

 

 

using EmployeeManagement.Database;
using EmployeeManagement.Entities;
using EmployeeManagement.Shared.Common;
using EmployeeManagement.Shared.Configrations;
using EmployeeManagement.Shared.Services.Department;
using EmployeeManagement.Shared.Services.Employee;
using EmployeeManagement.Shared.Services.UserRole;
using EmployeeManagement.Shared.Services.VacationRequests;
using FluentValidation;
using FluentValidation.AspNetCore;
using Microsoft.AspNetCore.Authentication.Certificate;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.Filters;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();

builder.Services.AddSwaggerGen(options =>
{
    options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
    {
        In = ParameterLocation.Header,
        Name = "Authorization",
        Type = SecuritySchemeType.ApiKey
    });
    options.OperationFilter<SecurityRequirementsOperationFilter>();
});

builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection") ?? 
    throw new InvalidOperationException( "Connection string Not found")));

builder.Services.AddAuthorization();


builder.Services.AddIdentityApiEndpoints<ApplicationUser>()
    .AddRoles<IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>();

builder.Services.AddAuthentication().AddJwtBearer();

builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
});
builder.Services.AddAutoMapper(
    typeof(EmployeeMapperConfig),
    typeof(UserRoleReMapperConfig),
    typeof(DepartmentMapperConfig),
    typeof(VacationRequestsMapperConfig),
    typeof(ApplicationUserMapperConfig)
 );
builder.Services.AddScoped<IEmployeeService, EmployeeService>();
builder.Services.AddScoped<IUserRole, UserRoleService>();
builder.Services.AddScoped<IDepartmentService, DepartmentServices>();
builder.Services.AddScoped<IVacationRequestsService, VacationRequestsService>();

builder.Services.AddFluentValidation();
builder.Services.AddValidatorsFromAssemblyContaining<IAssemblyMarker>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.MapIdentityApi<ApplicationUser>();

app.UseCors(options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

 

 

Angular app:

Here I got an exception when I decode the Toke, the exception shows that the token is not in a proper JWT format, because it is Bearer token not a JWT. I want to create my own API and call it here to validate the Token.

 

import { HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { jwtDecode } from 'jwt-decode';
import { EmployeeManagementWebAPIService } from '../api/employee-management-web-api.service';
import { RefreshRequest } from '../model/refresh-request';
import { Router } from '@angular/router';

export const tokenInterceptorInterceptor: HttpInterceptorFn = (req, next) => {
  console.log("tokenInterceptorInterceptor+++");
  let authService = inject(EmployeeManagementWebAPIService);
  let router = inject(Router);
  const AccessToken = localStorage.getItem('AccessToken');
  const RefreshToken = localStorage.getItem('RefreshToken');
  if (AccessToken) {
    console.log("tokenInterceptorInterceptor++999+"+AccessToken);
   try{
    let decodedToken = jwtDecode(AccessToken);
    console.log("decodedToken+++" + decodedToken);
    const isExpired =
      decodedToken && decodedToken.exp
        ? decodedToken.exp < Date.now() / 1000
        : false;

    if (isExpired) {
      console.log('token is expired');
      const refreshRequest: RefreshRequest = {
        refreshToken: RefreshToken,
      };
      authService.refreshPost(refreshRequest).subscribe(
        (newToken: any) => {
          localStorage.setItem('AccessToken', newToken);
          req.clone({
            setHeaders: {
              Authorization: `Bearer ${newToken}`,
              'Content-Type': 'application/json', // Set content type here
            },
          });
          console.log('Refresh token successful:', newToken);
        },
        (error) => {
          // Handle error response here
          localStorage.removeItem("AccessToken");
          router.navigateByUrl('/login');
          console.error('Error refreshing token:', error);
        }
      );
    }
    else{
      console.error('Token not expired');
    }
   }catch(e){
      console.log("invalid token" , e);
      localStorage.removeItem("AccessToken");
      router.navigateByUrl('/login');
   }
  }
  else{
    console.error('Token Not found');
    router.navigateByUrl('/login');
  }
  return next(req);
};

 

 

my login response:

 

 

{
  "tokenType": "Bearer",
  "accessToken": "",
  "expiresIn": 3600,
  "refreshToken": ""
}

 

1 Reply

  • TohidAzizi's avatar
    TohidAzizi
    Copper Contributor
    I have the same problem with standalone Blazor Wasm. Is there a way to *decode* Microsoft Identity 8 token?

Resources