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

场景:

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

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

aspnetcore最最简单的接口权限认证的更多相关文章

  1. SpringBoot系列 - 集成JWT实现接口权限认证

    会飞的污熊 2018-01-22 16173 阅读 spring jwt springboot RESTful API认证方式 一般来讲,对于RESTful API都会有认证(Authenticati ...

  2. SpringBoot集成JWT 实现接口权限认证

    JWT介绍 Json web token (JWT), 是为了在网络应用环境间传递声明而执行的一种基于JSON的开放标准((RFC 7519).该token被设计为紧凑且安全的, 特别适用于分布式站点 ...

  3. IdentityServer4实现.Net Core API接口权限认证(快速入门)

    什么是IdentityServer4 官方解释:IdentityServer4是基于ASP.NET Core实现的认证和授权框架,是对OpenID Connect和OAuth 2.0协议的实现. 通俗 ...

  4. Ocelot网关+IdentityServer4实现API权限认证

    Ocelot是一个用.NET Core实现并且开源的API网关,它功能强大,包括了:路由.请求聚合.服务发现.认证.鉴权.限流熔断.并内置了负载均衡器与Service Fabric.Butterfly ...

  5. 【JEECG技术文档】JEECG 接口权限开发及配置使用说明

    1.功能介绍   通过接口配置实现,对接口的访问权限控制和数据权限控制,接口时REST接口,接口权限认证机制使用Json web token (JWT) 接口权限调用流程: (1)通过接口用户的用户名 ...

  6. Asp-Net-Core权限认证

    title: Asp.Net Core权限认证 date: 2022-10-27 16:17:52 tags: - .NET 翻了很多的博客,文档,发现asp.net core自带的权限认证还是比较复 ...

  7. 10分钟简单学习net core集成jwt权限认证,快速接入项目落地使用

    什么是JWT JSON Web Token(JWT)是目前最流行的跨域身份验证.分布式登录.单点登录等解决方案. JWT的官网地址:https://jwt.io/ 通俗地来讲,JWT是能代表用户身份的 ...

  8. 用c#开发微信 (19) 公众平台接口权限列表说明 - 订阅号、服务号认证后的区别

    最新发现有些原来认证服务号的权限对认证的订阅号开放了,这里是官方的文档说明<公众平台接口权限列表说明>,明显比这里说得详细.准确多了<微信公众平台服务号.订阅号的相关说明>.另 ...

  9. 跟我一起学.NetCore之熟悉的接口权限验证不能少(Jwt)

    前言 权限管控对于一个系统来说是非常重要的,最熟悉不过的是菜单权限和数据权限,上一节通过Jwt实现了认证,接下来用它实现接口权限的验证,为什么不是菜单权限呢?对于前后端分离而言,称其为接口权限感觉比较 ...

  10. Spring Boot 2.0 利用 Spring Security 实现简单的OAuth2.0认证方式2

    0.前言 经过前面一小节已经基本配置好了基于SpringBoot+SpringSecurity+OAuth2.0的环境.这一小节主要对一些写固定InMemory的User和Client进行扩展.实现动 ...

随机推荐

  1. 基于深度学习的农作物叶片病害检测系统(UI界面+YOLOv5+训练数据集)

    摘要:农作物叶片病害检测系统用于智能检测常见农作物叶片病害情况,自动化标注.记录和保存病害位置和类型,辅助作物病害防治以增加产值.本文详细介绍基于YOLOv5深度学习模型的农作物叶片病害检测系统,在介 ...

  2. 从源码彻底理解 Prometheus/VictoriaMetrics 中的 relabel_configs/metric_relabel_configs 配置

    背景 最近接手维护了公司的指标监控系统,之后踩到坑就没站起来过.. 本次问题的起因是我们配置了一些指标的删除策略没有生效: - action: drop_metrics regex: "^e ...

  3. Redis 性能优化

    一.Linux 操作系统 [1]ulimit 与 TCP backlog:1).修改 ulimit:通过 ulimit 修改 open files 参数,redis 建议把 open files 至少 ...

  4. 修改Win+E映射

    !!!!!!此过程需要修改注册表,请谨慎操作 作用 修改后可以实现Win+E快捷打开任意程序 从原始资源管理器到其它应用 注册表路径: HKEY_CLASSES_ROOT\Folder\shell\o ...

  5. 使用nw.js打包以后的web项目 发布客户端

    一.下载nw.js 直接前往官网下载即可 https://nwjs.io/downloads/ 二.封装最简单的客户端 nw.js下载完成后,在任意位置新建文件夹,例如nwtest,然后在文件夹中新建 ...

  6. hta--Windows运行html的桌面应用程序(HTML应用程序)

    HTA(HTML Application)-- HTML应用程序 作为前端开发,我们能熟练使用html实现各种效果,但是如果要实现一个简单的桌面应用程序那么应该怎么做呢,答案很简单,只需要把html文 ...

  7. 5.mapper出错原因

    1.总结:前个星期mapper出错,很大原因是自己的项目结构创建有问题,大项目下应该是spring init那种项目结构形式,但是在创建多模块的时候应该是使用moudle形式的项目结构: 所以自己在运 ...

  8. 【Diary】CSP-S2 2021 游记 & NOIP 备赛发疯日记

    Day 0 两个极端的回跳. .....不行啊. 我快输不起了........... ------------------------------- 早上被生物钟强行唤醒,逼自己懒床到6:40. 弹琴 ...

  9. MySQL 读书笔记(一)

    1 MySQL 表 1.1 索引组织表 在 InnoDB 存储引擎中,表都是根据主键顺序存放的,这种存储方式称为索引组织表. InnoDB存储引擎中,每张 MySQL表 都有一个唯一主键,如果创建表时 ...

  10. ServletContext 详解(转载)

    转载:https://www.cnblogs.com/zjdxr-up/p/7761813.html ServletContext,是一个全局的储存信息的空间,服务器开始,其就存在,服务器关闭,其才释 ...