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

发布时间 2023-05-04 16:26:02作者: kele-cc

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

新建一个名为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