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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM