<output id="qn6qe"></output>

    1. <output id="qn6qe"><tt id="qn6qe"></tt></output>
    2. <strike id="qn6qe"></strike>

      亚洲 日本 欧洲 欧美 视频,日韩中文字幕有码av,一本一道av中文字幕无码,国产线播放免费人成视频播放,人妻少妇偷人无码视频,日夜啪啪一区二区三区,国产尤物精品自在拍视频首页,久热这里只有精品12

      aspnetcore最最簡單的接口權限認證

      五月一眨眼就過去,就當湊個數吧。

      場景:

      一個小小的項目,需要一個后臺,就展示幾個列表,連用戶表、角色表等都不需要設計。

      之前有寫過identityserver4和jwt4的demo

      (exercisebook/IdentityServer4&Serilog at main · liuzhixin405/exercisebook · GitHub

      exercisebook/授權/授權一/JwtToken at main · liuzhixin405/exercisebook · GitHub),

      但是這樣一個項目中上這些肯定是大材小用。

      微軟提供的還有一個就是cookie,既然夠簡單,那么什么也不用設計,盡量做到最簡單,而且后期還可以通過表設計來完善這個的后臺登錄模塊。

      首先我們要實現的就是接口代碼的授權:

        [Authorize]
          [ApiController]
          [Route("[controller]")]
          public class WeatherForecastController : ControllerBase
          {
              private static readonly string[] Summaries = new[]
              {
              "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
          };
      
              private readonly ILogger<WeatherForecastController> _logger;
      
              public WeatherForecastController(ILogger<WeatherForecastController> logger)
              {
                  _logger = logger;
              }
      
              [Authorize(Roles = "Admin")] // 要求"Admin"角色的授權
              [HttpGet(Name = "GetWeatherForecast")]
              public IEnumerable<WeatherForecast> Get()
              {
                  return Enumerable.Range(1, 5).Select(index => new WeatherForecast
                  {
                      Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
                      TemperatureC = Random.Shared.Next(-20, 55),
                      Summary = Summaries[Random.Shared.Next(Summaries.Length)]
                  })
                  .ToArray();
              }
          }

      上面的特性使得WeatherForecastController接口需要權限才能訪問,而GetWeatherForecast接口需要Admin角色就可以訪問。

      下面就通過program來配置及安全中心和授權策略:

      using Microsoft.AspNetCore.Authentication.Cookies;
      
      namespace auth_cookie
      {
          /// <summary>
          /// 一個簡單的Cookie身份驗證和授權示例
          /// </summary>
          public class Program
          {
              public static void Main(string[] args)
              {
                  var builder = WebApplication.CreateBuilder(args);
      
                  // Add services to the container.
      
                  builder.Services.AddControllers();
                  // 配置Cookie身份驗證
                  builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                      .AddCookie(options =>
                      {
                          options.Cookie.Name = "YourAuthCookie"; // 設置Cookie的名稱
                          options.LoginPath = "/api/Auth/Login"; // 設置登錄路徑
                      });
      
                  // 配置授權服務
                  builder.Services.AddAuthorization(options =>
                  {
                      options.AddPolicy("RequireAdminRole", policy => policy.RequireRole("Admin"));
                  });
                  // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
                  builder.Services.AddEndpointsApiExplorer();
                  builder.Services.AddSwaggerGen();
      
                  var app = builder.Build();
      
                  // Configure the HTTP request pipeline.
                  if (app.Environment.IsDevelopment())
                  {
                      app.UseSwagger();
                      app.UseSwaggerUI();
                  }
      
                  app.UseHttpsRedirection();
                  app.UseAuthentication(); // 啟用身份驗證
                  app.UseAuthorization(); // 啟用授權
      
      
                  app.MapControllers();
      
                  app.Run();
              }
          }
      }

      上面的代碼夠簡單的吧,核心代碼也就這幾行。指定默認的scheme為cookie,寫好注釋。指定策略RequireAdminRole,要求角色Admin,都可以很靈活的多配置,通過數據庫,配置文件等。

       // 配置Cookie身份驗證
                  builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                      .AddCookie(options =>
                      {
                          options.Cookie.Name = "YourAuthCookie"; // 設置Cookie的名稱
                          options.LoginPath = "/api/Auth/Login"; // 設置登錄路徑
                      });
      
                  // 配置授權服務
                  builder.Services.AddAuthorization(options =>
                  {
                      options.AddPolicy("RequireAdminRole", policy => policy.RequireRole("Admin"));
                  });

      這樣不算晚,還需要一個登錄和登出的授權的接口,而且接口路徑寫好了,/api/Auth/Login

      using Microsoft.AspNetCore.Authentication.Cookies;
      using Microsoft.AspNetCore.Authentication;
      using Microsoft.AspNetCore.Http;
      using Microsoft.AspNetCore.Mvc;
      using System.Security.Claims;
      
      namespace auth_cookie.Controllers
      {
          [Route("api/[controller]")]
          [ApiController]
          public class AuthController : ControllerBase
          {
              //[HttpPost("login")]
              [HttpGet("login")] //方便測試
              public async Task<IActionResult> Login(string username, string password)
              {
                  // 執行驗證用戶名和密碼的邏輯
                  //這里可以和存到數據庫的用戶和密碼進行比對
                  if(username != "admin" && password != "123456")
                  {
                      return BadRequest("Invalid username or password");
                  }
                  // 如果驗證成功,創建身份驗證Cookie
                  var claims = new List<Claim>
                  {
                      new Claim(ClaimTypes.Name, username),
                      new Claim(ClaimTypes.Role, "Admin") // 添加用戶角色
                  };
      
                  var claimsIdentity = new ClaimsIdentity(
                      claims, CookieAuthenticationDefaults.AuthenticationScheme);
      
                  await HttpContext.SignInAsync(
                      CookieAuthenticationDefaults.AuthenticationScheme,
                      new ClaimsPrincipal(claimsIdentity),
                      new AuthenticationProperties());
      
                  return Ok("Login successful");
              }
      
              //[HttpPost("logout")]
              [HttpGet("logout")]
              public async Task<IActionResult> Logout()
              {
                  await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
                  return Ok("Logout successful");
              }
          }
      }

      上面的核心代碼根據我們配置的做的設置,一一對應,要不然就無權訪問WeatherForecastController了:

       var claims = new List<Claim>
                  {
                      new Claim(ClaimTypes.Name, username),
                      new Claim(ClaimTypes.Role, "Admin") // 添加用戶角色
                  };
      
                  var claimsIdentity = new ClaimsIdentity(
                      claims, CookieAuthenticationDefaults.AuthenticationScheme);

      下面看看效果,訪問 :https://localhost:7066/WeatherForecast,會自動跳轉到https://localhost:7066/api/Auth/Login?ReturnUrl=%2FWeatherForecast

      我們指定一下用戶名和密碼 https://localhost:7066/api/Auth/Login?username=admin&password=123456ReturnUrl=%2FWeatherForecast

      再來訪問 https://localhost:7066/WeatherForecast

      退出登錄,https://localhost:7066/api/auth/logout

      再來訪問 

      https://localhost:7066/WeatherForecast

      配合前端的后臺管理,一個很簡單的后臺登陸就這樣ok了。

      源代碼:

      exercisebook/授權/授權三/auth_cookie at main · liuzhixin405/exercisebook · GitHub

      posted @ 2023-05-31 10:21  星仔007  閱讀(849)  評論(2)    收藏  舉報
      主站蜘蛛池模板: 国产精品成人一区二区三区| 国产愉拍精品手机| 久久99热只有频精品8| 成人精品一区日本无码网| 国内精品久久久久影院日本| 亚洲精品美女一区二区| 国产一区二区三区在线看| 丰满的熟妇岳中文字幕| 正安县| 亚洲丰满老熟女激情av| 激情亚洲专区一区二区三区| 天天做天天爱夜夜爽女人爽| 91中文字幕在线一区| jizz国产免费观看| 熟女性饥渴一区二区三区| 沾益县| 亚洲av色夜色精品一区| 中文字幕在线精品国产| av色综合久久天堂av色综合在| 亚洲顶级裸体av片| 91精品国产一二三产区| 日韩av裸体在线播放| 亚洲欧洲日产国产 最新| 精品国产午夜福利伦理片| 亚洲а∨天堂久久精品2021| 国产亚洲另类无码专区| 九九热在线免费精品视频| 日韩少妇内射免费播放| 夜夜爽77777妓女免费看| 美乳丰满人妻无码视频| 一本一本久久a久久综合精品| 欧美黑人巨大xxxxx| 国产精品无码av不卡| 久久久无码一区二区三区| 长腿校花无力呻吟娇喘| 色欲国产精品一区成人精品| 亚洲综合精品一区二区三区| 国产一区二区在线观看粉嫩| 久久99国产精品尤物| 屁屁影院ccyy备用地址| av亚洲在线一区二区|