2014-01-23 17 views
2

我試圖在用戶使用Google帳戶登錄到我的MVC5網站時獲取用戶的出生日期和頭像/圖標/照片/圖片。使用MVC5 GoogleAuthenticationOptions在身份驗證期間獲取額外的用戶配置文件信息

我讀過這樣的:

Get ExtraData from MVC5 framework OAuth/OWin identity provider with external auth provider

但它並沒有多大意義......我,我想知道這一點?

在我Startup.Auth.cs文件我有這樣的片段:

var gProvider = new GoogleAuthenticationProvider { OnAuthenticated = context => { var claims = context.Identity.Claims.ToList(); return Task.FromResult(0); } }; 
var gOptions = new GoogleAuthenticationOptions { Provider = gProvider }; 
app.UseGoogleAuthentication(gOptions); 

索賠變量包含5個項目:(每個項目以 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/')

0: { nameidentifier: https://www.google.com/accounts/.../id?id... } 
1: { givenname: Benjamin } 
2: { surname: Day } 
3: { name: Benjamin Day } 
4: { emailaddress: [email protected] } 

誰能幫助指出我做錯了什麼,或者我錯過了什麼來獲取我正在尋找的額外配置文件數據?

回答

4

如果簡而言之,您必須使用與Google的OAuth 2.0集成,而不是默認啓用的Open ID。

public class CustomGoogleProvider : GoogleOAuth2AuthenticationProvider 
{ 
    public override Task Authenticated(GoogleOAuth2AuthenticatedContext context) 
    { 
     context.Identity.AddClaim(new Claim("picture", context.User.GetValue("picture").ToString())); 
     context.Identity.AddClaim(new Claim("profile", context.User.GetValue("profile").ToString())); 

     return base.Authenticated(context); 
    } 
} 

並使用它作爲

var googleOAuth2AuthenticationOptions = new GoogleOAuth2AuthenticationOptions 
    { 
     ClientId = "{{Your Client Id}}", 
     ClientSecret = "{{Your Client Secret}}", 
     CallbackPath = new PathString("/Account/ExternalGoogleLoginCallback"), 
     Provider = new CustomGoogleProvider(), 
    }; 

    googleOAuth2AuthenticationOptions.Scope.Add("email"); 

    app.UseGoogleAuthentication(googleOAuth2AuthenticationOptions); 

我所描述的過程在細節here

相關問題