各位好 : )

最近筆者在嘗試改用ASP.NET Identity做為新系統的認證方式,發現到網路上給的資訊,不是很完整,所以做為一個工程屍,為了避免大家遇到一樣的問題。特地將一些有趣的地方記錄下來

首先如果你是舊的專案,想要用ASP.NET Identity ,你必需要利用NuGet安裝以下幾個套件

Microsoft.Owin.Host.SystemWeb

Microsoft.AspNet.Identity.Owin

接下來,我是在App_Start資料夾中加入Startup.cs檔,加入以下程式碼 (這裡是直接參考有用Identity的專案中的設定,但專案中是有將Startup.cs拆成兩個class ,這裡我僅用一個class檔)

public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
public void ConfigureAuth(IAppBuilder app)
{
// Cookie Auth
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Home/Index")
});
// Use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ApplicationCookie);
}

再來微調一下專案中的Web.config檔

<system.web>
<authentication mode="None" />
  ------------------------------------------------------
<system.webServer>
<modules>
<remove name="FormsAuthenticationModule" />
</modules>

在實際要進行登入時,有二種寫法。二種都是可以的,但接下來我會講到幾個點要注意

//AuthenticationManager的獲取方式

HttpContext.GetOwinContext().Authentication;

//清除先前的登錄資訊

AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);

//第一種

IList<Claim> claims = new List<Claim>();

claims.Add(new Claim(ClaimTypes.NameIdentifier, Request["userName"].ToString()));

claims.Add(new Claim(ClaimTypes.Name, Request["userName"].ToString()));

claims.Add(new Claim(ClaimTypes.Role, "Users"));

ClaimsIdentity identity = new ClaimsIdentity(claims,

DefaultAuthenticationTypes.ApplicationCookie);

//第二種

ClaimsIdentity claimsIdentity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie,ClaimTypes.NameIdentifier, ClaimTypes.Role);

claimsIdentity.AddClaim(new Claim( ClaimTypes.NameIdentifier, "MyCustomID"));

claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, "MyCustomUser"));

claimsIdentity.AddClaim(new Claim(
ClaimTypes.NameIdentifier, Request["userName"].ToString(),
"http://www.w3.org/2001/XMLSchema#string"));

claimsIdentity.AddClaim(
new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider",
"My Identity", "http://www.w3.org/2001/XMLSchema#string"));

//這裡強烈建議用第二種的寫法, 原因是如果你的頁面有利用antiforgerytoken 來防CSRF攻擊時,第一種寫法會產生錯誤

//但如果用第二種寫法,並加上identityprovider 這一個Claim 。就能正常使用了,不過在本篇最下方也有提到,可以透過Global.asax.cs加入參數設定,如果是透過Global.asax.cs的話,則以上兩種寫法都是沒有問題的 : )

//登錄

AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = true },identity);

-----------------------------重點來了-------------------------------

我在找資料時發現在StackOverFlow上有的回應居然是錯的…

比如說像以下這篇

http://stackoverflow.com/questions/18801120/where-is-microsoft-aspnet-identity-owin-authenticationmanager-in-asp-net-identit

private async Task SignInAsync(ApplicationUser user, bool isPersistent) {

AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);

var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);

}

其實他提到的並沒有很完整,問題在哪裡呢?問題在於我們的Startup.cs中

app.UseCookieAuthentication(new CookieAuthenticationOptions

{

AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,

LoginPath = new PathString("/Home/Index")

});

// Use a cookie to temporarily store information about a user logging in with a third party login provider

//其實這一段內部實作來說跟上面是一樣的

app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

其實ClaimsIdentity 最後是會用粗體的地方做為Cookie的名稱,而也是因為這樣,如果你在SignOut的方法裡指定的名稱跟Startup.cs中設定的不一樣。會導致你無法正常的登出先前使用者的資訊喔!(很重要)

有興趣可以參考這篇

CookieAuthenticationMiddelware 对cookie的加密方式

至於剛剛提到的Startup.cs ,嚴格來說其實app.UseExternalSignInCookie與app.UseCookieAuthentication只要選一種實作就可以了。參考一下UseExternalSignInCookie原始碼會發現其實他做的事情真的跟UseCookieAuthentication是差不多的

public static void UseExternalSignInCookie(this IAppBuilder app, string externalAuthenticationType) {

if (app == null) {

throw new ArgumentNullException("app");

}

app.SetDefaultSignInAsAuthenticationType(externalAuthenticationType);

app.UseCookieAuthentication(new CookieAuthenticationOptions {

AuthenticationType = externalAuthenticationType,

AuthenticationMode = AuthenticationMode.Passive,

CookieName = CookiePrefix + externalAuthenticationType,

ExpireTimeSpan = TimeSpan.FromMinutes(5),

});

}

出處

根據上面我們提到的CookieName設定,也可以知道我們如果是利用ClaimsIdentity要做登入時,CookieName也要跟Startup.cs設定的一樣,不然你會發現,明明程式碼都是對的,為什麼就是登入不了 (  ̄ c ̄)y▂ξ

ClaimsIdentity claimsIdentity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie,ClaimTypes.NameIdentifier, ClaimTypes.Role);

另外,如果又不小心遇到AntiForgery錯誤的話 (這是微軟提供一種防CSRF攻擊的方法)

可以在Global.asax.cs檔中在Appliccation_Start加入這段。ClaimTypes就端看你的ClaimsIdentity有什麼樣的Types能用

AntiForgeryConfig.UniqueClaimTypeIdentifier  = ClaimTypes.NameIdentifier;

以上是簡單的ClaimsIdentity心得,我們下回見 : )

參考 :

http://www.cnblogs.com/jesse2013/p/aspnet-identity-claims-based-authentication-and-owin.html#protectcookie

https://github.com/MohammadYounes/MVC5-MixedAuth/issues/20

http://dotnetcodr.com/2013/02/11/introduction-to-claims-based-security-in-net4-5-with-c-part-1/

http://stackoverflow.com/questions/19977833/anti-forgery-token-issue-mvc-5

[ASP.NET] ASP.NET Identity 中 ClaimsIdentity 解析的更多相关文章

  1. 在ASP.NET非MVC环境中(WebForm中)构造MVC的URL参数,以及如何根据URL解析出匹配到MVC路由的Controller和Action

    目前项目中有个需求,需要在WebForm中去构造MVC的URL信息,这里写了一个帮助类可以在ASP.NET非MVC环境中(WebForm中)构造MVC的URL信息,主要就是借助当前Http上下文去构造 ...

  2. asp.net core使用identity+jwt保护你的webapi(三)——refresh token

    前言 上一篇已经介绍了identity的注册,登录,获取jwt token,本篇来完成refresh token. 开始 开始之前先说明一下为什么需要refresh token. 虽然jwt toke ...

  3. ASP.NET Core 之 Identity 入门(一)

    前言 在 ASP.NET Core 中,仍然沿用了 ASP.NET里面的 Identity 组件库,负责对用户的身份进行认证,总体来说的话,没有MVC 5 里面那么复杂,因为在MVC 5里面引入了OW ...

  4. [转]ASP.NET Core 之 Identity 入门(一)

    本文转自:http://www.cnblogs.com/savorboard/p/aspnetcore-identity.html 前言 在 ASP.NET Core 中,仍然沿用了 ASP.NET里 ...

  5. ASP.NET Core和ASP.NET Framework共享Identity身份验证

    .NET Core 已经热了好一阵子,1.1版本发布后其可用性也越来越高,开源.组件化.跨平台.性能优秀.社区活跃等等标签再加上"微软爸爸"主推和大力支持,尽管现阶段对比.net ...

  6. 理解ASP.NET Core验证模型(Claim, ClaimsIdentity, ClaimsPrincipal)不得不读的英文博文

    这篇英文博文是 Andrew Lock 写的 Introduction to Authentication with ASP.NET Core . 以下是简单的阅读笔记: -------------- ...

  7. ASP.NET Core 和 ASP.NET Framework 共享 Identity 身份验证

    .NET Core 已经热了好一阵子,1.1版本发布后其可用性也越来越高,开源.组件化.跨平台.性能优秀.社区活跃等等标签再加上"微软爸爸"主推和大力支持,尽管现阶段对比.net ...

  8. 【转】理解ASP.NET Core验证模型(Claim, ClaimsIdentity, ClaimsPrincipal)不得不读的英文博文

    这篇英文博文是 Andrew Lock 写的 Introduction to Authentication with ASP.NET Core . 以下是简单的阅读笔记: -------------- ...

  9. ASP.NET Core 之 Identity 入门(转载)

    原文地址:https://www.cnblogs.com/gongap/p/9504562.html 前言 在 ASP.NET Core 中,仍然沿用了 ASP.NET里面的 Identity 组件库 ...

随机推荐

  1. spring-cloud-Zuul学习(四)【中级】--自定义zuul Filter详解【重新定义spring cloud实践】

      实现自定义zuul Filter 方法很简单,只要继承ZuulFilter跟加入到spring IOC容器即可,zuulFilter是一个抽象类,里面包含以下方法需要我们实现: String fi ...

  2. java课程之团队开发冲刺阶段1.3

    一.总结昨天进度 1.完成任务指标,但是有些问题没有得到根本上解决,只是换方式解决了 2.使用时间:6小时 二.遇到的困难 1.在设置AlertDialog弹窗组件的时候,没有办法获取选中值,再实验多 ...

  3. 微信测试号开发入门配置问题java

    这个测试号配置弄了好几天了,入了无数坑,终于解决了...辛苦我了,手动安慰一下自己.. 为了萌新们以后不要再浪费时间绕半天做无用功.看看楼楼的艰苦历程吧. 此教程针对没有云服务器,没有自己的域名的.没 ...

  4. swust oj 987

    输出用先序遍历创建的二叉树是否为完全二叉树的判定结果 1000(ms) 10000(kb) 2553 / 5268 利用先序递归遍历算法创建二叉树并判断该二叉树是否为完全二叉树.完全二叉树只能是同深度 ...

  5. 最新鲜最详细的Android SDK下载安装及配置教程

    //来源: http://www.cnblogs.com/summary-2017/p/8073225.html 最近Neo突发神经,想要将学过的一些计算机视觉.机器学习中的算法都放到移动设备上去跑跑 ...

  6. java实现多线程使用多个代理ip的方式爬取网页页面内容

    项目的目录结构 核心源码: package cn.edu.zyt.spider; import java.io.BufferedInputStream; import java.io.FileInpu ...

  7. python从入门到实践-9章类

    #!/user/bin/env python# -*- coding:utf-8 -*- # 类名采用的是驼峰命名法,即将类名中每个单词的首字母大写,而不使用下划线.# 对于每个类,都应紧跟在类定义后 ...

  8. 长沙学院APP之校园模块设计

    一.简单回顾 在上次的scrum冲刺中,我将整个长沙学院的APP做了一个基本的架构设计以及框架设计,确定好了APP的功能结构以及实现时所要达到的效果,并且做了一个简单的用户登录界面,由于所学知识有限, ...

  9. libguestfs手册(2):guestfish command

    添加一个drive:guestfs_add_drive_opts add-drive filename [readonly:true|false] [format:..] [iface:..] [na ...

  10. 2018 大湾区(深圳) .NET技术分享交流会 第一期

    .NET Core 2.1 已于2018年5月30日正式发布,邀请粤港澳大湾区.NET技术专家和从业人员,一起分享与交流.NET技术的发展方向,提高粤港澳大湾区.NET技术交流氛围,挖掘.NET高级人 ...