IdentityServer4实战 - 与API单项目整合

本文详细介绍了如何在同一个项目中整合IdentityServer4与API,包括在Startup.cs中配置IdentityServer4,添加认证,以及中间件配置。并通过测试验证了整合后的功能,提供了完整的步骤和代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文: 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

posted on 2019-02-01 17:08 NET未来之路 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/lonelyxmas/p/10346380.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值