IdentityServer4实战中怎么与API单项目整合,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
一.前言
我们在实际使用 IdentityServer4 的时候,可能会在使用 IdentityServer4 项目添加一些API,比如 找回密码、用户注册、修改用户资料等,这些API与IdentityServer4怎么共存在一个项目呢?
二.整合
1.首先在 Startup.cs
中添加 IdentityServer4
services.AddIdentityServer(options=>options.Authentication.CookieAuthenticationScheme= "Cookies")
.AddDeveloperSigningCredential()
.AddInMemoryIdentityResources(Config.GetIdentityResources())
.AddInMemoryApiResources(Config.GetApis())
.AddInMemoryClients(Config.GetClients())
.AddTestUsers(Config.GetUsers());
2.然后在添加 IdentityServer4 下添加认证
services.AddAuthentication("Bearer")
.AddCookie("Cookies")
.AddJwtBearer("Bearer", options =>
{ //identityserver4 地址 也就是本项目地址
options.Authority = "http://localhost:5000";
options.RequireHttpsMetadata = false;
options.Audience = "api1";
});
注意事项:

3.中间件配置
app.UseIdentityServer();
这里只需 UseIdentityServer 即可
三.测试
在 IdentityServer4 项目添加一个 Controller
[Route("identity")]
[Authorize]public class IdentityController : ControllerBase{
public IActionResult Get() {
return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
}
}
将 IdentityServer4 项目的端口设置为5000,使用密码模式,下面进行测试:
1.请求Token

2.请求API

关于IdentityServer4实战中怎么与API单项目整合问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注天达云行业资讯频道了解更多相关知识。