我正在构建一个使用cookie身份验证作为主要身份验证方法的MVC 5 Web应用程序 .

我们的申请流程如下:

  • 首次使用用户名/密码注册以创建IdentityUser .

  • 用户使用其用户名/密码登录

  • 用户将一个或多个Google和/或Microsoft帐户与其"local"帐户相关联 .

  • OWIN Google和Microsoft提供商处理外部身份验证 .

  • 我们使用简单的委托方法来读取返回的access_token和refresh_token,并将其存储为身份声明 .

  • 我们使用访问令牌在服务器端进行API调用 .

  • 当一个过期时,我们使用刷新令牌获取新的访问令牌 .

问题是,实现访问令牌验证,到期和续订的最佳位置是什么 . 如果有人能引导我走向正确的方向,我真的很感激 .

var googleCreds = new GoogleOAuth2AuthenticationOptions
{
    ClientId = "833250754551-qg564a5g29f0l37q0egqimcoklpjf6dj.apps.googleusercontent.com",
    ClientSecret = "YpY_u07KQU4kjhPWH5vuiMzz"
    Provider = new Microsoft.Owin.Security.Google.GoogleOAuth2AuthenticationProvider
    {
        OnApplyRedirect = context =>
        {
            var queryString = HttpContext.Current.Request.QueryString.ToString();
            var queryParms = HttpUtility.ParseQueryString(queryString);

            string redirect = context.RedirectUri;
            redirect += "&access_type=offline";
            redirect += "&approval_prompt=force";
            redirect += "&include_granted_scopes=true";

            var uri = new Uri(redirect);

            if ((!string.IsNullOrEmpty(queryParms.Get("scope"))))
            {
                var scope = queryParms.Get("scope");
                var redirectQueryString = HttpUtility.ParseQueryString(uri.Query);
                switch (scope)
                {
                    case "GooglePlus":
                        redirectQueryString.Set("scope", "https://www.googleapis.com/auth/plus.login");
                        break;
                    case "YoutTube":
                        redirectQueryString.Set("scope", "https://gdata.youtube.com");
                        break;
                    default:
                        throw new Exception("Invalid scope passed in: scope: " + scope);
                }

                redirect = uri.GetLeftPart(UriPartial.Path) + "?" + redirectQueryString.ToString();
            }

            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));
            context.Identity.AddClaim(new Claim("urn:tokens:google:accesstokenexpiry", DateTime.Now.Add(expiryDuration).ToString()));

            return Task.FromResult<object>(null);
        }
    }
}; 

app.UseGoogleAuthentication(googleCreds);