天天看點

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(李志強)

聲明:原創部落格請在轉載時保留原文連結或者在文章開頭加上本人部落格位址,如發現錯誤,歡迎批評指正。凡是轉載于本人的文章,不能設定打賞功能,如有特殊需求請與本人聯系!