asp.net core2.2多用戶驗(yàn)證與授權(quán)示例詳解
前言
asp.net core2.2 用戶驗(yàn)證 和授權(quán)有很詳細(xì)和特貼心的介紹,我感興趣的主要是這兩篇:
我的項(xiàng)目有兩類(lèi)用戶:
- 微信公眾號(hào)用戶,用戶名為公眾號(hào)的openid
- 企業(yè)微信的用戶,用戶名為企業(yè)微信的userid
每類(lèi)用戶中部分人員具有“Admin”角色
因?yàn)槠髽I(yè)微信的用戶有可能同時(shí)是微信公眾號(hào)用戶,即一個(gè)人兩個(gè)名,所以需要多用戶驗(yàn)證和授權(quán)。咱用代碼說(shuō)話最簡(jiǎn)潔,如下所示:
public class DemoController : Controller
{
/// <summary>
/// 企業(yè)微信用戶使用的模塊
/// </summary>
/// <returns></returns>
public IActionResult Work()
{
return Content(User.Identity.Name +User.IsInRole("Admin"));
}
/// <summary>
/// 企業(yè)微信管理員使用的模塊
/// </summary>
/// <returns></returns>
public IActionResult WorkAdmin()
{
return Content(User.Identity.Name + User.IsInRole("Admin"));
}
/// <summary>
/// 微信公眾號(hào)用戶使用的模塊
/// </summary>
/// <returns></returns>
public IActionResult Mp()
{
return Content(User.Identity.Name + User.IsInRole("Admin"));
}
/// <summary>
/// 微信公眾號(hào)管理員使用的模塊
/// </summary>
/// <returns></returns>
public IActionResult MpAdmin()
{
return Content(User.Identity.Name + User.IsInRole("Admin"));
}
}
下面咱一步一步實(shí)現(xiàn)。
第一步 改造類(lèi)Startup
修改ConfigureServices方法,加入以下代碼
services.AddAuthentication
(
"Work" //就是設(shè)置一個(gè)缺省的cookie驗(yàn)證的名字,缺省的意思就是需要寫(xiě)的時(shí)候可以不寫(xiě)。另外很多時(shí)候用CookieAuthenticationDefaults.AuthenticationScheme,這玩意就是字符串常量“Cookies”,
)
.AddCookie
(
"Work", //cookie驗(yàn)證的名字,“Work”可以省略,因?yàn)槭侨笔∶?
option =>
{
option.LoginPath = new PathString("/Demo/WorkLogin"); //設(shè)置驗(yàn)證的路徑
option.AccessDeniedPath= new PathString("/Demo/WorkDenied");//設(shè)置無(wú)授權(quán)訪問(wèn)跳轉(zhuǎn)的路徑
}).AddCookie("Mp", option =>
{
option.LoginPath = new PathString("/Demo/MpLogin");
option.AccessDeniedPath = new PathString("/Demo/MpDenied");
});
修改Configure方法,加入以下代碼
app.UseAuthentication();
第二步 添加驗(yàn)證
public async Task WorkLogin(string returnUrl)
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, "UserId"),
new Claim(ClaimTypes.Role, "Admin") //如果是管理員
};
var claimsIdentity = new ClaimsIdentity(claims, "Work");//“,"Work"”可以省略,因?yàn)槭侨笔∶?
var authProperties = new AuthenticationProperties
{
AllowRefresh = true,
//ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(10),
// The time at which the authentication ticket expires. A
// value set here overrides the ExpireTimeSpan option of
// CookieAuthenticationOptions set with AddCookie.
IsPersistent = false, //持久化保存,到底什么意思我也不太清楚,哪位兄弟清楚的話,盼解釋
//IssuedUtc = <DateTimeOffset>,
// The time at which the authentication ticket was issued.
RedirectUri = returnUrl ?? "/Demo/Work"
};
await HttpContext.SignInAsync("Work", new ClaimsPrincipal(claimsIdentity), authProperties);
}
public IActionResult WorkDenied()
{
return Forbid();
}
public async Task MpLogin(string returnUrl)
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, "OpenId"),
new Claim(ClaimTypes.Role, "Admin") //如果是管理員
};
var claimsIdentity = new ClaimsIdentity(claims, "Mp");//“,"Mp"”不能省略,因?yàn)椴皇侨笔∶?
var authProperties = new AuthenticationProperties
{
AllowRefresh = true,
IsPersistent = false,
RedirectUri = returnUrl ?? "/Demo/Mp"
};
await HttpContext.SignInAsync("Mp", new ClaimsPrincipal(claimsIdentity), authProperties);
}
public IActionResult MpDenied()
{
return Forbid();
}
第三步 添加授權(quán)
就是在對(duì)應(yīng)的Action前面加[Authorize]
/// <summary>
/// 企業(yè)微信用戶使用的模塊
/// </summary>
/// <returns></returns>
[Authorize(
AuthenticationSchemes ="Work" //缺省名可以省略
)]
public IActionResult Work()
{
return Content(User.Identity.Name + User.IsInRole("Admin"));
}
/// <summary>
/// 企業(yè)微信管理員使用的模塊
/// </summary>
/// <returns></returns>
[Authorize(AuthenticationSchemes ="Work",Roles ="Admin")]
public IActionResult WorkAdmin()
{
return Content(User.Identity.Name + User.IsInRole("Admin"));
}
/// <summary>
/// 微信公眾號(hào)用戶使用的模塊
/// </summary>
/// <returns></returns>
[Authorize(AuthenticationSchemes ="Mp")]
public IActionResult Mp()
{
return Content(User.Identity.Name + User.IsInRole("Admin"));
}
/// <summary>
/// 微信公眾號(hào)管理員使用的模塊
/// </summary>
/// <returns></returns>
[Authorize(AuthenticationSchemes ="Mp",Roles ="Admin")]
public IActionResult MpAdmin()
{
return Content(User.Identity.Name + User.IsInRole("Admin"));
}
Ctrl+F5運(yùn)行,截屏如下:



![]() |
最后,講講碰到的坑和求助
坑
一開(kāi)始的驗(yàn)證的代碼如下:
public async Task<IActionResult> Login(string returnUrl)
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, "UserId"),
new Claim(ClaimTypes.Role, "Admin") //如果是管理員
};
var claimsIdentity = new ClaimsIdentity(claims, "Work");//“,"Work"”可以省略,因?yàn)槭侨笔∶?
var authProperties = new AuthenticationProperties
{
//AllowRefresh = true,
//IsPersistent = false,
//RedirectUri
};
await HttpContext.SignInAsync("Work", new ClaimsPrincipal(claimsIdentity), authProperties);
return Content("OK");
}
- 返回類(lèi)型為T(mén)ask<IActionResult> ,因?yàn)閼械脤?xiě)View,順手寫(xiě)了句return Content("OK");
- 從網(wǎng)站復(fù)制過(guò)來(lái)代碼,AuthenticationProperties沒(méi)有設(shè)置任何內(nèi)容
運(yùn)行起來(lái)以后不停的調(diào)用login,百度了半天,改了各種代碼,最后把return Content("OK");改成return RedirectToAction("Index");一切OK!
揣摩原因可能是當(dāng) return Content("OK");時(shí),自動(dòng)調(diào)用AuthenticationProperties的RedirectUri,而RedirectUri為空時(shí),自動(dòng)調(diào)用自己。也不知道對(duì)不對(duì)。
這時(shí)候重視起RedirectUri,本來(lái)就要返回到returnUrl,是不是給RedirectUri賦值returnUrl就能自動(dòng)跳轉(zhuǎn)?
確實(shí),return Content("OK");時(shí)候自動(dòng)跳轉(zhuǎn)了,return RedirectToAction("Index");無(wú)效。
最后把Task<IActionResult> 改成Task ,把return ...刪除,一切完美?。ㄈ跞鯁?wèn)一句,是不是原來(lái)就應(yīng)該這樣寫(xiě)?我一直在走彎路?)
求助
User有屬性Identities,看起來(lái)可以有多個(gè)Identity,如何有?
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)腳本之家的支持。
- asp.net core 認(rèn)證和授權(quán)實(shí)例詳解
- ASP.NET?Core?6.0?添加?JWT?認(rèn)證和授權(quán)功能
- ASP.NET?Core中的策略授權(quán)和ABP授權(quán)
- ASP.NET Core 3.0輕量級(jí)角色API控制授權(quán)庫(kù)
- ASP.NET Core使用JWT自定義角色并實(shí)現(xiàn)策略授權(quán)需要的接口
- asp.net core3.1cookie和jwt混合認(rèn)證授權(quán)實(shí)現(xiàn)多種身份驗(yàn)證方案
- ASP.NET Core使用JWT認(rèn)證授權(quán)的方法
- ASP.NET Core學(xué)習(xí)之使用JWT認(rèn)證授權(quán)詳解
- 淺談ASP.NET Core 中jwt授權(quán)認(rèn)證的流程原理
- asp.net core 授權(quán)詳解
- asp.net core項(xiàng)目授權(quán)流程詳解
相關(guān)文章
asp.net 仿騰訊微薄提示 還能輸入*個(gè)字符 的實(shí)現(xiàn)代碼
asp.net 仿騰訊微薄提示 還能輸入*個(gè)字符 的實(shí)現(xiàn)代碼,需要的朋友可以參考下。2011-10-10
微信公眾平臺(tái)開(kāi)發(fā)之發(fā)送文本消息.Net代碼解析
這篇文章主要為大家詳細(xì)解析了微信公眾平臺(tái)開(kāi)發(fā)之發(fā)送文本消息.Net代碼,感興趣的小伙伴們可以參考一下2016-06-06
ASP.NET 動(dòng)態(tài)寫(xiě)入服務(wù)器端控件
使用Asp.net進(jìn)行開(kāi)發(fā)時(shí),因?yàn)槟承┬枨笤颍枰陧?yè)面中動(dòng)態(tài)添加控件。當(dāng)然,這些控件可以是普通的html標(biāo)簽,也可以是Asp.net獨(dú)有的服務(wù)器端控件。2009-04-04
asp.net頁(yè)面master頁(yè)面與ascx用戶控件傳值的問(wèn)題
aspx 頁(yè)面,master頁(yè)面與ascx用戶控件傳值的問(wèn)題2010-03-03
解決VS2012 Express的There was a problem sending the command to
安裝Visual Studio 2012 Express之后,雙擊打開(kāi)web.config文件時(shí)經(jīng)常出現(xiàn)“There was a problem sending the command to the program”的錯(cuò)誤,然后VS2012 Express打開(kāi)了,但web.config文件沒(méi)打開(kāi),需要再次雙擊web.config文件才能打開(kāi)。很是煩人2013-02-02
asp.net分頁(yè)控件AspNetPager的樣式美化
自從吳旗娃推出了AspNetPager分頁(yè)控件之后,受到了廣大程序員朋友的喜愛(ài),無(wú)數(shù)個(gè)網(wǎng)站都出現(xiàn)這個(gè)控件的身影??墒谴蟛糠志W(wǎng)站程序員的朋友都是直接套用,導(dǎo)致滿世界的分頁(yè)控件樣式都是一樣的簡(jiǎn)潔,傷不起啊2011-12-12
CheckBox控件默認(rèn)選中,提交時(shí)永遠(yuǎn)獲得選中狀態(tài)的實(shí)現(xiàn)代碼
下面小編就為大家?guī)?lái)一篇CheckBox控件默認(rèn)選中,提交時(shí)永遠(yuǎn)獲得選中狀態(tài)的實(shí)現(xiàn)代碼。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-05-05


