首页 > 其他分享 >.Net6基于IdentityServer4配置服务授权以及策略授权

.Net6基于IdentityServer4配置服务授权以及策略授权

时间:2023-05-04 16:35:47浏览次数:53  
标签:builder Microsoft public Net6 using 授权 options IdentityServer4

上一篇中,配置了认证授权服务。这篇配置接口访问时进行授权

新建一个名为Web.API.Test的.Net6项目,引用包源IdentityServer4.AccessTokenValidation

Program注入

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.Authority = "http://localhost:6001";
        options.RequireHttpsMetadata = false;
        options.TokenValidationParameters = new TokenValidationParameters { ValidateAudience = false };
    });
	
	
app.UseAuthentication();

添加TestController

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace Web.API.Test.Controllers;

[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{
    [Authorize]
    [HttpGet("GetAuthTest")]
    public IActionResult GetAuthTest()
    {
        return Ok("授权信息");
    }
}

这样认证授权配置就可以了。启动服务Ids4.ServerWeb.API.Test。先获取AccessToken,再请求接口。
image

上面的认证授权配置没有权限的概念,只要AccessToken符合认证授权服务生成的规则就可以访问接口。在实际的开发中,有些接口是只允许管理员访问的。接下来配置策略授权,改造一下上面的代码。

Program注入

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.Authority = "http://localhost:6001";
        //options.Audience = "api2";
        options.RequireHttpsMetadata = false;
        options.TokenValidationParameters = new TokenValidationParameters { ValidateAudience = false };
    });

builder.Services.AddAuthorization(option =>
{
    // 添加名为AdminPolicy的策略授权,检测Token中Role是否有admin
	// 可以添加多个策略
    option.AddPolicy("AdminPolicy", builder =>
    {
        builder.RequireAuthenticatedUser();
		// 可以添加多个验证
		// builder.RequireClaim(JwtClaimTypes.Scope, "api2");
        builder.RequireRole(JwtClaimTypes.Role, "admin");
    });
});

app.UseAuthentication();

TestController添加GetAdminAuthTest接口

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace Web.API.Test.Controllers;

[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{
    [Authorize]
    [HttpGet("GetAuthTest")]
    public IActionResult GetAuthTest()
    {
        return Ok("授权信息");
    }

    [Authorize("AdminPolicy")]
    [HttpGet("GetAdminAuthTest")]
    public IActionResult GetAdminAuthTest()
    {
        return Ok("只允许角色为admin的访问");
    }
}

用户名为zhangsan拥有admin的角色,获取到的AccessToken可以正常访问接口。lisi则不行
image
image
image
image

源码地址:https://gitee.com/nzyGetHub/Microservice2.git

标签:builder,Microsoft,public,Net6,using,授权,options,IdentityServer4
From: https://www.cnblogs.com/kele-cc/p/17371221.html

相关文章

  • Gitlab CI + Dotnet6
    1.DockerfileFROMmcr.microsoft.com/dotnet/aspnet:6.0WORKDIR/appEXPOSE80EXPOSE443COPY/app/publish.ENTRYPOINT["dotnet","coreqi_api.dll"]2.[.gitlab-ci.yml]stages:-build-project-build-docker-deployvariables:......
  • ubuntu20安装docker、redis、mysql及部署net6应用
    一、更新系统软件包索引sudoaptupdate二、安装dockersudoaptinstalldocker.io三、在docker中安装Mysql拉取mysql镜像dockerpullmysql:latest查看镜像dockerpullmysql:latest运行容器dockerrun-itd-p3306:3306-eMYSQL_RO......
  • IdentityServer4 问题解决
    RedirectUris={"https://localhost:7098/signin-oidc"},PostLogoutRedirectUris={"https://localhost:7098/signout-callback-oidc"},服务端添加这个 RequirePkce=false,添加这一句......
  • 微信网页静默授权(snsapi_base与snsapi_userinfo区别)
    1、区别:有无授权完整服务弹框2、业务:有的网页只需要用户openid进行绑定,所以不需要弹框授权完整服务,用户会觉得整体体验不好。3、snsapi_base:scope发起的网页授权,是用来获取进入页面的用户的openid的,并且是静默授权并自动跳转到回调页的。注:静默的另一种:对于已关注公众号的用户,......
  • License授权文件生成器源码
    功能介绍1.对销售后的软件或网站执行版权控制,防止被非法另行出售;2.对网站域名进行有效的管理监控,防止非法域名或未授权域名;3.防止黑客使用极端手段获取网站或程序原文件后非法部署;系统功能:1.完整版Lisence生成工具。2.对网站使用域名执行控制。3.对网站域名使用时间执行授权控制......
  • P.22-认证配置详解、P.23-权限系统的作用、P.24-授权基本流程
    P.22-认证配置详解在SecurityConfig下进行修改@ConfigurationpublicclassSecurityConfigextendsWebSecurityConfigurerAdapter{//创建BCryptPasswordEncoder注入容器@BeanpublicPasswordEncoderpasswordEncoder(){returnnewBCryptPasswordEn......
  • 解决 NET6 GET请求不设置参数值报错问题
    1、调用的方法1///<summary>2///获取干预集合3///</summary>4///<returns></returns>5[HttpGet]6publicJsonResultGetIntervenes(stringkeyword)7{89Li......
  • SpringSecurity从入门到精通:授权基本流程&设置资源所需权限&封装权限信息
    授权基本流程在SpringSecurity中,会使用默认的FilterSecurityInterceptor来进行权限校验,在FilterSecurityInterceptor中会从SecurityContextHilder获取其中的Authentication,然后获取其中的权限信息,当前用户是否拥有访问当前资源所需的权限所以我们在项目中只需要把当前登......
  • 【HMS Core】Health Kit取消授权接口怎么辨识是哪个用户取消授权呢?
    【问题描述1】取消授权接口怎么辨识是哪个用户取消授权呢? 【解决方案】取消授权时,请求头中需要传入access_token,此access_token对应某个用户。详情请查看取消授权接口:https://developer.huawei.com/consumer/cn/doc/development/HMSCore-References/cancel-scpoes-00000010......
  • Net6+axios 返回401 axios不能获取 状态码问题解决
    错误使用app.UseAuthentication();//认证 这里要加,位置不能反app.UseAuthorization();//授权 app.UseCors();//启用Cors解决方法app.UseCors();//启用Corsapp.UseAuthentication();//认证 这里要加,位置不能反app.UseAuthorization();//授权  更换前更换后  ......