2015-11-10 108 views
0

当我在启动时使用Google身份验证登录时,我可以获取访问令牌。存储外部声明

启动:

app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions() 
{ 
    ClientId = "", 
    ClientSecret = "", 
    Scope = { "" }, 
    Provider = new GoogleOAuth2AuthenticationProvider 
    { 
     OnAuthenticated = async context => 
     { 
      context.Identity.AddClaim(new Claim("googletoken", context.AccessToken)); 
      context.Identity.AddClaim(new Claim(ClaimTypes.Name, context.Name, "http://www.w3.org/2001/XMLSchema#string")); 
      context.Identity.AddClaim(new Claim(ClaimTypes.Email, context.Email, "http://www.w3.org/2001/XMLSchema#string")); 
     } 
    } 
}); 

我的定制要求经理:

public class ClaimManager 
{ 
    private readonly ClaimsIdentity _user; 

    public ClaimManager(ClaimsIdentity user) 
    { 
     this._user = user; 
    } 
    public static string GetAccessToken(ClaimsIdentity user) 
    { 
     var claim = user.Claims.Select(c => new { Type = c.Type, Value = c.Value }).FirstOrDefault(c => c.Type == "googletoken"); 
     return claim == null ? null : claim.Value; 
    } 
    public static string GetName(ClaimsIdentity user) 
    { 
     var claim = user.Claims.Select(c => new { Type = c.Type, Value = c.Value }).FirstOrDefault(c => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"); 
     return claim == null ? null : claim.Value; 
    } 
    public static string GetEmail(ClaimsIdentity user) 
    { 
     var claim = user.Claims.Select(c => new { Type = c.Type, Value = c.Value }).FirstOrDefault(c => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"); 
     return claim == null ? null : claim.Value; 
    } 
} 

访问令牌没有在用户要求仍然存在。我如何坚持要求,让他们留在用户会话?

回答

1

这是我想出的解决方案。我正在存储访问令牌,就像数据库中的常规声明一样。

在帐户控制:

public async Task StoreAccessToken(ExternalLoginInfo loginInfo) 
{ 
    var user = await UserManager.FindAsync(loginInfo.Login); 
    if (user != null) 
    { 
     var newClaim = loginInfo.ExternalIdentity.Claims.Select(c => new Claim(c.Type, c.Value)).FirstOrDefault(c => c.Type == "googletoken"); 

     if (newClaim != null) 
     { 
      var userClaims = await UserManager.GetClaimsAsync(user.Id); 
      foreach (var userClaim in userClaims.Where(c => c.Type == newClaim.Type).ToList()) 
       await UserManager.RemoveClaimAsync(user.Id, userClaim); 

      await UserManager.AddClaimAsync(user.Id, newClaim); 
     } 
    } 
} 

ExternalLoginCallback():

var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(); 
    if (loginInfo == null) 
    { 
     return RedirectToAction("Login"); 
    } 

    await StoreAccessToken(loginInfo); 

ExternalLoginConfirmation():

if (result.Succeeded) 
{ 
    result = await UserManager.AddLoginAsync(user.Id, info.Login); 
    if (result.Succeeded) 
    { 
     await StoreAccessToken(info); 
     await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); 
     return RedirectToLocal(returnUrl); 
    } 
} 
+0

最后一个答案,我可以按照! – hobwell