天天看点

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";
                });
           

注意事项:

  • Cookie Scheme 是非必须的,但是如果不设置会报错,但是也不会影响正常使用
  • AddAuthentication

    必须必须必须 放在

    AddIdentityServer

    之后
IdentityServer4实战 - 与API单项目整合

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

IdentityServer4实战 - 与API单项目整合

2.请求API

IdentityServer4实战 - 与API单项目整合

四.资料

本文Demo:

https://github.com/stulzq/IdentityServer4.Samples/tree/master/Practice/05_Integration

目前学习.NET Core 最好的教程 .NET Core 官方教程 ASP.NET Core 官方教程

.NET Core 交流群:923036995  欢迎加群交流

如果您认为这篇文章还不错或者有所收获,您可以点击右下角的【推荐】支持,或请我喝杯咖啡【赞赏】,这将是我继续写作,分享的最大动力!

作者:晓晨Master(李志强)

声明:原创博客请在转载时保留原文链接或者在文章开头加上本人博客地址,如发现错误,欢迎批评指正。凡是转载于本人的文章,不能设置打赏功能,如有特殊需求请与本人联系!