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.

Developer technologies | ASP.NET | ASP.NET API
{count} votes

3 answers

Sort by: Most helpful
  1. Danny Nguyen (WICLOUD CORPORATION) 5,400 Reputation points Microsoft External Staff Moderator
    2025-07-29T08:03:21.75+00:00

    Hi @Lavanya Chakkaravel , thank you for the detailed code.

    From what I've seen, the problem you're facing is that you're using ASP.NET Core Identity with Entity Framework Core 8 and PostgreSQL, and you'd like to retrieve the refresh token that Identity generates internally.

    The catch is—ASP.NET Identity does not generate refresh tokens by default. It manages login, cookie-based sessions, and optionally JWT access tokens, but it doesn’t include refresh token logic unless you implement it yourself.


    Here’s how you can implement it:

    You’ll need to implement refresh token support manually. Start by creating a model to store refresh tokens:

    public class RefreshToken
    {
        public int Id { get; set; }
        public string Token { get; set; }
        public string UserId { get; set; }
        public IdentityUser User { get; set; }
        public DateTime ExpiryDate { get; set; }
        public bool IsRevoked { get; set; }
    }
    

    Add this to your DbContext:

    public class ApplicationDbContext : IdentityDbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options) { }
     
        public DbSet<RefreshToken> RefreshTokens { get; set; }
    }
    

    Next, during login or token generation, generate and store the refresh token securely:

    public async Task<string> GenerateRefreshTokenAsync(IdentityUser user)
    {
        var refreshToken = new RefreshToken
        {
            Token = Convert.ToBase64String(RandomNumberGenerator.GetBytes(64)),
            UserId = user.Id,
            ExpiryDate = DateTime.UtcNow.AddDays(7),
            IsRevoked = false
        };
     
        _dbContext.RefreshTokens.Add(refreshToken);
        await _dbContext.SaveChangesAsync();
     
        return refreshToken.Token;
    }
    

    When you authenticate a user, return both the access token and the refresh token:

    var accessToken = GenerateAccessToken(user); // Your JWT logic
    var refreshToken = await GenerateRefreshTokenAsync(user);
     
    return Ok(new
    {
        AccessToken = accessToken,
        RefreshToken = refreshToken
    });
    

    Later, when the access token expires, the client can send the refresh token to an endpoint like /api/token/refresh, where you'll validate the token, check expiry/revocation, and then issue a new access token.


    A good implementation guide that mirrors this approach: Using Refresh Tokens in ASP.NET Core Authentication - Code Maze

    Helpful documentations you can checkout:


    Hope this helps! Let me know if you need any additional information or help in implementing this.

    1 person found this answer helpful.

  2. Bruce (SqlWork.com) 81,981 Reputation points Volunteer Moderator
    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

  3. SurferOnWww 4,951 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' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.