How to get Access token and refresh token from in-built Asp.Net Identity Authentication (Internal memory)

Lavanya Chakkaravel 20 Reputation points
2025-05-02T07:09:26.4366667+00:00

Hi,

I am using Microsoft.EntityFrameworkCore (Version 8.0.6) + Microsoft.AspNetCore.Identity.EntityFrameworkCore(Version 8.0.6) + Npgsql.EntityFrameworkCore.PostgreSQL (Version 8).

I want to get refresh token which it is automatically generated by Identity Framework. After I retrieve that token, i want to save in database.

Here sample startup.cs file,

sing Microsoft.AspNetCore.Identity;

using Microsoft.EntityFrameworkCore;

using Microsoft.Extensions.DependencyModel;

using Microsoft.OpenApi.Models;

using Swashbuckle.AspNetCore.Filters;

using AutoMapper;

using Microsoft.Extensions.Configuration;

using Microsoft.AspNetCore.Rewrite;

using Microsoft.AspNetCore.Identity.UI.Services;

using Npgsql;

using Microsoft.Extensions.DependencyInjection;

using Microsoft.Extensions.Hosting;

var builder = WebApplication.CreateBuilder(args);

var allowAllOrigins = "AllowAllOriginsPolicy";

builder.Services.AddCors(options =>

{

    options.AddPolicy(allowAllOrigins,

        policy =>

        {

            policy.AllowAnyOrigin()

                .AllowAnyHeader()

                .AllowAnyMethod();

        });

});

builder.Services.AddEndpointsApiExplorer();

builder.Services.AddSwaggerGen(options =>

{

    options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme

    {

        In = ParameterLocation.Header,

        Name = "Authorization",

        Type = SecuritySchemeType.ApiKey

    });

    options.OperationFilter

});

builder.Services.AddAutoMapper(cfg =>

{

    cfg.CreateMap

  });

var dataSourceBuilderSource = new NpgsqlDataSourceBuilder(builder.Configuration.GetConnectionString("DefaultConnection"));

dataSourceBuilderSource.EnableDynamicJson();

var dataSourceBuilder = dataSourceBuilderSource.Build();

builder.Services.AddDbContext

    options.UseNpgsql(dataSourceBuilder);

});

builder.Services.AddAuthorization();

builder.Services.AddIdentityApiEndpoints

    .AddRoles

    .AddEntityFrameworkStores

builder.Services.AddHttpContextAccessor();

builder.Services.AddScoped

builder.Services.AddScoped

builder.Services.AddSingleton

builder.Services.RegisterAccountModule();

var app = builder.Build();

using (var scope = app.Services.CreateScope())

{

    var applicationDbContext = scope.ServiceProvider.GetRequiredService

    applicationDbContext.Database.Migrate();

}

app.UseSwagger();

app.UseSwaggerUI();

app.MapIdentityApi

app.UseHttpsRedirection();

app.UseCors(allowAllOrigins);

app.UseAuthorization();

app.MapEndpoints();

app.Run();

Note: The above configuration will auto provide access and refresh token and have it in internal storage. I want to get that token and wants to store in database.

ASP.NET API
ASP.NET API
ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
420 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 75,051 Reputation points
    2025-05-02T15:48:39.86+00:00

    The builtin token caching uses the distributed cache. While there is Sqlserver and CosmosDb backed cache, there isn’t one for PostgreSQL. You would need to code one:

    https://learn.microsoft.com/en-us/aspnet/core/performance/caching/distributed?view=aspnetcore-9.0#idistributedcache-interface

    Alternatively you can just create a table, and store the token during authentication. Typically the user name is used as a key.

    note: your use case seems unclear. You appear to be creating a webapi, which would not need to store the access and refresh tokens, as the client needs a valid access token to call the webapi. If the access token is expired, how would the client call the webapi to get the refresh token?

    more confusing is you called AddIdentityApiEndpoints and MapIdentityApi, meaning the site is a SPA application. So the webapi is generating tokens for the login request. Again the client should store these, not the server. When a request comes, how would the server know which token belongs to the user?

    0 comments No comments

  2. SurferOnWww 4,391 Reputation points
    2025-05-03T02:05:21.9+00:00

    I want to get refresh token which it is automatically generated by Identity Framework. After I retrieve that token, i want to save in database.

    Below is only my idea. Please note that I don't know if it is right answer you need as your question does not make sense to me.

    Please see my answer in how to implement JWT token using .net core 8 web api.

    In the code at the step (5) in my answer, tokenString is "token which it is automatically generated by Identity Framework". After the line of var tokenString = BuildToken(); you will be able to add your code which can save the generated token to your database as required.

    public IActionResult CreateToken([FromBody] LoginModel login)
    {
        string? id = login.Username;
        string? pw = login.Password;
        IActionResult response = Unauthorized();
    
        if (!string.IsNullOrEmpty(id) && !string.IsNullOrEmpty(pw))
        {
            if (VerifyUser(id, pw))
            {
                // token generated by Identity Framework
                var tokenString = BuildToken();
    
                // write your code to save token to database as required (code omitted)
    
                response = Ok(new { token = tokenString });
            }
        }
    
        return response;
    }
    

    If above does not satisfy your requirement, please let me know the difference from your requirements in detail.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.