zoukankan      html  css  js  c++  java
  • Asp.Net Core IdentityServer4 API访问

    IdentityServer4 是一个中间件 ,它能够将符合规范的 OpenID Connect 和 OAuth2.0 端点添加到任意一个 ASP.NET Core 应用程序中。详细理论看官网文档

    安装IdentityServer4的模板
    dotnet new -i IdentityServer4.Templates
    使用空模板创建IdentityServer4的服务
    dotnet new is4empty -n IdentityServer
    打开项目编辑Config

    配置里添加一个客户端和保护的api资源

     public static class Config
     {
         public static IEnumerable<IdentityResource> Ids =>
             new IdentityResource[]
             {
                 new IdentityResources.OpenId()
             };
    
         public static IEnumerable<ApiResource> Apis =>
             new ApiResource[]
             {
                  new ApiResource("api1", "My API")
             };
    
         public static IEnumerable<Client> Clients =>
             new Client[]
             {
                  new Client
                 {
                     ClientId = "client",
    
                     // 没有交互式用户,请使用clientid / secret进行身份验证
                     AllowedGrantTypes = GrantTypes.ClientCredentials,
    
                     // 认证加密
                     ClientSecrets =
                     {
                         new Secret("secret".Sha256())
                     },
    
                     // 客户有权访问的范围
                     AllowedScopes = { "api1" }
                 }
             };
     }
    

    创建一个api资源

    添加引用
    Install-Package Microsoft.AspNetCore.Authentication.JwtBearer -Version 3.1.3
    加入IdentityServer服务

         services.AddAuthentication("Bearer")
                      .AddJwtBearer("Bearer", options =>
                      {
                          options.Authority = "http://localhost:5000";//IdentityServer的地址
                          options.RequireHttpsMetadata = false;
                          options.Audience = "api1";//对应IdentityServer里的api资源
                      });
        app.UseAuthentication();
        app.UseAuthorization();   
    


    控制器添加验证

    添加一个控制台客户端,然后客户端请求IdentityServer 服务获取token,携带token请求相对应的Api资源
    添加引用
    Install-Package IdentityModel -Version 5.0.0-preview.0

  • 相关阅读:
    caffe用到的命令和零碎知识
    Manjaro — ssh出现22端口拒绝访问问题(port 22: Connection refused)
    Linux 解压z01 .z02 .z03... zip分卷
    Manjaro_Windows双系统安装
    Linux 的chsh命令
    mat2json, python读取mat成字典, 保存json
    最便捷的caffe编译方法 ---- cmake+anaconda虚拟环境
    复制跳过软链接
    使用Screen解决ssh连接中断导致的训练中断问题
    Caffe训练时Loss=87.3365问题
  • 原文地址:https://www.cnblogs.com/SuperDust/p/12757522.html
Copyright © 2011-2022 走看看