客户端认证:搭建认证服务器
这玩意坑了我1天半的时间,网上找的资源和方法都是坑,以下是我遇到的问题做个记录
目前知识个服务端,客户端还没完成,后续会增加客户端内容
参考的连接:
https://www.cnblogs.com/monster17/p/13261647.html 虽然有坑,但是有个好思路
http://www.identityserver.com.cn/Home/Detail/aspnetcoreidentity 这也有坑
https://identityserver4.readthedocs.io/en/latest/quickstarts/1_client_credentials.html 最终还是这个靠谱
废话不多说,看代码
一、 服务端
1.新建API项目,nuget 搜索安装 IdentityServer4
2.新增一个Config.cs文件,代码如下,注意ApiScope
using IdentityServer4.Models;
using System.Collections.Generic;
namespace IdentityServerServiceDemo
{
public class Config
{
public static IEnumerable<ApiScope> ApiScopes =>
new List<ApiScope>
{
new ApiScope("api1", "My API")
};
public static IEnumerable<Client> Clients =>
new List<Client>
{
new Client
{
ClientId = "client",
// no interactive user, use the clientid/secret for authentication
AllowedGrantTypes = GrantTypes.ClientCredentials,
// secret for authentication
ClientSecrets =
{
new Secret("secret".Sha256())
},
// scopes that client has access to
AllowedScopes = { "api1" }
}
};
}
}
3.Startup代码如下
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace IdentityServerServiceDemo
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryApiScopes(Config.ApiScopes)
.AddInMemoryClients(Config.Clients);
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseIdentityServer();
}
}
}
4.启动后访问这个地址 {host}/.well-known/openid-configuration 说明接口通了,但是不能高兴的太早
5.用postman测试拿到token才是真的OK
总结:
坑点一
网上的资源有很多都是form-data去请求数据,早期版本我不清楚,但是现在用的是 x-www-form-urlencoded,
坑点二:
Config.cs那个代码片段里,相对应的startup里也用的是AddInMemoryApiResources,scopes读的不是这玩意,
return new List<ApiResource>
{
new ApiResource("api1", "My API")
};