通过密码访问API

一、客户端

图:

五、通过密码访问API-LMLPHP

客户端请求代码:

        static void Main(string[] args)
{
Console.WriteLine("确定三个项目都已经启动");
Console.Read();
Console.WriteLine("按任意键开始运行");
// discover endpoints from metadata
var client = new HttpClient();
var disco = client.GetDiscoveryDocumentAsync("http://localhost:5000").ConfigureAwait(false).GetAwaiter().GetResult();
if (disco.IsError)
{
Console.WriteLine(disco.Error);
return;
}
// request token
var tokenResponse = client.RequestPasswordTokenAsync(new PasswordTokenRequest
{
Address = disco.TokenEndpoint,//默认
ClientId = "socialnetwork",
ClientSecret = "secret",
//GrantType = "password",//这句话可以加也可以不加 与资源服务器对应 AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
UserName = "[email protected]",
Password = "password",
Scope = "socialnetwork",
}).ConfigureAwait(false).GetAwaiter().GetResult();
// call api
client.SetBearerToken(tokenResponse.AccessToken);
var response = client.GetAsync("http://localhost:5001/identity").ConfigureAwait(false).GetAwaiter().GetResult();
if (!response.IsSuccessStatusCode)
{
Console.WriteLine(response.StatusCode);
}
else
{
var content = response.Content.ReadAsStringAsync().ConfigureAwait(false).GetAwaiter().GetResult();
Console.WriteLine(JArray.Parse(content));
}
Console.ReadKey(false);//因为控制台会关闭,设置不关闭
}

二、颁发token服务器

五、通过密码访问API-LMLPHP

服务端配置文件必须添加

    public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
var builder = services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryIdentityResources(Config.GetIdentityResources())
.AddInMemoryApiResources(Config.ApiResources())
.AddInMemoryClients(Config.Clients())//添加客户端
.AddTestUsers(Config.Users().ToList());//添加用户支持
// rest omitted
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
} app.UseIdentityServer(); app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
}

如果不加则是

五、通过密码访问API-LMLPHP

05-25 09:45