Using AspNetUserTokens table to store refresh token in ASP.NET Core Web Api

落爺英雄遲暮 提交于 2019-12-04 00:05:21
Chris Schoon

I’ll answer your question directly then propose an alternative. You can Remove, Set, Get, and Validate tokens with the AspNetUserTokens table. However, you can probably skip the db and I'll describe that below.

The following methods of the UserManager will generate and store:

await _userManager.RemoveAuthenticationTokenAsync(user, "MyApp", "RefreshToken");
var newRefreshToken = await _userManager.GenerateUserTokenAsync(user, "MyApp", "RefreshToken");
await _userManager.SetAuthenticationTokenAsync(user, "MyApp", "RefreshToken", newRefreshToken);

The following methods of the UserManager will get and validate:

var refreshToken = await _userManager.GetAuthenticationTokenAsync(user, "MyApp", "RefreshToken");
var isValid = await _userManager.VerifyUserTokenAsync(user, "MyApp", "RefreshToken", refreshToken );

You will need to set up a provider like this using the IdentityBuilder in Startup.

identity.AddTokenProvider("MyApp", typeof(DataProtectorTokenProvider<User>)

As an alternative to storing these tokens in the database, you can use the following to invalidate all tokens as needed. You might do this as a part of Logout.

_userManager.UpdateSecurityStampAsync(user);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!