在上一篇中,配置了认证授权服务。这篇配置接口访问时进行授权
新建一个名为
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.Server
和Web.API.Test
。先获取AccessToken,再请求接口。
上面的认证授权配置没有权限的概念,只要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
则不行
源码地址:https://gitee.com/nzyGetHub/Microservice2.git
标签:builder,Microsoft,public,Net6,using,授权,options,IdentityServer4 From: https://www.cnblogs.com/kele-cc/p/17371221.html