I'm using Asp.Net Identity. I systematically have an Invalid token error when I want to confirm new users with an email confirmation token.
Here's my WebApi user controller:
public class UsersController : ApiController
{
private MyContext _db;
private MyUserManager _userManager;
private MyRoleManager _roleManager;
public UsersController()
{
_db = new MyContext();
_userManager = new MyUserManager(new UserStore<MyUser>(_db));
_roleManager = new MyRoleManager(new RoleStore<IdentityRole>(_db));
}
//New user method
[HttpPost]
public async Task<HttpResponseMessage> Register([FromBody]PostUserModel userModel)
{
//New user code
...
var token = await _userManager.GenerateEmailConfirmationTokenAsync(user.Id);
var message = new IdentityMessage();
message.Body = string.Format("Hi {0} !\r\nFollow this link to set your password : \r\nhttps://www.mywebsite.com/admin/users/{1}/reset?token={2}", user.UserName, user.Id, HttpUtility.UrlEncode(token));
message.Subject = "Confirm e-mail";
message.Destination = user.Email;
await _userManager.SendEmailAsync(user.Id, message.Subject, message.Body);
return Request.CreateResponse(HttpStatusCode.OK, res); }
}
To confirm the email, I'm just doing :
var result = await _userManager.ConfirmEmailAsync(user.Id, token);
I'm not doing an HttpUtility.UrlDecode because WebApi does it by itself.
And my custom user manager class :
public class MyUserManager : UserManager<MyUser>
{
public MyUserManager(IUserStore<MyUser> store)
: base(store)
{
UserValidator = new UserValidator<MyUser>(this)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};
// Configure user lockout defaults
UserLockoutEnabledByDefault = false;
EmailService = new EmailService();
SmsService = new SmsService();
var dataProtectionProvider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("MyApp");
UserTokenProvider = new Microsoft.AspNet.Identity.Owin.DataProtectorTokenProvider<MyUser>(dataProtectionProvider.Create("UserToken"));
}
}
}
Any idea ? Thank you very much