2013-07-14 59 views
19

我需要在登錄成功後直接獲取UserId Guid。下面的代碼不起作用:成功登錄後User.Identity.IsAuthenticated爲false

if (Membership.ValidateUser(txtUsername.Value, txtPassword.Value)) 
{ 
    FormsAuthentication.SignOut(); 
    FormsAuthentication.SetAuthCookie(txtUsername.Value, true); 

    if (HttpContext.Current.User.Identity.IsAuthenticated) 
    { 
     // doesn't run 
     Guid puk = (Guid)Membership.GetUser().ProviderUserKey;    
    } 
} 

下面的代碼不工作:

if (Membership.ValidateUser(txtUsername.Value, txtPassword.Value)) 
{ 
    FormsAuthentication.SignOut(); 
    FormsAuthentication.SetAuthCookie(txtUsername.Value, true); 

    MembershipUser user = Membership.GetUser(txtUsername.Value); 

    if (user != null) 
    { 
     Guid puk = (Guid)user.ProviderUserKey; 
    } 
} 

爲什麼會出現這種情況?除了SetAuthCookie還有什麼可做的嗎?

回答

13

因爲當您撥打FormsAuthentication.SetAuthCookie(txtUsername.Value, true);時,您將密鑰存儲在客戶端的Cookie中。爲此,您需要對用戶做出迴應。 而對於HttpContext.Current.User.Identity要填充cookie,您還需要一個請求。

總之你的計劃是這樣的:

  1. 客戶端發送他的用戶名和密碼。

  2. 服務器獲取並檢查它。如果它們有效,則服務器將Set-Cookie標題發送給客戶端。

  3. 客戶端接收並存儲它。對於每個請求客戶端將cookies發送回服務器。

更新@Jake

添加設置User的例子在HttpContext

var identity = new System.Security.Principal.GenericIdentity(user.UserName); 
var principal = new GenericPrincipal(identity, new string[0]); 
HttpContext.Current.User = principal; 
Thread.CurrentPrincipal = principal; 

請注意,您可以創建自定義的主類繼承自GenericPrincipalClaimsPrincipal

+0

有什麼辦法來訪問相同的請求用戶身份? –

+1

@AhmadAhmadi您可以手動將它設置爲將CustomPrincipal對象分配給HttpContext的User屬性。 –

+0

@OleksiiAza你能否更新你的答案來展示如何做到這一點? – Jake

22

我也是同樣的問題。我忘了設置web.config配置。

也許你也錯過了。

<system.web> 
    <authentication mode="Forms"> 
     <forms loginUrl="~/user/login" timeout="1000" name="__Auth" /> 
    </authentication> 
    </system.web> 
0

我嘗試了所有上述解決方案,但解決我的問題的事情是在web.config中

<modules> 
    <remove name="FormsAuthentication"/> 
</modules> 
0

在我的開發環境的情況下評論此,requireSSL屬性設置爲true,我通過將其更改爲requireSSL = false來解決問題。

enter image description here