Asp .Net Core 2.0 登入授權以及多使用者登入

來源:互聯網
上載者:User

標籤:使用者登入   users   await   entity   跳轉頁面   pass   asp   def   control   

使用者登入是一個非常常見的應用情境 .net core 2.0 的登入方式發生了點變化,應該是屬於是良性的變化,變得更方便,更容易擴充。

配置

開啟項目中的Startup.cs檔案,找到ConfigureServices方法,我們通常在這個方法裡面做依賴注入的相關配置。添加如下代碼:

public void ConfigureServices(IServiceCollection services){    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)        .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o =>            {                o.LoginPath = new PathString("/Account/Login");                o.AccessDeniedPath = new PathString("/Error/Forbidden");            });}

這段代碼的大概意思就是,添加授權支援,並添加使用Cookie的方式,配置登入頁面和沒有許可權時的跳轉頁面。

再找到Configure方法,添加 app.UseAuthentication(),使用授權:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory){    app.UseAuthentication();}

這樣基本的配置就完成了。

登入

添加一個Controller,如AccountController,再添加一個Action,如 Login,所配置的路由,要與上面的配置對應,不然跳轉登入時會跳錯頁面。

使用者提交使用者名稱和密碼,登入代碼大致如下:

[HttpPost]public async Task <IActionResult> Login(string userName, string password, string ReturnUrl){    var user = _userService.Login(userName, password);    if (user != null)    {        user.AuthenticationType = CookieAuthenticationDefaults.AuthenticationScheme;        var identity = new ClaimsIdentity(user);        identity.AddClaim(new Claim(ClaimTypes.Name, user.UserID));        await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));        if (ReturnUrl.IsNullOrEmpty())        {            return RedirectToAction("Index", "Dashboard");        }        return Redirect(ReturnUrl);    }    ViewBag.Errormessage = "登入失敗,使用者名稱密碼不正確";    return View();}

這裡要注意的是 AuthenticationType 所設定的Scheme一定要與前面的配置一樣,這樣對應的登入授權才會生效。

使用登入身份

登入的目錄,就是希望有些頁面或者資源只有登入以後才可訪問。使用AuthorizeAttribute來做限制。在需要做限制的Controller上加上[Authorize]特性來做限制。

[Authorize]public class ThemeController{}

這樣這個Controller下的所有的Action都必需要登入後才可訪問。如果希望其中某些Action可以不用登入也可訪問,可以添加例外:

[AllowAnonymous]public ActionResult Index(){    return View();}

到這裡一個最基礎的登入就完成了。

在Web項目中,通常會遇到一個問題,後端管理員和前台使用者。這兩個使用者都是可登入的,在 .net core 2.0,這個將很容易實現。

多使用者登入添加一個登入方案(Scheme)

CookieAuthenticationDefaults.AuthenticationScheme,這是系統已經定義好的一個預設的登入方案,添加一個新的來實現一個不同的身份登入。代碼如下:

public class CustomerAuthorizeAttribute : AuthorizeAttribute{    public const string CustomerAuthenticationScheme = "CustomerAuthenticationScheme";    public CustomerAuthorizeAttribute()    {        this.AuthenticationSchemes = CustomerAuthenticationScheme;    }}

添加使用這個新的方案,在Startup.cs檔案下:

public void ConfigureServices(IServiceCollection services){    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)        .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o =>            {                o.LoginPath = new PathString("/Account/Login");                o.AccessDeniedPath = new PathString("/Error/Forbidden");            })            .AddCookie(CustomerAuthorizeAttribute.CustomerAuthenticationScheme, option =>            {                option.LoginPath = new PathString("/Account/Signin");                option.AccessDeniedPath = new PathString("/Error/Forbidden");            });}

添加新的登入方案,並配置一個新的登入頁面,登入的方法和剛才是一樣,只是AuthenticationType使用了新的方案。

[HttpPost]public async Task <IActionResult> Login(string userName, string password, string ReturnUrl){    var user = _userService.Login(userName, password);    if (user != null)    {        user.AuthenticationType = CustomerAuthorizeAttribute.CustomerAuthenticationScheme;        var identity = new ClaimsIdentity(user);        identity.AddClaim(new Claim(ClaimTypes.Name, user.UserID));        await HttpContext.SignInAsync(CustomerAuthorizeAttribute.CustomerAuthenticationScheme, new ClaimsPrincipal(identity));        if (ReturnUrl.IsNullOrEmpty())        {            return RedirectToAction("Index", "Dashboard");        }        return Redirect(ReturnUrl);    }    ViewBag.Errormessage = "登入失敗,使用者名稱密碼不正確";    return View();}
驗證登入狀態

使用方法和之前的差不多,換成新的CustomerAuthorizeAttribute就行了:

[CustomerAuthorize]public class CustomerController{}

CustomerAuthorizeAttribute這個類,不是必需的,只是為了方便使用而寫,其實完全可以只定義一個新的方案(Scheme)就行了。

誰才是HttpContext.User?

登入了多個使用者,那麼誰才是HttpContext.User呢?AddAuthentication()方法預設指它的方案(Scheme)所登入的使用者,就是這個HttpContext.User了。

如何擷取對應方案的登入使用者呢?使用HttpContext.AuthenticateAsync

var auth = await HttpContext.AuthenticateAsync(CustomerAuthorizeAttribute.CustomerAuthenticationScheme);if (auth.Succeeded){    auth.Principal.Identity...}
退出登入

這個就簡單了,指定方案退出就可以了。

public async Task Logout(string returnurl){    await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);    return Redirect(returnurl ?? "~/");}

原文地址:http://www.zkea.net/codesnippet/detail/post-60 

Asp .Net Core 2.0 登入授權以及多使用者登入

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.