五月一眨眼就过去,就当凑个数吧。

场景:

一个小小的项目,需要一个后台,就展示几个列表,连用户表、角色表等都不需要设计。

之前有写过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();
        }
    }
05-31 19:45