欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

asp.net core2.2多用戶驗(yàn)證與授權(quán)示例詳解

 更新時(shí)間:2019年01月10日 11:06:54   作者:毛毛蟲  
這篇文章主要給大家介紹了關(guān)于asp.net core2.2多用戶驗(yàn)證與授權(quán)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧

前言

asp.net core2.2 用戶驗(yàn)證 和授權(quán)有很詳細(xì)和特貼心的介紹,我感興趣的主要是這兩篇:

我的項(xiàng)目有兩類用戶:

  • 微信公眾號用戶,用戶名為公眾號的openid
  • 企業(yè)微信的用戶,用戶名為企業(yè)微信的userid

每類用戶中部分人員具有“Admin”角色

因?yàn)槠髽I(yè)微信的用戶有可能同時(shí)是微信公眾號用戶,即一個(gè)人兩個(gè)名,所以需要多用戶驗(yàn)證和授權(quá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>
 /// 微信公眾號用戶使用的模塊
 /// </summary>
 /// <returns></returns>
 public IActionResult Mp()
 {
 return Content(User.Identity.Name + User.IsInRole("Admin"));
 }
 /// <summary>
 /// 微信公眾號管理員使用的模塊
 /// </summary>
 /// <returns></returns>
 public IActionResult MpAdmin()
 {
 return Content(User.Identity.Name + User.IsInRole("Admin"));
 }
}

下面咱一步一步實(shí)現(xiàn)。

第一步 改造類Startup

修改ConfigureServices方法,加入以下代碼

  services.AddAuthentication
   (
   "Work" //就是設(shè)置一個(gè)缺省的cookie驗(yàn)證的名字,缺省的意思就是需要寫的時(shí)候可以不寫。另外很多時(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è)置無授權(quá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)

就是在對應(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>
 /// 微信公眾號用戶使用的模塊
 /// </summary>
 /// <returns></returns>
 [Authorize(AuthenticationSchemes ="Mp")]
 public IActionResult Mp()
 {
  return Content(User.Identity.Name + User.IsInRole("Admin"));
 }
 /// <summary>
 /// 微信公眾號管理員使用的模塊
 /// </summary>
 /// <returns></returns>
 [Authorize(AuthenticationSchemes ="Mp",Roles ="Admin")]
 public IActionResult MpAdmin()
 {
  return Content(User.Identity.Name + User.IsInRole("Admin"));
 }

Ctrl+F5運(yùn)行,截屏如下:


最后,講講碰到的坑和求助


一開始的驗(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");
 }
  • 返回類型為Task<IActionResult> ,因?yàn)閼械脤慥iew,順手寫了句return Content("OK");
  • 從網(wǎng)站復(fù)制過來代碼,AuthenticationProperties沒有設(shè)置任何內(nèi)容

運(yùn)行起來以后不停的調(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)用自己。也不知道對不對。

這時(shí)候重視起RedirectUri,本來就要返回到returnUrl,是不是給RedirectUri賦值returnUrl就能自動(dòng)跳轉(zhuǎn)?

確實(shí),return Content("OK");時(shí)候自動(dòng)跳轉(zhuǎn)了,return RedirectToAction("Index");無效。

最后把Task<IActionResult> 改成Task ,把return ...刪除,一切完美?。ㄈ跞鯁栆痪洌遣皇窃瓉砭蛻?yīng)該這樣寫?我一直在走彎路?)

求助

User有屬性Identities,看起來可以有多個(gè)Identity,如何有?

總結(jié)

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。

相關(guān)文章

最新評論