测试 build-in MVC 5 OAuth2/OpenID providers 后我能够创建一个网站,该网站允许我使用我的 Twitter 凭据对自己进行身份验证。
我现在遇到的问题是,我还想存储 token (oauth_token & oauth_verifier) Twitter posts back, in the url, a user has been successful认证。我需要这些 token ,这样我就可以允许用户将详细信息直接从我的网站发布到他们的 Twitter 帐户。
在 Startup.Auth.cs 中设置了 TwitterAuthenticationOptions(见下文)后,我确实发现我需要的 token 可以在上下文中找到(((context.Response.Context).Request).QueryString)
但解析这似乎是一个丑陋的解决方案。
var tw = new TwitterAuthenticationOptions {
ConsumerKey = "SecretKey",
ConsumerSecret = "SecretSecret",
SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie,
Provider = new TwitterAuthenticationProvider() {
OnAuthenticated = (context) => {
context.Identity.AddClaim(new System.Security.Claims.Claim("urn:twitter:access_token", context.AccessToken, XmlSchemaString, "Twitter"));
return Task.FromResult(0);
}
}
};
app.UseTwitterAuthentication(tw);
如何优雅地实现这一点?对于 Facebook,我找到了一个实际检索附加信息的解决方案,这感觉很相似......
get-more-information-from-social-providers-used-in-the-vs-2013-project-templates
最佳答案
Request对象中有一个很好的扩展方法。在需要的地方在 HomeController 或 Controller 中添加以下行。
Request.GetOwinContext().Authentication.User.Claims // Lists all claims
// Filters by type
Request.GetOwinContext().Authentication.User.FindAll("urn:twitter:access_token")
GetOwinContext 将为您提供身份验证对象,您可以在其中找到用户对象及其声明。
我在这里找到了一个有用的帖子 How do I access Microsoft.Owin.Security.xyz OnAuthenticated context AddClaims values?
我按照帖子中的步骤进行了修改。
账户 Controller .cs
private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
//New method call made here to persist the claims from external cookie
await SetExternalProperties(identity);
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}
//New method added to persist identity info
private async Task SetExternalProperties(ClaimsIdentity identity)
{
// get external claims captured in Startup.ConfigureAuth
ClaimsIdentity ext = await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);
if (ext != null)
{
var ignoreClaim = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims";
// add external claims to identity
foreach (var c in ext.Claims)
{
if (!c.Type.StartsWith(ignoreClaim))
if (!identity.HasClaim(c.Type, c.Value))
identity.AddClaim(c);
}
}
}
试试这个,让我知道。
关于c# - 在 asp.net mvc Twitter OAuth2 登录后获取 oauth 凭据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21335441/