您可以在 MVC5 Startup.Auth.cs 文件中自定义 GoogleOAuth2AuthenticationOptions 以请求离线访问代码和刷新令牌以用于 Google 的 OAuth2 api。
在此示例中,我收集从 google 传递到 OWIN OAuth2 中间件的值,并将它们添加到您的 Callback 方法中可访问的声明中。
var googleCreds = new GoogleOAuth2AuthenticationOptions
{
ClientId = "[replace with your google console issued client id]",
ClientSecret = "[replace with your google console issued client secret]",
Provider = new Microsoft.Owin.Security.Google.GoogleOAuth2AuthenticationProvider
{
OnApplyRedirect = context =>
{
string redirect = context.RedirectUri;
redirect += "&access_type=offline";
redirect += "&approval_prompt=force";
redirect += "&include_granted_scopes=true";
context.Response.Redirect(redirect);
},
OnAuthenticated = context =>
{
TimeSpan expiryDuration = context.ExpiresIn ?? new TimeSpan();
context.Identity.AddClaim(new Claim("urn:tokens:google:email", context.Email));
context.Identity.AddClaim(new Claim("urn:tokens:google:url", context.GivenName));
if (!String.IsNullOrEmpty(context.RefreshToken))
{
context.Identity.AddClaim(new Claim("urn:tokens:google:refreshtoken", context.RefreshToken));
}
context.Identity.AddClaim(new Claim("urn:tokens:google:accesstoken", context.AccessToken));
if (context.User.GetValue("hd") != null)
{
context.Identity.AddClaim(new Claim("urn:tokens:google:hd", context.User.GetValue("hd").ToString()));
}
context.Identity.AddClaim(new Claim("urn:tokens:google:accesstokenexpiry", DateTime.UtcNow.Add(expiryDuration).ToString()));
return System.Threading.Tasks.Task.FromResult<object>(null);
}
}
};
googleCreds.Scope.Add("openid");
googleCreds.Scope.Add("email");
app.UseGoogleAuthentication(googleCreds);
现在您可以通过回调方法访问这些声明值。例如:
var loginInfo = AuthenticationManager.GetExternalLoginInfo();
string GoogleAccessCode = String.Empty;
if (loginInfo.ExternalIdentity.Claims.FirstOrDefault(c => c.Type.Equals("urn:tokens:google:accesstoken")) != null)
{
GoogleAccessCode = loginInfo.ExternalIdentity.Claims.FirstOrDefault(c => c.Type.Equals("urn:tokens:google:accesstoken")).toString();
}
在身份验证序列开始时,或在您完成 AuthenticationManager.GetExternalLoginInfo() 之后,您可以清除浮动的外部身份验证 cookie,以防止任何有问题的重复 cookie 堆积:
if (Request.Cookies[".AspNet.ExternalCookie"] != null)
{
var c = new System.Web.HttpCookie(".AspNet.ExternalCookie");
c.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(c);
}