2009-09-27 137 views
4

我剛開始嘗試DotNetOpenAuth項目。修改樣本OpenIdRelyingPartyMvc項目,我能夠獲得ClaimRequest電子郵件與谷歌合作。爲什麼我的ClaimsRequest會返回null?

但是,當我嘗試將OpenID添加到我自己的項目中時,ClaimResponse始終返回null。我想知道是否有我缺少的項目或環境設置?

這裏是我的Authenticate方法:

public ActionResult Authenticate(string returnUrl) 
{ 
    var response = openid.GetResponse(); 
    if (response == null) 
    { 
     // Stage 2: user submitting Identifier 
     Identifier id; 
     if (Identifier.TryParse(Request.Form["openid_identifier"], out id)) 
     { 
      try 
      { 
       IAuthenticationRequest req = openid.CreateRequest(Request.Form["openid_identifier"]); 
       req.AddExtension(new ClaimsRequest { Email = DemandLevel.Require }); 
       return req.RedirectingResponse.AsActionResult(); 
      } 
      catch (ProtocolException ex) 
      { 
       ViewData["Message"] = ex.Message; 
       return View("Login"); 
      } 
     } 
     else 
     { 
      ViewData["Message"] = "Invalid identifier"; 
      return View("Login"); 
     } 
    } 
    else 
    { 
     // Stage 3: OpenID Provider sending assertion response 
     switch (response.Status) 
     { 
      case AuthenticationStatus.Authenticated: 
       ClaimsResponse sreg = response.GetExtension<ClaimsResponse>(); 
       if (sreg != null) 
       { 
        var email = sreg.Email; 
        Session["Email"] = email; 
       } 
       Session["FriendlyIdentifier"] = response.FriendlyIdentifierForDisplay; 
       FormsAuthentication.SetAuthCookie(response.ClaimedIdentifier, false); 
       if (!string.IsNullOrEmpty(returnUrl)) 
       { 
        return Redirect(returnUrl); 
       } 
       else 
       { 
        return RedirectToAction("Index", "Home"); 
       } 
      case AuthenticationStatus.Canceled: 
       ViewData["Message"] = "Canceled at provider"; 
       return View("Login"); 
      case AuthenticationStatus.Failed: 
       ViewData["Message"] = response.Exception.Message; 
       return View("Login"); 
     } 
    } 
    return new EmptyResult(); 
} 

}

回答

11
<configuration> 
     <configSections> 
      <section name="dotNetOpenAuth" type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection" requirePermission="false" allowLocation="true"/> 
     </configSections> 
     <dotNetOpenAuth> 
      <openid> 
      <relyingParty> 
       <behaviors> 
        <!-- The following OPTIONAL behavior allows RPs to use SREG only, but be compatible 
         with OPs that use Attribute Exchange (in various formats). --> 
        <add type="DotNetOpenAuth.OpenId.Behaviors.AXFetchAsSregTransform, DotNetOpenAuth" /> 
       </behaviors> 
      </relyingParty> 
      </openid> 
     </dotNetOpenAuth> 
    </configuration> 

http://dotnetopenauth.net:8000/wiki/CodeSnippets/OpenIDRP/AXFetchAsSregTransform

添加的配置信息,以你的web.config。

谷歌有一個獨特的特質,因爲它忽略了標記爲「可選」的所有屬性請求。您必須要求用戶的電子郵件地址爲「必填」,才能從Google獲取電子郵件地址。請注意,根據需要標記該屬性,Google將拒絕驗證用戶,除非用戶願意放棄其電子郵件地址。因此,如果您實際上並不需要電子郵件地址,最好將其標記爲可選,然後放棄Google用戶,以避免強制用戶放棄其電子郵件地址不想。