在Web API中,我創建了一個TokenAuthentication
屬性來驗證來自客戶端的令牌,然後用戶應該登錄,然後使用我的UserServiceManager
來登錄這樣的:Web Api中的不同Thread.Principal自定義屬性
ApplicationUser aUser = new ApplicationUser();
user.CopyToModel(aUser);
_signInManager.SignIn(aUser, true, true);
//_signInManager.UserManager.CreateIdentity(authenticationType,"")
//var l = _authenticationManager.GetExternalLoginInfo();
////l.Login.
//var authType = _authenticationManager.GetAuthenticationTypes();
//var cliamIdentity = _authenticationManager.CreateTwoFactorRememberBrowserIdentity(aUser.Id);
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, user.UserName));
claims.Add(new Claim(ClaimTypes.Email, user.Email));
claims.Add(new Claim(ClaimTypes.NameIdentifier, user.UserName));
var identity = new ClaimsIdentity(claims, "CustomApiKeyAuth");
var principal = new ClaimsPrincipal(new[] { identity });
Thread.CurrentPrincipal = principal;
System.Web.HttpContext.Current.User = principal;
_authenticationManager.SignIn(new AuthenticationProperties { IsPersistent = true }, identity);
return UpdateResult<SignInStatus>.Success(SignInStatus.Success);
我同時使用Thread.CurrentPrincipal
和System.Web.HttpContext.Current.User
設置主要由於網頁API不同的線程。
我的目的是Thread.CurrentPrincipal.Identity.Name
可以在我的api控制器中使用。然後我設置在我TokenAuthentication
屬性登錄後:
Thread.CurrentPrincipal = System.Web.HttpContext.Current.User;
它不工作,Thread.CurrentPrincipal.Identity.Name
仍處於API空controller.I在我的行動感動上述行和工作,但我不想寫在我的每一個行動。我該怎麼辦?
如果你正在操作,你可以從'Api'屬性調用'User',例如:'this.User'來自'ApiController' –
謝謝,但我有幾個使用Thread.CurrentPrincipal.Identity.Name的服務需要使用這個。我應該在我的動作中將此用戶分配給Thread.CurrentPrincipal。正如我所說的,我不想在我的每一個行動中做這樣的任務。我需要總體發生的事情。 –