首页 > 其他分享 >IdentityServer4:简化(隐藏)模式

IdentityServer4:简化(隐藏)模式

时间:2023-03-09 16:11:50浏览次数:26  
标签:builder app public options 简化 new 隐藏 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();

            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    //IdentityServer4地址
                    options.Authority = "https://localhost:6001";
                    //认证的ApiResource名称
                    options.Audience = "CustomerAPIResource";
                    //使用JWT认证类型
                    options.TokenValidationParameters.ValidTypes = new[] { "at+jwt" };
                });

            //配置跨域。
            builder.Services.AddCors(options =>
            {
                options.AddPolicy("AppCors", policy => policy.WithOrigins("https://localhost:6021")
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .AllowCredentials()
                );
            });

            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.UseCors("AppCors");
            //身份验证
            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 是认证服务器地址。

(2) 纯前端项目存在跨域问题,故这里资源服务器为纯前端项目提供跨域支持。

            //配置跨域。
            builder.Services.AddCors(options =>
            {
                options.AddPolicy("AppCors", policy => policy.WithOrigins("https://localhost:6021")
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .AllowCredentials()
                );
            });
           app.UseCors("AppCors");

添加 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"},
            };
        }
    }
}

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();
        }
    }
}

标签:builder,app,public,options,简化,new,隐藏,IdentityServer4,客户端
From: https://www.cnblogs.com/easy5weikai/p/17198853.html

相关文章

  • mysql使用DBeaver工具导入数据,隐藏坑
    数据中不能包含",否则会识别失败!   其实是由于数据里面有英文分号,”导致工具识别出错。  将分号去掉即可。......
  • IdentityServer4:客户端模式
    IdentityServer4:客户端模式Api资源项目创建项目打开VS,创建一个“AspNetCoreWebApi”项目,名为:Dotnet.WebApi.Ids4.CustomerApi依赖包添加依赖包<PackageRe......
  • IdentityServer4: 配置项持久化
    目录IdentityServer配置项持久化创建IdentityServer项目添加依赖包添加QuickstartUI数据库迁移ConfigurationDbContextPersistedGrantDbContext生成初始化数据严重BU......
  • IdentityServer4: 集成 AspNetCore Identity 框架
    IdentityServer4集成identity框架新增依赖包在IdentityServer4项目中新增集成AspNetCoreIdentity所需的依赖包:<PackageReferenceInclude="IdentityServer......
  • 第六章 数据简化原理
    第六章数据简化原理该笔记基于书本《统计推断》,笔记省略部分均可在该书上找到对应的详细解释。6.1基本定义定义$T(\boldsymbol{X})$是一个统计量,其中\(\bolds......
  • 使用反射简化批量保存sql语句
    写批量保存的时候遇到实体类字段比较多的时候写起来非常的头疼,所以我想能不能通过程序自动获取拼接思路:1.通过反射获取实体类的所有字段2.把字段拼接为id,user_name,us......
  • 在Linux和Unix上隐藏Nginx版本
    使用CLI显示当前Nginx版本Nginx将在错误页面和“服务器”响应标头字段中显示版本。我们可以使用以下命令进行验证:示例输出:$curl-Ihttps://your-domain$curl-I......
  • 数学结构化语言——矩阵的分块简化(四)
    分块矩阵是线性代数中的一个重要内容,是处理阶数较高的矩阵时常采用的技巧,也是数学在多领域的研究工具。对矩阵进行适当分块,可使高阶矩阵的运算可以转化为低阶矩阵的运算,同......
  • VSCode 隐藏部分右键菜单
    资源管理器右键菜单:进入设置界面、输入ExplorerContextMenu搜索设置。编辑器右键菜单(包括编辑器标题右键菜单):进入设置界面、输入EditorContextMenu搜索设置。编辑器......
  • 微信怎么隐藏视频号入口
    这两年短视频风靡全球,但是他们极为占据用户的宝贵时间,由于视频流切换下个视频的成本极低,导致很容易上瘾,一旦开始刷,就很难停下来,包括知乎里的段子、笑话这类文本流,也有类似......