首页 > 技术文章 > 我怎么忽略了身份框架魔法,只是使用OWIN验证的中间件,以获得要求我寻求什么呢?

longyi 2016-02-24 10:53 原文

该OWIN中间件的东西第三方登录集成到您的ASP.NET应用程序是非常酷的,但我似乎无法弄清楚如何就剜出来的新的ID,它取代了蹩脚的成员身份 API。我没有兴趣在坚持所产生的债权,并在英法为基础的数据持久化,我只是想这样我就可以把它应用到我的现有项目账户。我不希望采用新的编号只是为了利 用这些东西的优势。 我一直在浏览CodePlex上的代码,但有一大堆的静态magic。你可以提供什么建议吗?
本文地址 :CodeGo.net/608804/

-------------------------------------------------------------------------------------------------------------------------
1. 使用下面的代码来设置OWIN安全中间件:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
 AuthenticationType = "Application",
 AuthenticationMode = AuthenticationMode.Passive,
 LoginPath = new PathString("/Login"),
 LogoutPath = new PathString("/Logout"),
});
app.SetDefaultSignInAsAuthenticationType("External");
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
 AuthenticationType = "External",
 AuthenticationMode = AuthenticationMode.Passive,
 CookieName = CookieAuthenticationDefaults.CookiePrefix + "External",
 ExpireTimeSpan = TimeSpan.FromMinutes(5),
});
app.UseGoogleAuthentication();

上面的代码设置了应用程序的cookie,外部cookie和谷歌外部登录中间件。外部登录中间件将登录数据转换身份,并将其设置为外部cookie的中间件。在你的应用程序,你需要得到外部的cookie身份并将其转换为外部登录数据,那么你可以用它检查您的 下面是示例代码。 请使用应用程序的cookie:

var authentication = System.Web.HttpContext.Current.GetOwinContext().Authentication;
var identity = new ClaimsIdentity("Application");
identity.AddClaim(new Claim(ClaimTypes.Name, "<user name>"));
authentication.AuthenticationResponseGrant = new AuthenticationResponseGrant(identity, new AuthenticationProperties() { 
 IsPersistent = false
});

获取应用程序的cookie身份:

var identity = System.Web.HttpContext.Current.User as ClaimsIdentity;

获取外部的cookie身份(谷歌):

var authentication = System.Web.HttpContext.Current.GetOwinContext().Authentication;
var result = await authentication.AuthenticateAsync("External");
var externalIdentity = result.Identity;

从身份提取外部登录数据:

public static ExternalLoginData FromIdentity(ClaimsIdentity identity)
{
 if (identity == null)
 {
  return null;
 }
 Claim providerKeyClaim = identity.FindFirst(ClaimTypes.NameIdentifier);
 if (providerKeyClaim == null || String.IsNullOrEmpty(providerKeyClaim.Issuer)
  || String.IsNullOrEmpty(providerKeyClaim.Value))
 {
  return null;
 }
 if (providerKeyClaim.Issuer == ClaimsIdentity.DefaultIssuer)
 {
  return null;
 }
 return new ExternalLoginData
 {
  LoginProvider = providerKeyClaim.Issuer,
  ProviderKey = providerKeyClaim.Value,
  UserName = identity.FindFirstValue(ClaimTypes.Name)
 };
}

 

推荐阅读