2014-10-11 93 views
0

我知道有很多關於此主題的信息,但我似乎無法找到適合我的具體需求的答案: 我打開了一個新的MVC 4.0 基本應用程序(意思是,不存在「AuthConfig.cs」文件)。 我已經成功實施了Facebook登錄。 我似乎無法找到任何方式對Google執行相同操作。MVC 4.0 - 使用Google登錄

我已經有一個自定義「連接谷歌」按鈕。我需要一個非常簡單的代碼來使用谷歌進行身份驗證。請記住,認證後,我需要獲取用戶信息,並獲取用戶的日曆。

請幫忙

謝謝。

回答

0

一些代碼,以幫助您開始

在AuthConfig文件

OAuthWebSecurity.RegisterClient(new Mvc.GoogleCustomClient(), "Google", null); 

在GoogleCustomClient.cs

public class GoogleCustomClient : OpenIdClient 
{ 


    public GoogleCustomClient() 
     : base("google", WellKnownProviders.Google) { } 



    /// <summary> 
    /// Gets the extra data obtained from the response message when authentication is successful. 
    /// </summary> 
    /// <param name="response"> 
    /// The response message. 
    /// </param> 
    /// <returns>A dictionary of profile data; or null if no data is available.</returns> 
    protected override Dictionary<string, string> GetExtraData(IAuthenticationResponse response) 
    { 
     FetchResponse fetchResponse = response.GetExtension<FetchResponse>(); 
     if (fetchResponse != null) 
     { 
      var extraData = new Dictionary<string, string>(); 
      extraData.Add("email", fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.Email)); 
      extraData.Add("country", fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.HomeAddress.Country)); 
      extraData.Add("firstName", fetchResponse.GetAttributeValue(WellKnownAttributes.Name.First)); 
      extraData.Add("lastName", fetchResponse.GetAttributeValue(WellKnownAttributes.Name.Last)); 

      return extraData; 
     } 

     return null; 
    } 

    /// <summary> 
    /// Called just before the authentication request is sent to service provider. 
    /// </summary> 
    /// <param name="request"> 
    /// The request. 
    /// </param> 
    protected override void OnBeforeSendingAuthenticationRequest(IAuthenticationRequest request) 
    { 
     // Attribute Exchange extensions 
     var fetchRequest = new FetchRequest(); 
     fetchRequest.Attributes.AddRequired(WellKnownAttributes.Contact.Email); 
     fetchRequest.Attributes.AddRequired(WellKnownAttributes.Contact.HomeAddress.Country); 
     fetchRequest.Attributes.AddRequired(WellKnownAttributes.Name.First); 
     fetchRequest.Attributes.AddRequired(WellKnownAttributes.Name.Last); 

     request.AddExtension(fetchRequest); 
    } 


} 

您可以使用此代碼檢索從谷歌的用戶信息。

+0

嗨,感謝Kumer的重播,但正如我所說,這是一個基本的MVC應用程序,我沒有AuthConfig .. – 2014-10-16 08:03:45