我按照本教程在webapi中实现了外部登录提供程序: http://bitoftech.net/2014/08/11/asp-net-web-api-2-external-logins-social-logins-facebook-google-angularjs-app/
我还希望在此解决方案中包含刷新令牌。我设法按照这篇文章在常规登录方案中执行此操作 - http://bitoftech.net/2014/07/16/enable-oauth-refresh-tokens-angularjs-app-using-asp-net-web-api-2-owin/
不幸的是我不知道如何为外部登录做这件事。我已经研究了OWIN的实现,并尝试做类似下面的代码。它会生成令牌但我在序列化票证时遇到问题(当我尝试根据以这种方式生成的刷新令牌生成新的访问令牌请求时,票证不能不受保护。)
private async Task<JObject> GenerateLocalAccessTokenResponse(string userId)
{
var tokenExpiration = TimeSpan.FromDays(1);
ClaimsIdentity identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);
var user = await GetUser(userId);
identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
identity.AddClaim(new Claim("role", "user"));
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));
var props = new AuthenticationProperties()
{
IssuedUtc = DateTime.UtcNow,
ExpiresUtc = DateTime.UtcNow.Add(tokenExpiration),
};
var ticket = new AuthenticationTicket(identity, props);
var accessToken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket);
// This is what I added
var context = Request.GetOwinContext();
// Here I use a DataProtectionProvider which I generated on startup with app.GetDataProtectionProvider() and I keep it as a static object
var secureDataFormat = new TicketDataFormat(Helpers.Providers.DataProtectionProvider.Create(
typeof(OAuthAuthorizationServerMiddleware).Namespace, "Refresh_Token", "v1", "ASP.NET Identity"));
var createContext = new AuthenticationTokenCreateContext(context, secureDataFormat, ticket);
await Startup.OAuthServerOptions.RefreshTokenProvider.CreateAsync(createContext);
JObject tokenResponse = new JObject(
new JProperty("userName", user.UserName),
new JProperty("access_token", accessToken),
new JProperty("token_type", "bearer"),
new JProperty("expires_in", tokenExpiration.TotalSeconds.ToString()),
new JProperty(".issued", ticket.Properties.IssuedUtc.ToString()),
new JProperty(".expires", ticket.Properties.ExpiresUtc.ToString()),
new JProperty("refresh_token", createContext.Token)
);
return tokenResponse;
}