Giraffe: How to use custom token providers

Created on 21 Apr 2019  路  2Comments  路  Source: giraffe-fsharp/Giraffe

I want to override the email token lifespan in ASPNET, but it is not working. I am trying this with the sample IdentityApp. I created a branch and made the changes in the IdentityApp.

You can see my code here. And I am following the user guide here.

Basically you need to create a custom token provider and add a ProviderMap to the Identity configuration at startup.

In services.AddIdentity

            options.Tokens.ProviderMap.Add("CustomEmailConfirmation", 
                new TokenProviderDescriptor(typedefof<CustomEmailConfirmationTokenProvider<IdentityUser>>))
            options.Tokens.EmailConfirmationTokenProvider <- "CustomEmailConfirmation"

to services

    services.AddTransient<CustomEmailConfirmationTokenProvider<IdentityUser>>() |> ignore

The app loads, but I get an error when I try to get at the UserManager when I submit a registration.

            let  userManager = ctx.GetService<UserManager<IdentityUser>>()

This is the error.

No service for type 'CustomTokenProviders+CustomEmailConfirmationTokenProvider`1[TUser]' has been registered.

I am assuming I am not registering the provider correctly. Maybe it is as simple as my CustomEmailConfirmationTokenProvider is not setup correctly? Any help is appreciated.

It works when I run the sample app from the ASPNET user guide.

My workaround at the moment it to instead override the default token provider options like this

   services.Configure<DataProtectionTokenProviderOptions>(fun (o:DataProtectionTokenProviderOptions) -> 
       o.TokenLifespan <- TimeSpan.FromMinutes(5.0)) |> ignore

This works but changes all of the tokens, not just email.

question

All 2 comments

Hi,

Thanks for providing such a detailed issue, made my life super easy to find out what had to be changed :).

You've got it almost right, but there is a minor difference between typeof and typedefof and in your code you must use typeof when adding the TokenProviderDescriptor:

options.Tokens.ProviderMap.Add(
                "CustomEmailConfirmation",
               TokenProviderDescriptor(typeof<CustomEmailConfirmationTokenProvider<IdentityUser>>))

After I've made this change then I was able to successfully run the register code in your IdentityApp.

Hope this helps and let me know if there is anything else I can help with!

Thank you! It's working in my IdentityApp and in my big Saturn app, now, too.

Ya know, I had actually tried this but at the time I has still getting the same error. I guess I must have fixed a different problem but left myself with this one.

Was this page helpful?
0 / 5 - 0 ratings