首页 > 编程语言 >aspnetcore最最简单的接口权限认证

aspnetcore最最简单的接口权限认证

时间:2023-05-31 10:36:34浏览次数:52  
标签:builder 最最 aspnetcore 接口 options public Cookie new app

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

场景:

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

之前有写过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

标签:builder,最最,aspnetcore,接口,options,public,Cookie,new,app
From: https://www.cnblogs.com/morec/p/17445328.html

相关文章

  • net core-调用接口方式实现IHostedService的停止和启动
    usingMicrosoft.AspNetCore.Mvc;usingMicrosoft.AspNetCore.Authorization;[Route("home")][AllowAnonymous]publicclassHomeController:ControllerBase{ privatereadonlyIEnumerable<IHostedService>_hostedServices; privatereadonlyRec......
  • keycloak~自定义登出接口
    keycloak提供了登出的接口,不过它是一个post方法,需要你根据client_id,client_secret及refresh_token进行登出操作的,有时不太灵活,所以我又自己封装了一下,通过客户端浏览器上存储的session_id进行会话登出。kc提供的logoutapi:{{host}}/auth/realms/fabao/protocol/openid-connect......
  • Flowable基础表介绍-基础Service接口
    基础表结构Flowable的所有数据库表都以ACT_开头。第二部分是说明表用途的两字符标示符。ACT_RE_:'RE’代表repository。带有这个前缀的表包含“静态”信息,例如流程定义与流程资源(图片、规则等)。ACT_RU_:'RU’代表runtime。这些表存储运行时信息,例如流程实例(processinstance)、用......
  • Postman mock 接口集合
    官网介绍mocking-with-examplesmock-with-api由于postman的request都保存在collection中,所以mock的时候都需要选哪个collection去mock通过界面上example创建mockserver具体步骤在需要mock的collection里面先发送一些request并保存他们的response为examplecollection上.........
  • "以API接口快速获得aliexpress速卖通商品详情-返回值说明
     为了方便商家获取速卖通上的商品信息,速卖通提供了API接口来获取商品数据。本文将介绍如何通过API接口获取速卖通商品数据。一、申请API接口权限在使用API接口前,首先需要在速卖通官网注册账号并通过实名认证。然后,在个人资料页面找到开发者中心,申请API接口权限。在申请权限时,需要......
  • .net调用动态库NationECCode.dll使用电子凭证二维码解码接口
    .net调用动态库NationECCode.dll使用电子凭证二维码解码接口 C#.net调用示例代码:[DllImport("NationECCode.dll",CallingConvention=CallingConvention.StdCall)]publicstaticexternvoidNationEcTrans(stringurl,stringinput,IntPtroutput);......
  • laravel实现调用 webservice 接口
    1、打开php.ini  放开soap  2、代码实现 ......
  • 1688API商品详情页数据,接口封装
    首先,大家要到官方主页去申请一个 appkey,这个是做什么用的呢?AppKey是应用的唯一标识,TOP通过AppKey来鉴别应用的身份。AppSecret是TOP给应用分配的密钥,开发者需要妥善保存这个密钥,这个密钥用来保证应用来源的的可靠性,防止被伪造。就是说嘛,想要进门可要先有钥匙啊,所以,appke......
  • 拼多多商品详情接口(封装代码)
    一、使用拼多多商品接口可以获取拼多多商品详情。下面是获取商品详情的基本步骤和代码详解。1.注册账号并创建应用,获取API访问权限和密钥。2.根据API文档了解所需的参数和返回结果,构造请求参数和签名。其中,需要特别注意的是签名的生成方法,必须按照规定的方法进行,否则会导......
  • 利用akshare接口进行数据抓取
    akshare地址:https://www.akshare.xyz/data/index.html常用的包导入:importakshareasakimportnumpyasnpimportpandasaspdfromdatetimeimportdatetimeimportmatplotlib.pyplotaspltimportmplfinanceasmpffrompylabimportmplmpl.rcParams['font.san......