新建netcore 项目
安装nuget包
在ConfigureServices 中加入
services.AddIdentityServer().
AddDeveloperSigningCredential().
AddInMemoryClients(InMemoryConfig.GetClients()).
AddInMemoryApiScopes(InMemoryConfig.GetApiScopes()).
AddInMemoryApiResources(InMemoryConfig.GetApiResources());
InMemoryConfig代码如下
public class InMemoryConfig
{
public static IEnumerable<IdentityResource> IdentityResources =>
new IdentityResource[]
{
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
};
/// <summary>
/// ApiResource 资源列表
/// </summary>
public static IEnumerable<ApiResource> GetApiResources()
{
return new[]
{
new ApiResource("Users", "获取用户信息API")
{
Scopes={ "scope1" }//必须
}
};
}
/// <summary>
/// ApiScopes 作用域
/// </summary>
public static IEnumerable<ApiScope> GetApiScopes()
{
return new ApiScope[]
{
new ApiScope("scope1")
};
}
/// <summary>
/// Client 客户端
/// </summary>
public static IEnumerable<Client> GetClients()
{
return new[]
{
new Client
{
ClientId = "HomeJok.Authentication", //客户端唯一标识
ClientName = "Authentication", //客户端名称
ClientSecrets = new [] { new Secret("wintersir".Sha256()) },//客户端密码,进行了加密
AllowedGrantTypes = GrantTypes.ClientCredentials, //授权方式,客户端认证 ClientId+ClientSecrets
AllowedScopes = new [] { "scope1" }, //允许访问的资源
Claims = new List<ClientClaim>(){
new ClientClaim(IdentityModel.JwtClaimTypes.Role,"Admin"),
new ClientClaim(IdentityModel.JwtClaimTypes.NickName,"WinterSir"),
new ClientClaim("email","641187567@qq.com")
}
}
};
}
}
Configure中加入
app.UseIdentityServer();
启动认证服务dotnet run urls=http://*:5000,用postman或者apifox 请求接口
http://localhost:5000/connect/token
grant_type:client_credentials
client_id:HomeJok.Authentication
client_secret:wintersir
可以用jwt工具验证一下token JWT链接1 JWT链接2
认证中心就可以了,下面新建webapi项目
api项目中的stratup 中 ConfigureServices 添加
services.AddAuthentication("Bearer").AddIdentityServerAuthentication(options =>
{
options.Authority = "http://localhost:5000";//认证中心地质
options.ApiName = "Users";//认证中心资源列表中的名称
options.RequireHttpsMetadata = false;
});
Configure中添加
app.UseAuthentication();//鉴权
然后在controller中的接口添加
[Authorize]
dotnet run urls=“http://localhost:8000”
最后用apifox请求接口
token错误时会报错401 ,