一、服务端代码
1、静态资源代码
public class InitConfig
{
/// <summary>
/// 定义ApiResource
/// </summary>
/// <returns></returns>
public static IEnumerable<ApiResource> GetApiResources()
{
return new[]
{
new ApiResource("UserApi","用户获取Api")
};
}
/// <summary>
/// you can read DB in this function
/// </summary>
/// <returns></returns>
public static IEnumerable<Client> GetClients()
{
return new[]
{
new Client
{
ClientId="ClientId1",
ClientSecrets=new [] { new Secret("123456".Sha256())},
AllowedGrantTypes=GrantTypes.ResourceOwnerPassword, // GrantTypes.ClientCredentials,
AllowedScopes=new []{ "UserApi" },
Claims=new List<Claim>(){
new Claim(IdentityModel.JwtClaimTypes.Role,"Admin")
}
}
};
}
public static List<TestUser> GetTestUser()
{
return new List<TestUser>
{
new TestUser
{
SubjectId = "SubjectId 1",
Username = "scott",
Password = "password",
Claims = new List<Claim> {
new Claim(JwtClaimTypes.Email, "scott@163.com"),
new Claim(JwtClaimTypes.Role, "admin1")
}
}
};
}
}
2、Startup.cs 配置
//configureServices 方法 注入申明
services.AddMvc()
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddTestUsers(InitConfig.GetTestUser())
.AddInMemoryClients(InitConfig.GetClients())
.AddInMemoryApiResources(InitConfig.GetApiResources());
//Configure 使用中间件
app.UseIdentityServer();// use IdentityServer MiddleWare
二、客户端获取Token
1、可以使用postman测试
URL: 服务端地址/connect/token
参数如下:
client_id:ClientId1
client_secret:123456
grant_type:client_credentials//客户端登录模式
grant_type:password //用户名密码登录模式设置
//如果为用户名密码模式须要用户名密码参数
username:scott
password:password
2、可以创建一个,net core项目作为客户端测试
//记得Nuget引入IdentityModel
//the lastest IdentityModel have many diffirence with before version in use
var client = new HttpClient();
//客户端验证模式
//var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
//{
// Address = "http://localhost:51482/connect/token",
// ClientId = "陈常春",
// ClientSecret = "123456",
//});
//用户名密码验证模式
var tokenResponse = await client.RequestPasswordTokenAsync(new PasswordTokenRequest
{
Address = "http://localhost:51482/connect/token",
ClientId = "ClientId1",
ClientSecret = "123456",
UserName = "scott",
Password = "password"
});
if (tokenResponse.IsError)
{
Console.WriteLine(tokenResponse.Error);
return tokenResponse.Error;
}
return tokenResponse.AccessToken ;