Search code examples
asp.net-coreasp.net-core-mvcidentityserver4

Can/should IdentityServer4 be used to create a token for user-email verification


I have IdentityServer4 setup for API authentication although I have a use case where I want to verify that a guest (user) is essentially a valid user. A valid user in my case is anyone with a valid email address, so I want to do the following:

  • send the user an email with a verification token (preferably something which is a mash up of their email address, some salt and an expiry
  • the user can then enter this token into my app and they are "allowed" to go ahead

I was wondering if IdentityServer4 can/should be used to achieve the above?

Their tools show that you can generate a token although I am very new to this topic so was hoping for some guidance.


Solution

  • No, the tokens Identity Server deals with are access_tokens which are to do with claims-based authentication.

    The tokens you need to use for email verification are commonly referred to as User Tokens, or one-time passwords (OTP). You can find a wealth of information on how to generate/consume these using those search terms but if you use the aspnet identity classes such as the UserManager you will find it has some in-built read to use. Or you can register your own UserTokenProvider with the UserManager.

    In general you'd do something like this:

    • Use your UserTokenProvider to get a token (otp) for a specific user. The UserManager will use the security hash of that user and your own 'reason' (e.g. "EmailVerification") to generate the short OTP.
    • You could then wrap that OTP into an object that includes the email address, a userid maybe, and whatever you like. Safe Base64 encode it (there is a helper function within Identity Server that has this in fact, making sure it doesn't have the superfluous _ at the end which will mess with HTML links), put it in an email to the user
    • User clicks your link which takes them to your 'verify password' controller, with your mashed up token as payload. You decode it, work out which user it was for, get UserManager to verify the OTP part is still valid.
    • Job done.

    If you want them to enter the OTP into your app directly, while logged in, then you could just skip the whole mash-up part of emailing a link, and email the short OTP directly.