[英]How to authenticate from Web API controller endpoint when implementing Identity 2.1 + OWIN OAuth JWT bearer token
作為我的Confirm-User-Signup工作流的一部分,我無法從控制器方法中進行身份驗證,並且正在尋找一些指導,以確保實現正確。
我的控制器方法具有以下代碼; 我已經確認用戶已填充(作為FindById
調用的一部分),但是在SignIn
之后; 未設置this.Authentication.User.Identity
( Name
為空白, IsAuthenticated
為false):
this.Authentication.SignOut("JWT");
ApplicationUser user = await this.AppUserManager.FindByIdAsync(userId);
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(this.AppUserManager, "JWT");
this.Authentication.SignIn(new AuthenticationProperties() { IsPersistent = true }, oAuthIdentity);
使用OWIN OAuth時,這種自動登錄的正確方法是嗎?
完整的控制器方法可以在這里看到: https : //gist.github.com/chrismoutray/8a8e5f6a7b433571613b
作為參考,我一直在關注一個名為Bit of Tech的博客中的一系列文章,該文章使我能夠使用JWT承載令牌設置OWIN OAuth。
第3部分特別討論了JWT(共5個): http : //bitoftech.net/2015/02/16/implement-oauth-json-web-tokens-authentication-in-asp-net-web-api-and-身份-2 /
從我創建的自定義OAuth提供程序的文章中可以繼承自OAuthAuthorizationServerProvider
並實現GrantResourceOwnerCredentials
,並且當我的客戶端代碼(AngularJS)嘗試使用端點/oauth/token
進行身份驗證時,我可以看到它給出了正確的響應和受保護的然后可以訪問端點(使用Authorize屬性)。
因此,通過中間件進行身份驗證確實可行,但是從控制器方法內部進行身份驗證的正確方法是什么?
我認為我應該分享自己想出的解決方案。
簡短的答案; 我創建了一個臨時的一次性密碼(令牌),該密碼將用於首次驗證用戶
要點請參考: https : //gist.github.com/chrismoutray/159e6fd74f45d88efd12
總結–在AccountController ConfirmSignUp
方法中; 我使用用戶管理器生成一個自定義令牌,稱為GRANT-ACCESS
,然后使用uri中的用戶名和令牌重定向到我的confirm-signup
頁面。 我的角度應用程序解析ui路由以confirm-signup
並執行登錄,並將令牌作為密碼傳遞。
var tokenResult = this.AppUserManager.GenerateUserTokenAsync("GRANT-ACCESS", userId);
string token = tokenResult.Result;
Uri redirectLocation = new Uri(
string.Format("http://localhost:45258/#/confirm-signup?user={0}&token={1}",
Uri.EscapeDataString(user.UserName), Uri.EscapeDataString(token)));
return Redirect(redirectLocation);
最后,對GrantResourceOwnerCredentials
了修訂,因此,如果FindAsync
(按用戶名和密碼)沒有返回用戶,則我將再次嘗試,但這一次將context.Password
作為GRANT-ACCESS
用戶令牌進行驗證。 如果令牌有效,那么我將返回JWT身份驗證票證,就像用戶使用有效密碼登錄一樣。
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
... code obmitted
ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
user = await userManager.FindByNameAsync(context.UserName);
... null checks obmitted
string token = context.Password;
bool result = await userManager.VerifyUserTokenAsync(user.Id, "GRANT-ACCESS", token);
}
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT");
var ticket = new AuthenticationTicket(oAuthIdentity, null);
context.Validated(ticket);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.