ASP.NET Core分布式项目实战(客户端集成IdentityServer)--学习笔记

任务9:客户端集成IdentityServer

新建 API 项目

dotnet new webapi --name ClientCredentialApi

控制器添加验证

using Microsoft.AspNetCore.Authorization;

namespace ClientCredentialApi.Controllers
{
    [ApiController]
    [Route("[controller]")]
    [Authorize]
    public class WeatherForecastController : ControllerBase

添加验证之后这个 API 就无法访问,需要添加认证授权模式

因为这是客户端,所以只需要添加 IdentityServer4.AccessTokenValidation

添加 Nuget 包之后

dotnet restore

注册服务

services.AddAuthentication("Bearer")
        .AddIdentityServerAuthentication(options => {
            options.Authority = "http://localhost:5000";// 获取授权地址
            options.RequireHttpsMetadata = false;
            options.ApiName = "api";
        });

使用服务

app.UseAuthentication();

在 Program.cs 中配置启动端口

webBuilder.UseUrls("http://localhost:5001");

启动程序

dotnet run

访问地址

http://localhost:5001/weatherforecast

返回 401,未授权

VS Code 添加另一个控制台,启动 IdentityServerCenter

访问地址

http://localhost:5000/.well-known/openid-configuration

获取 token_endpoint

"token_endpoint": "http://localhost:5000/connect/token",

通过 Postman 获取 token

使用 Post 的方式访问 token_endpoint

http://localhost:5000/connect/token

Body 添加三个参数(参数在 IdentityServerCenter 的 Config.cs 中定义)

发送请求获取 access_token

通过 access_token 访问客户端

访问地址

http://localhost:5001/weatherforecast

Headers 添加参数 Authorization,Value 为 Bearer + access_token

返回200,授权访问成功

课程链接

http://video.jessetalk.cn/course/explore

相关文章

ASP.NET Core分布式项目实战(业务介绍,架构设计,oAuth2,IdentityServer4)--学习笔记

ASP.NET Core分布式项目实战(课程介绍,MVP,瀑布与敏捷)--学习笔记

ASP.NET Core快速入门 -- 学习笔记汇总

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值