IdentityServer4:客戶端模式

IdentityServer4:客戶端模式

Api 資源項目

創建項目

打開 VS,創建一個“AspNet Core WebApi” 項目, 名爲:Dotnet.WebApi.Ids4.CustomerApi

依賴包

添加依賴包

    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="7.0.3" />

添加認證方案

修改 Program.cs 爲如下代碼:


using Microsoft.AspNetCore.Authentication.JwtBearer;

namespace Dotnet.WebApi.Ids4.CustomerApi
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Console.Title = "CustomerAPI服務器";

            var builder = WebApplication.CreateBuilder(args);

            builder.Services.AddControllers();

            // Add services to the container.
            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    //IdentityServer4地址
                    options.Authority = "https://localhost:6001";
                    //認證的ApiResource名稱
                    options.Audience = "CustomerAPIResource";
                    //使用JWT認證類型
                    options.TokenValidationParameters.ValidTypes = new[] { "at+jwt" };
                });

            // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
            builder.Services.AddEndpointsApiExplorer();
            builder.Services.AddSwaggerGen();

            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (app.Environment.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI();
            }

            app.Urls.Add("https://*:6011");
            app.UseHttpsRedirection();

            //身份驗證
            app.UseAuthentication();
            //授權
            app.UseAuthorization();

            app.MapControllers();

            app.Run();
        }
    }
}

(1)添加 JWT 認證:

            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    //IdentityServer4地址
                    options.Authority = "https://localhost:6001";
                    //認證的ApiResource名稱
                    options.Audience = "CustomerAPIResource";
                    //使用JWT認證類型
                    options.TokenValidationParameters.ValidTypes = new[] { "at+jwt" };
                });
 https://localhost:6001 是認證服務器地址。

添加 Api

新增文件:Controllers/CustomerController.cs

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Dotnet.WebApi.Ids4.CustomerApi.Controllers
{
    [Authorize]
    [Route("api/[controller]")]
    [ApiController]
    public class CustomerController : ControllerBase
    {
        /// <summary>
        /// 獲取客戶信息列表。
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetList")]
        public IEnumerable<Customer> GetList()
        {
            return new List<Customer>
            {
                new Customer{ Id=1, Name="客戶1", Phone="電話1"},
                new Customer{ Id=2, Name="客戶2", Phone="電話2"},
                new Customer{ Id=3, Name="客戶3", Phone="電話3"},
            };
        }
    }
}

其中:
(1)在控制器上添加特性:[Authorize],這樣只有登錄用戶才能訪問,這樣就起到保護了Api資源的目的。

Customer.cs

namespace Dotnet.WebApi.Ids4.CustomerApi
{
    /// <summary>
    /// 客戶實體模型
    /// </summary>
    public class Customer
    {
        public int Id { get; set; }
        public string? Name { get; set; }
        public string? Phone { get; set; }
    }
}

認證服務器

創建項目

打開 VS,創建一個“AspNet Core 空” 項目,名爲:Dotnet.WebApi.Ids4.AuthService

依賴包

添加依賴包

<PackageReference Include="IdentityServer4" Version="4.1.2" />

配置 IdentityServer4

創建文件:IdentityConfig.cs,添加如下代碼:

using IdentityServer4.Models;

namespace Dotnet.WebApi.Ids4.AuthService
{
    public static class IdentityConfig
    {
        /// <summary>
        /// 配置API作用域。
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<ApiScope> GetApiScopes()
        {
            return new List<ApiScope>
            {
                //客戶相關API作用域
                new ApiScope("Customer.Read","讀取客戶信息。"),
                new ApiScope("Customer.Add","添加客戶信息。"),

                //共享API作用域
                new ApiScope("News","新聞信息。")
            };
        }

        /// <summary>
        /// 配置ApiResource。
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<ApiResource> GetApiResources()
        {
            //將多個具體的APIScope歸爲一個ApiResource。
            return new List<ApiResource>()
            {
                new ApiResource("CustomerAPIResource", "客戶資源")
                {
                    Scopes={ "Customer.Read", "Customer.Add", "News" }
                }
            };
        }

        /// <summary>
        /// 配置客戶端應用。
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<Client> GetClients()
        {
            return new List<Client>
            {
                new Client
                {
                    //客戶端ID。
                    ClientId = "AppCustomerReadClient",
                    //客戶端憑據模式
                    AllowedGrantTypes = GrantTypes.ClientCredentials, 
                    //認證密鑰。
                    ClientSecrets =
                    {
                        new Secret("App00000001".Sha256())
                    },
                    //客戶端有權訪問的範圍。
                    AllowedScopes={ "Customer.Read" }
                }
            };
        }
    }
}

其中,如下代碼添加了 Client,並將其授權模式設置爲:客戶端模式, 並設置密碼,和 Scope:

                new Client
                {
                    //客戶端ID。
                    ClientId = "AppCustomerReadClient",
                    //客戶端憑據模式
                    AllowedGrantTypes = GrantTypes.ClientCredentials, 
                    //認證密鑰。
                    ClientSecrets =
                    {
                        new Secret("App00000001".Sha256())
                    },
                    //客戶端有權訪問的範圍。
                    AllowedScopes={ "Customer.Read" }
                }

集成 IdentityServer4

修改 Program.cs 爲如下代碼:

namespace Dotnet.WebApi.Ids4.AuthService
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Console.Title = "認證和授權服務器";

            var builder = WebApplication.CreateBuilder(args);

            //註冊IdentityServer4組件
            builder.Services.AddIdentityServer()
                .AddInMemoryApiScopes(IdentityConfig.GetApiScopes())
                .AddInMemoryApiResources(IdentityConfig.GetApiResources())
                .AddInMemoryClients(IdentityConfig.GetClients())
                .AddDeveloperSigningCredential(); // 添加臨時內存中的證書

            var app = builder.Build();
            //修改端口號
            app.Urls.Add("https://*:6001");

            //添加IDS4中間件。
            //在瀏覽器中輸入如下地址訪問 IdentityServer4 的發現文檔:https://localhost:6001/.well-known/openid-configuration
            app.UseIdentityServer();

            app.Run();
        }
    }
}

其中,app.Urls.Add("https://*:6001"); 設置認證服務器的監聽端口爲:6001

客戶端模式客戶端

創建項目

新控制檯項目,名爲:Dotnet.WebApi.Ids4.Client

依賴包

添加依賴包

<PackageReference Include="IdentityServer4" Version="4.1.2" />

Program.cs

將 Program.cs 的代碼修改爲;

namespace Dotnet.WebApi.Ids4.Client
{
    internal class Program
    {
        static void Main()
        {
            Console.Title = "客戶端模式-客戶端";

            //獲取AccessToken
            var token = DataService.GetAccessToken();
            Console.WriteLine(token);

            //獲取API數據
            var data = DataService.GetAPIData(token);
            Console.WriteLine(data.Result);

            Console.ReadKey();
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章