.net core cookie 鑑權

毛毛球的书签發表於2024-08-20

思路:在startup中的configservice設定cookie鑑權,在config方法中use鑑權,然後新增兩個頁面,一個登入頁面,一個使用者資訊頁面(登陸後才能訪問,沒有登入則返回失敗或者需要登入)

1:新增一個cookie鑑權的方法

 1 public class CookieAuthConfig
 2 {
 3     public static void ConfigureServices(IServiceCollection services)
 4     {
 5         //使用cookie鑑權
 6         services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
 7             .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
 8             {
 9                 options.LoginPath = "/Auth/Login";
10                 options.AccessDeniedPath = "/Auth/Login";
11             });
12     }
13 
14     public static void Configure(IApplicationBuilder app, IWebHostEnvironment env)
15     {
16 
17         app.UseAuthentication();
18     }
19 }

2:在startup.cs中的配置和使用方法中引用cookie鑑權的方法

 1  public void ConfigureServices(IServiceCollection services)
 2  {
 3      CookieAuthConfig.ConfigureServices(services);
 4 
 5 }
 6 
 7   public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
 8   {
 9       CookieAuthConfig.ConfigureServices(app,env);
10   }

3:controll裡面的設定:

 1 public class AuthController : Controller
 2 {
 3 
 4 ///表示要授權才能訪問對於的info頁面
 5 
 6 [Authorize]
 7 public IActionResult Info()
 8 {
 9 
10     return View();
11 }
12 
13 
14  /// <summary>
15  /// 使用cookie方式儲存使用者資訊
16  /// </summary>
17  /// <param name="username"></param>
18  /// <param name="password"></param>
19  /// <returns></returns>
20  public async Task<IActionResult> Login(string username, string password)
21  {
22      if ("liping".Equals(username) && "123456".Equals(password))
23      {
24          ClaimsIdentity identity = new ClaimsIdentity("lipingtest");
25          identity.AddClaim(new Claim(ClaimTypes.Name, username));
26          identity.AddClaim(new Claim(ClaimTypes.Email, "111@qq.com"));
27          identity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));
28          identity.AddClaim(new Claim(ClaimTypes.Country, "China"));
29 
30          //寫入cookie
31          await base.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
32                 new ClaimsPrincipal(identity),
33                 new AuthenticationProperties
34                 {
35                     ExpiresUtc = System.DateTimeOffset.UtcNow.AddMinutes(30),
36                 });
37 
38 
39          return new JsonResult(new
40          {
41              Status = true,
42              MSg = "登入成功"
43          });
44      }
45      else
46      {
47          await System.Threading.Tasks.Task.CompletedTask;
48          return new JsonResult(new
49          {
50              Status = false,
51              MSg = "登入失敗"
52          });
53 
54      }
55 
56 
57  }
58 
59 
60 
61   public async Task<IActionResult> Logout()
62   {
63       //退出
64       await base.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
65 
66       return new JsonResult(new
67       {
68           Status = true,
69           MSg = "退出成功"
70       });
71   }
72 
73 
74 
75 }

相關文章