IdentityServer4密码模式
书接上文。
做完了客户端模式来做密码模式。
密码模式需要用户和密码。
现在Config里面添加个方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public static List<TestUser> GetUsers() { return new List<TestUser>() { new TestUser() { //用户名 Username= "apiUser" , //密码 Password= "apiUserPassword" , //用户Id SubjectId= "0" , //在IdentityServer4中,TestUser有一个Claims属性,允许自已添加Claim,有一个ClaimTypes枚举列出了可以直接添加的Claim 同时需要在ApiResouce的构造函数有一个重载支持传进一个Claim集合,用于允许该Api资源可以携带那些Claim Claims= new List<Claim>(){ new Claim(ClaimTypes.Role, "admin" ) } } }; } |
Clients方法里面增加一个客户端变成这样
public static IEnumerable<Client> Clients => new Client[] { //1:客户端模式 new Client { ClientId = "apiClientCd", ClientName = "Client Credentials Client", AllowedGrantTypes = GrantTypes.ClientCredentials, ClientSecrets = { new Secret("apiSecret".Sha256()) }, AllowedScopes = { "secretapi" } }, //密码模式 new Client() { //客户端Id ClientId="apiClientPassword", //客户端密码 ClientSecrets={new Secret("apiSecret".Sha256()) }, //客户端授权类型,ClientCredentials:客户端凭证方式 AllowedGrantTypes=GrantTypes.ResourceOwnerPassword, //允许访问的资源 AllowedScopes={ "secretapi" } } };
在StartUp.cs里面增加一个 builder.AddTestUsers(Config.GetUsers()),表示验证用户。
API项目不变
然后用postman请求,此时注意,需要加两个参数,用户名和密码,就是你增加的用户名和密码
复制这个token依然能够访问你的资源。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
2020-09-02 任务的取消