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 之后

1549006874861

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

1549007117138

2.请求API

1549007152188

四.资料#

本文Demo:

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

作者:晓晨Master(李志强)

出处:https://www.cnblogs.com/stulzq/p/10346095.html

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。

posted @   晓晨Master  阅读(11901)  评论(4编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
more_horiz
keyboard_arrow_up dark_mode palette
选择主题
menu
点击右上角即可分享
微信分享提示