0

在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.CurrentPrincipalSystem.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在我的行動感動上述行和工作,但我不想寫在我的每一個行動。我該怎麼辦?

+0

如果你正在操作,你可以從'Api'屬性調用'User',例如:'this.User'來自'ApiController' –

+0

謝謝,但我有幾個使用Thread.CurrentPrincipal.Identity.Name的服務需要使用這個。我應該在我的動作中將此用戶分配給Thread.CurrentPrincipal。正如我所說的,我不想在我的每一個行動中做這樣的任務。我需要總體發生的事情。 –

回答

0

其實我決定創建一個從AuthorizeAttribute繼承的屬性來解決問題,而不是在每個動作中重複賦值。但看完AuthorizeAttribute source後,我發現另一種解決方案:

actionContext.ControllerContext.RequestContext.Principal = System.Web.HttpContext.Current.User; 

這是寫在自定義tokenAuthentication屬性,而不是Thread.CurrentPrincipal = System.Web.HttpContext.Current.User和它的工作。現在,api控制器中的Thread.CurrentPrincipal具有正確的主體。