IdentityServer4 - How to store refresh token into database using mysql.data?

Mini Dev 1 picture Mini Dev 1 · Nov 15, 2017 · Viewed 9.5k times · Source

I'm new at IdentityServer4. I read I need to implement an IPersistedGrantStore to store refresh tokens into a table like PersistedGrants in my database.

IdentityServer logs is the following when my native app ask for a new access token: "refresh_token" grant with value: "{value}" not found in store.

That's because I'm using in-memory version of the persisted grant store. So I need to store refresh token in a PersistedGrant table.

Therefore in my startup.cs I added the following line:

builder.Services.AddScoped<IPersistedGrantStore, PersistedGrantStore>();

and IPersistedGrantStore.cs is

public interface IPersistedGrantStore
{        
    Task StoreAsync(CustomPersistedGrant grant);

    Task<CustomPersistedGrant> GetAsync(string key);

    Task<IEnumerable<CustomPersistedGrant>> GetAllAsync(string subjectId);        
}

So I have a CustomPersistedGrant.cs class

public class CustomPersistedGrant
{
    public string Key { get; set; }

    public string Type { get; set; }

    public string SubjectId { get; set; }

    public string ClientId { get; set; }

    public DateTime CreationTime { get; set; }

    public DateTime? Expiration { get; set; }

    public string Data { get; set; }
}

and now I have to write the code for my PersistedGrantStore.cs class. But the question is: once I have write code for PersistedGrantStore.cs class where I call PersistedGrantStore.cs class? In Identity.Server Account/AccountController? I didn't find any example about it without use EntityFramework, because I don't want to use Entity Framework.

Thanks.

Answer

Jim Counts picture Jim Counts · Nov 16, 2017

The key will be to implement IPersistedGrantStore using whatever backend you like, then to tell IdentityServer to use that implementation by registering the implementation in the dependency injection system.

For example, if you call your implementation PersistedGrantStore, then you could register the implementation like this:

services.AddTransient<IPersistedGrantStore, PersistedGrantStore>();

You can see that essentially this is all that the EntityFramework implementation does, once you take away all the EntityFramework stuff.

Later when IdentityServer wants to persist a grant, it will get your implementation and call the appropriate method. So you don't have to do anything, other than inject your implementation into IdentityServer so it can do whats needed.