[英]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.