[英]Fetching oauth credentials after asp.net mvc Twitter OAuth2 login
在测试了内置的MVC 5 OAuth2 / OpenID提供程序后,我能够创建一个网站,允许我使用我的Twitter凭据进行身份验证。
我现在遇到的问题是,我还想在用户成功通过身份验证后,在网址中存储令牌( oauth_token和oauth_verifier )Twitter帖子。 我需要这些令牌,所以我可以允许用户直接从我的网站发布详细信息到他们的Twitter帐户。
在Startup.Auth.cs中设置了TwitterAuthenticationOptions (见下文)后,我确实发现我所关注的令牌可以在上下文中找到(((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我找到了一个实际检索其他信息的解决方案,这感觉类似......
您可以使用Query而不是QueryString,然后使用Get方法从查询字符串中检索值。
context.Response.Context.Request.Query.Get("oauth_verifier");
context.Response.Context.Request.Query.Get("oauth_token"); or context.AccessToken
需要注意的其他方法是你不需要oauth_verifer来发布数据。 在这里查看所需的标题。 我建议你使用这里的一个图书馆来与Twitter互动。
Request对象中有一个很好的扩展方法。 在HomeController或控制器中的任何需要的位置添加以下行。
Request.GetOwinContext().Authentication.User.Claims // Lists all claims
// Filters by type
Request.GetOwinContext().Authentication.User.FindAll("urn:twitter:access_token")
GetOwinContext将为您提供Authentication对象,您可以在其中找到用户对象及其声明。
我在这里找到了一个有用的帖子如何访问Microsoft.Owin.Security.xyz OnAuthenticated context AddClaims值?
我按照帖子中的步骤进行了修改。
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);
}
}
}
试试看,让我知道。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.