如何在ASP.NET Core中實現一個基礎的身份認證

來源:互聯網
上載者:User

標籤:lan   準備   async   完整   orm   gif   UI   instance   mat   

註:本文提到的程式碼範例> How to achieve a basic authorization in ASP.NET Core

如何在ASP.NET Core中實現一個基礎的身份認證

ASP.NET終於可以跨平台了,但是不是我們常用的ASP.NET, 而是叫一個ASP.NET Core的新平台,他可以跨Windows, Linux, OS X等平台來部署你的web應用程式,你可以理解為,這個架構就是ASP.NET的下一個版本,相對於傳統ASP.NET程式,它還是有一些不同的地方的,比如很多類庫在這兩個平台之間是不通用的。

 

今天首先我們在ASP.NET Core中來實現一個基礎的身份認證,既登陸功能。

 

前期準備:

1.推薦使用 VS 2015 Update3 作為你的IDE,:www.visualstudio.com

2.你需要安裝.NET Core的運行環境以及開發工具,這裡提供VS版:www.microsoft.com/net/core

 

建立項目:

在VS中建立項目,項目類型選擇ASP.NET Core Web Application (.NET Core), 輸入項目名稱為TestBasicAuthor。

接下來選擇 Web Application, 右側身份認證選擇:No Authentication

 

開啟Startup.cs

在ConfigureServices方法中加入如下代碼:

services.AddAuthorization(); 

在Configure方法中加入如下代碼:

app.UseCookieAuthentication(new CookieAuthenticationOptions {     AuthenticationScheme = "Cookie",     LoginPath = new PathString("/Account/Login"),     AccessDeniedPath = new PathString("/Account/Forbidden"),     AutomaticAuthenticate = true,     AutomaticChallenge = true }); 

完整的代碼應該是這樣:

public void ConfigureServices(IServiceCollection services) {     services.AddMvc();      services.AddAuthorization(); }  public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {     app.UseCookieAuthentication(new CookieAuthenticationOptions     {         AuthenticationScheme = "Cookie",         LoginPath = new PathString("/Account/Login"),         AccessDeniedPath = new PathString("/Account/Forbidden"),         AutomaticAuthenticate = true,         AutomaticChallenge = true     });      app.UseMvc(routes =>     {         routes.MapRoute(              name: "default",              template: "{controller=Home}/{action=Index}/{id?}");     }); }

你或許會發現貼進去的代碼是報錯的,這是因為還沒有引入對應的包,進入報錯的這一行,點擊燈泡,載入對應的包就可以了。

在項目下建立一個檔案夾命名為Model,並向裡面添加一個類User.cs

代碼應該是這樣

public class User{    public string UserName { get; set; }    public string Password { get; set; }}

 

建立一個控制器,取名為:AccountController.cs

在類中貼入如下代碼:

[HttpGet] public IActionResult Login() {     return View(); }  [HttpPost] public async Task<IActionResult> Login(User userFromFore) {     var userFromStorage = TestUserStorage.UserList         .FirstOrDefault(m => m.UserName == userFromFore.UserName && m.Password == userFromFore.Password);      if (userFromStorage != null)     {         //you can add all of ClaimTypes in this collection         var claims = new List<Claim>()         {             new Claim(ClaimTypes.Name,userFromStorage.UserName)             //,new Claim(ClaimTypes.Email,"[email protected]")          };          //init the identity instances         var userPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "SuperSecureLogin"));          //signin         await HttpContext.Authentication.SignInAsync("Cookie", userPrincipal, new AuthenticationProperties         {             ExpiresUtc = DateTime.UtcNow.AddMinutes(20),             IsPersistent = false,             AllowRefresh = false         });          return RedirectToAction("Index", "Home");     }     else     {         ViewBag.ErrMsg = "UserName or Password is invalid";          return View();     } }  public async Task<IActionResult> Logout() {     await HttpContext.Authentication.SignOutAsync("Cookie");      return RedirectToAction("Index", "Home"); } 

相同的檔案裡讓我們來添加一個類比使用者儲存的類

//for simple, I‘m not using the database to store the user data, just using a static class to replace it.public static class TestUserStorage{    public static List<User> UserList { get; set; } = new List<User>() {        new User { UserName = "User1",Password = "112233"}    };}

接下來修複好各種引用錯誤。

完整的代碼應該是這樣

using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.AspNetCore.Mvc;using TestBasicAuthor.Model;using System.Security.Claims;using Microsoft.AspNetCore.Http.Authentication;// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860namespace TestBasicAuthor.Controllers{    public class AccountController : Controller    {        [HttpGet]        public IActionResult Login()        {            return View();        }        [HttpPost]        public async Task<IActionResult> Login(User userFromFore)        {            var userFromStorage = TestUserStorage.UserList                .FirstOrDefault(m => m.UserName == userFromFore.UserName && m.Password == userFromFore.Password);            if (userFromStorage != null)            {                //you can add all of ClaimTypes in this collection                 var claims = new List<Claim>()                {                    new Claim(ClaimTypes.Name,userFromStorage.UserName)                     //,new Claim(ClaimTypes.Email,"[email protected]")                  };                //init the identity instances                 var userPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "SuperSecureLogin"));                //signin                 await HttpContext.Authentication.SignInAsync("Cookie", userPrincipal, new AuthenticationProperties                {                    ExpiresUtc = DateTime.UtcNow.AddMinutes(20),                    IsPersistent = false,                    AllowRefresh = false                });                return RedirectToAction("Index", "Home");            }            else            {                ViewBag.ErrMsg = "UserName or Password is invalid";                return View();            }        }        public async Task<IActionResult> Logout()        {            await HttpContext.Authentication.SignOutAsync("Cookie");            return RedirectToAction("Index", "Home");        }    }    //for simple, I‘m not using the database to store the user data, just using a static class to replace it.    public static class TestUserStorage    {        public static List<User> UserList { get; set; } = new List<User>() {        new User { UserName = "User1",Password = "112233"}    };    }}

在Views檔案夾中建立一個Account檔案夾,在Account檔案夾中建立一個名位index.cshtml的View檔案。

貼入如下代碼:

@model TestBasicAuthor.Model.User<html xmlns="http://www.w3.org/1999/xhtml"><head>    <title></title></head><body>    @using (Html.BeginForm())    {        <table>            <tr>                <td></td>                <td>@ViewBag.ErrMsg</td>            </tr>            <tr>                <td>UserName</td>                <td>@Html.TextBoxFor(m => m.UserName)</td>            </tr>            <tr>                <td>Password</td>                <td>@Html.PasswordFor(m => m.Password)</td>            </tr>            <tr>                <td></td>                <td><button>Login</button></td>            </tr>        </table>    }</body></html>

開啟HomeController.cs

添加一個Action, AuthPage.

[Authorize][HttpGet]public IActionResult AuthPage(){    return View();}

在Views/Home下添加一個視圖,名為AuthPage.cshtml

<html xmlns="http://www.w3.org/1999/xhtml"><head>    <title></title></head><body>    <h1>Auth page</h1>    <p>if you are not authorized, you can‘t visit this page.</p></body></html>

到此,一個基礎的身份認證就完成了,核心登陸方法如下:

await HttpContext.Authentication.SignInAsync("Cookie", userPrincipal, new AuthenticationProperties{    ExpiresUtc = DateTime.UtcNow.AddMinutes(20),    IsPersistent = false,    AllowRefresh = false});

啟用驗證如下:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory){    app.UseCookieAuthentication(new CookieAuthenticationOptions    {        AuthenticationScheme = "Cookie",        LoginPath = new PathString("/Account/Login"),        AccessDeniedPath = new PathString("/Account/Forbidden"),        AutomaticAuthenticate = true,        AutomaticChallenge = true    });}

在某個Controller或Action添加[Author],即可配置位需要登陸驗證的頁面。

 

最後:如何運行這個Sample以及下載完整的代碼請訪問:How to achieve a basic authorization in ASP.NET Core

如何在ASP.NET Core中實現一個基礎的身份認證

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.