来吧学学.Net Core之登录认证与跨域资源使用
序言
學(xué)習(xí)core登錄認(rèn)證與跨域資源共享是越不過的砍,所以我在學(xué)習(xí)中同樣也遇到啦這兩個問題,今天我們就用示例來演示下使用下這2個技術(shù)點吧.
本篇主要內(nèi)容如下:
1、展示一個登錄認(rèn)證的簡單示例
2、跨域資源訪問
3、跨域獲取登錄認(rèn)證的用戶信息
.Net Core使用身份認(rèn)證(Authentication,Identity)制作登錄認(rèn)證功能
首先我們實現(xiàn)登錄這個功能,代碼如下
? ?[Authorize] ? ?public class AccountController : Controller{[HttpGet][AllowAnonymous] ? ? ? ?public IActionResult Login(string returnUrl = null){ViewData["ReturnUrl"] = returnUrl; ? ? ? ? ? ?if (this.User.Identity.IsAuthenticated){ ? ? ? ? ? ? ? ?return RedirectPermanent(returnUrl);} ? ? ? ? ? ?return View();}[HttpPost][AllowAnonymous] ? ? ? ?public async Task<IActionResult> Login(string userName, string password,string returnUrl=null){ViewData["ReturnUrl"] = returnUrl; ? ? ? ? ?if (!string.IsNullOrEmpty(userName) && userName == password){ ? ? ? ? ? ? ? ?var claims = new List<Claim>(){ ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?new Claim(ClaimTypes.Name,userName),new Claim("password",password),new Claim("realname","張龍豪")}; ? ? ? ? ? ? ? ?//init the identity instances var userPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "Customer")); ? ? ? ? ? ? ? ?//signin await HttpContext.Authentication.SignInAsync("CookieAuth", userPrincipal, new AuthenticationProperties{ExpiresUtc = DateTime.UtcNow.AddMinutes(20),IsPersistent = false,AllowRefresh = false}); ? ? ? ? ? ? ? ?return RedirectPermanent(returnUrl);} ? ? ? ? ? ?else{ViewBag.ErrMsg = "UserName or Password is invalid"; ? ? ? ? ? ? ? ?return View();}}前臺代碼如下
<html> <head><meta name="viewport" content="width=device-width" /><title>Login</title> </head> <body><form asp-controller="Account" asp-action="Login" method="post" class="form-horizontal" asp-route-returnurl="@ViewData["ReturnUrl"]" role="form"><div class="form-group"><label class="col-md-2 control-label">UserName</label><div class="col-md-10"><input type="text" name="username" /></div></div><div class="form-group"><label class="col-md-2 control-label">Password</label><div class="col-md-10"><input type="password" name="password" /></div></div><div class="form-group"><div class="col-md-offset-2 col-md-10"><button type="submit" class="btn btn-default">Log in</button></div></div></form> </body> </html>在Startup文件的Configure方法中加入下面代碼
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory){ ? ? ? ? ?app.UseCookieAuthentication(new CookieAuthenticationOptions{AuthenticationScheme = "CookieAuth", //認(rèn)證方案:這是一個已知中間件的值,當(dāng)有多個實例的中間件如果你想限制授權(quán)到一個實例時這個選項將會起作用。LoginPath = new PathString("/Account/Login"), //登錄路徑:這是當(dāng)用戶試圖訪問資源但未經(jīng)過身份驗證時,程序?qū)⒄埱笾囟ㄏ虻竭@個相對路徑。AccessDeniedPath = new PathString("/Account/Forbidden"), //禁止訪問路徑:當(dāng)用戶試圖訪問資源時,但未通過該資源的任何授權(quán)策略,請求將被重定向到這個相對路徑。AutomaticAuthenticate = true, //自動認(rèn)證:這個標(biāo)志表明中間件應(yīng)該會在每個請求上進(jìn)行驗證和重建他創(chuàng)建的序列化主體。 ? ? ? ? ? ? ? ?AutomaticChallenge = true, //自動挑戰(zhàn):這個標(biāo)志標(biāo)明當(dāng)中間件認(rèn)證失敗時應(yīng)該重定向瀏覽器到登錄路徑或者禁止訪問路徑。SlidingExpiration = true, //Cookie可以分為永久性的和臨時性的。 臨時性的是指只在當(dāng)前瀏覽器進(jìn)程里有效,瀏覽器一旦關(guān)閉就失效(被瀏覽器刪除)。 永久性的是指Cookie指定了一個過期時間,在這個時間到達(dá)之前,此cookie一直有效(瀏覽器一直記錄著此cookie的存在)。 slidingExpriation的作用是,指示瀏覽器把cookie作為永久性cookie存儲,但是會自動更改過期時間,以使用戶不會在登錄后并一直活動,但是一段時間后卻自動注銷。也就是說,你10點登錄了,服務(wù)器端設(shè)置的TimeOut為30分鐘,如果slidingExpriation為false,那么10:30以后,你就必須重新登錄。如果為true的話,你10:16分時打開了一個新頁面,服務(wù)器就會通知瀏覽器,把過期時間修改為10:46。 更詳細(xì)的說明還是參考MSDN的文檔。CookieHttpOnly = false //默認(rèn)為true});好啦,你可以看到有[Authorize]屬性的方法或者控制器都需要登錄才能訪問,如果沒有登錄是不允許訪問的.
接下來你可能需要獲取當(dāng)前登錄用戶的用戶信息,代碼如下:
? ? ? ?[HttpPost] ? ? ?? ? ? ?public string GetCurrUserRealname(){ ? ? ?
? ? ? ? ?var s = this.User.Identities.First(u => u.IsAuthenticated).FindFirst("realname").Value; ? ? ? ? ? ?var ss = this.User.Identity.Name; ? ? ? ?
? ?return ss + ":" + s;}
ok,這樣就能獲取到當(dāng)前登錄的用戶信息
那如何退出呢?代碼如下:
? ? ? ?public async Task<JsonResult> Logout(){ ? ? ? ? ? ?await HttpContext.Authentication.SignOutAsync("CookieAuth"); ? ? ? ? ? ?return Json(new { data = "驗證方案:CookieAuth退出成功" });}這樣看來完整的登錄驗證就完成啦,但是目前位置,我的代碼都還簡單的要命,只能初學(xué)者拿來入手,具體還有很多東西可以擴(kuò)展.我們需要自己思考學(xué)習(xí).
.Net Core跨域資源訪問
那這個跨域的環(huán)境呢,需要我們自己搞一下.怎么搞,如下
本地測試前期準(zhǔn)備
1.首先我們搞兩個core的站點
?
2.本地host配置兩個域名,并在項目中做如下設(shè)置
hosts如下:
網(wǎng)站的launchSettings.json文件中配置項目CoreCorsATest為?"applicationUrl": "http://b.local.com:63455/",??項目AuthentiactionTest為 "applicationUrl": "http://a.local.com:50307/".
3. 實驗約定:
我們在項目AuthentiactionTest中寫接口,項目CoreCorsATest中調(diào)用AuthentiactionTest中的接口.
不做任何處理寫接口跨域調(diào)用
AuthentiactionTest中寫下如下接口
public class HomeController : Controller{ ?? ??public string GetName(){ ? ? ? ? ? ?return "張龍豪";}
CoreCorsATest中如下調(diào)用
$.post("http://a.local.com:50307/Home/GetName", null, function (data) { $("#content").html(data); });結(jié)果如下:接口調(diào)用成功,但是跨域資源不允許使用
解決問題
設(shè)置跨域的域名
public void ConfigureServices(IServiceCollection services){ ? ? ? ? ? ?//services.AddAuthorization(); ? ? ? ? ? ?// Add framework services. ? ? ? ? ? ?services.AddMvc();services.AddCors(options => options.AddPolicy("AllowSameDomain", builder => builder.WithOrigins("http://a.local.com:50307", "http://b.local.com:63455")));}下面的兩種調(diào)用方式
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory){app.UseCors("AllowSameDomain");? ? ?public string GetName(){ ? ? ? ? ? ?return "張龍豪";}
.Net Core跨域訪問需要登錄認(rèn)證的資源
這個問題就是上面跨域訪問的資源如果出現(xiàn)?[Authorize]特性,或者是訪問當(dāng)前用戶的登錄信息,用剛才的方法是不行的.
登錄使用,上述的登錄功能,接口如下
? ? ? ?[HttpPost] ? ? ? ?public string GetCurrUserRealname(){ ? ? ? ? ? ?var s = this.User.Identities.First(u => u.IsAuthenticated).FindFirst("realname").Value; ? ? ? ? ? ?var ss = this.User.Identity.Name; ? ? ? ? ? ?return ss + ":" + s;}那在b.local.com 這個域名下怎么訪問才是有效的呢?
需要下面兩部操作
1.設(shè)置接口服務(wù)項目配置,如下操作
services.AddCors(options => options.AddPolicy("AllowSameDomain", builder => builder.WithOrigins("http://a.local.com:50307", "http://b.local.com:63455").AllowCredentials()));2.ajax訪問接口時
$.ajax({type: 'POST',url: "http://a.local.com:50307/Account/GetCurrUserRealname",data: null,dataType: "json",xhrFields: {withCredentials: true},success: function (result) {$("#message").html(result);}});ok,這樣就可以訪問到當(dāng)前登錄用戶的信息啦
總結(jié)
本篇呢,寫的都是用例,理論原理,沒有涉及,也有一些其他常用額擴(kuò)展點,都沒有涉及到.
這里我只是把一些的點,貼出來,希望對想入手core的同學(xué)有所幫助.如有志同道合者,歡迎加左上方群,一起學(xué)習(xí)進(jìn)步.
原文地址:http://www.cnblogs.com/knowledgesea/p/7084419.html
.NET社區(qū)新聞,深度好文,微信中搜索dotNET跨平臺或掃描二維碼關(guān)注
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎總結(jié)
以上是生活随笔為你收集整理的来吧学学.Net Core之登录认证与跨域资源使用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 来吧学学.Net Core之项目文件简介
- 下一篇: 10分钟就能学会的.NET Core配置