阻止过期的访问令牌从资源服务器检索数据

2023-12-11

我一直在摆弄 IDS 4,但遇到了一个小问题。我将令牌生命周期设置为大约 15 秒,即使它们已过期,我仍然可以从资源服务器检索日期。如果我从客户端调用的标头中删除令牌,则会收到 401 错误。

Client

    [Authorize]
    public async Task<ActionResult> Shouts()
    {

        var accessToken = await HttpContext.GetTokenAsync("access_token");
        var tokenh = new JwtSecurityTokenHandler();

        var jwtSecurityToken= tokenh.ReadJwtToken(accessToken);

        var val = jwtSecurityToken.ValidTo;



        using (var client = new HttpClient())
        {

            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
            var rawResponse = await client.GetAsync("http://localhost:5002/api/Values/Get");

            if (rawResponse.StatusCode == System.Net.HttpStatusCode.Unauthorized)
            {
                var refreshSucc = await this.RefreshTokensAsync(this.HttpContext);
                if (!refreshSucc)
                {
                    var authServerInfo = await this.GetAuthenticationServerInfo();
                    return Redirect(authServerInfo.AuthorizeEndpoint);
                }
            }

            var response = await (rawResponse).Content.ReadAsStringAsync();
            var data = JsonConvert.DeserializeObject<List<String>>(response);
            return View("Shouts", data);
        }
    }
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            services.AddAuthentication(options =>
            {                
                options.DefaultScheme = "Cookies";
                options.DefaultChallengeScheme = "oidc";                
            })
                .AddCookie("Cookies",o=>o.LogoutPath="/home/logout")
                .AddOpenIdConnect("oidc", opt => 
                {
                    opt.SignInScheme = "Cookies";
                    opt.Authority = "http://localhost:5000";
                    opt.RequireHttpsMetadata = false;
                    opt.ClientId = "AuthTest_Code";
                    opt.ClientSecret = "secret";
                    opt.ResponseType = "id_token code";
                    opt.Scope.Add("TestAPI");
                    opt.Scope.Add("offline_access");
                    opt.Scope.Add("email");
                    opt.GetClaimsFromUserInfoEndpoint = true;
                    opt.SaveTokens = true;                    
                });
            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseAuthentication();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }

认证服务器

    public static IEnumerable<Client> GetClients()
    {
        return new List<Client>
        {              
               new Client
            {
                ClientId = "AuthTest_Code",
                ClientSecrets=new []{new Secret("secret".Sha256()) },
                AllowedGrantTypes = GrantTypes.Hybrid,
                AllowedScopes = new List<string>
                {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile,
                    IdentityServerConstants.StandardScopes.Email,                        
                    "TestAPI"
                },
                AllowAccessTokensViaBrowser=true,
                AllowOfflineAccess=true,
                RedirectUris = new [] { "http://localhost:5001/signin-oidc" },
                PostLogoutRedirectUris={ "http://localhost:5001/signout-callback-odic"},
                RequireConsent=false,
                AccessTokenLifetime=15,
                AbsoluteRefreshTokenLifetime=15
            }
        };
    }

public class Startup
{
    public IHostingEnvironment Environment { get; }

    public Startup(IHostingEnvironment environment)
    {
        Environment = environment;
    }
    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
        var isServer = services.AddIdentityServer()                
            .AddSigningCredential(new X509Certificate2(@"C:\OpenSSLCerts\Authenticate.pfx", "Password1"))
            .AddInMemoryApiResources(TestConfig.GetApis())
            .AddInMemoryClients(TestConfig.GetClients())
            .AddInMemoryIdentityResources(TestConfig.GetIdentityResources())
            .AddTestUsers(TestConfig.GetUsers());


        services.AddMvc();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (Environment.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseIdentityServer();

        app.UseStaticFiles();

        app.UseMvcWithDefaultRoute();
    }
}

资源服务器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace ResourceAPI
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvcCore()
                .AddAuthorization()
                .AddJsonFormatters();

            services.AddAuthentication("Bearer")                
                .AddIdentityServerAuthentication(options =>
                {
                    options.Authority = "http://localhost:5000";
                    options.RequireHttpsMetadata = false;                    
                    options.ApiName = "TestAPI";                    
                });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseAuthentication();
            app.UseMvc();
        }
    }
}


    [Route("api/[controller]")]
    public class ValuesController:ControllerBase
    {
        [HttpGet]
        [Route("Get")]
        [Authorize]
        public async Task<IActionResult> Get()
        {
            var username = User.Claims.FirstOrDefault(t => t.Type == "email")?.Value;
            return Ok(new string[] { "value1", "value2" });
        }      
    }

访问令牌: eyJhbGciOiJSUzI1NiIsImtpZCI6IjQ0Q0Q4NjFEQjA0MzdEMUM4NUY2REU0MTIyMkFDOEIwMTE3M0Q2MTAiLCJ0eXAiOiJKV1QiLCJ4NXQiOiJSTTJHSGJCRGZSeUY5dDVCSWlySXNCRnoxaEEifQ.eyJuY mYiOjE1NDIxMjc4OTQsImV4cCI6MTU0MjEyNzkwOSwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo1MDAwIiwiYXVkIjpbImh0dHA6Ly9sb2NhbGhvc3Q6NTAwMC9yZXNvdXJjZXMiLCJUZXN0 QVBJIl0sImNsaWVudF9pZCI6IkF1dGhUZXN0X0NvZGUILCJzdWIiOiIxIiwiYXV0aF90aW1lIjoxNTQyMTI3ODkzLCJpZHAiOiJsb2NhbCIsImVtYWlsIjoiRGF2aWRAQUJldHRlckxpZmUuY28 uemEiLCJzY29wZSI6WyJvcGVuaWQiLCJwcm9maWxlIiwiZW1haWwiLCJUZXN0QVBJIiwib2ZmbGluZV9hY2Nlc3MiXSwiYW1yIjpbInB3ZCJdfQ.hNskjZz3IBqPg_5T0xVwYEP5RukcMt3l019PR p74vNBkiEr6FLvBADa_eylhNGA8qDd7SwyDkq6APaKxaNt0YybAChZvFW6pzLlfknVVHM1vuN7PDOX9PNGhFK9kSONBypXo6JqV3epactsmJvhr3FZxBSufUDRyV4j_YY3O8TCjJf_5UORc_3ox9clNd jt-Vx-BlcDjVbpBw2P76F3pq2IPPDM139H4qYcyaTzSlEbFd3EdVwO6O85bWM1G8yQ9zQAUk23It29oHxTtwsi5Wg4Zpmt7K7AlvKjKxKoxw_Y32QdBkGY9xU_KXOn4h0WJV3LG-InZ c7BveLGHq6ncaQ


尝试在 Web api(资源服务器)中将 options.JwtValidationClockSkew 属性设置为零

   services.AddAuthentication("Bearer")
        .AddIdentityServerAuthentication(options =>
        {
            options.JwtValidationClockSkew = TimeSpan.Zero;
            options.Authority = "https://localhost:44323";
            options.RequireHttpsMetadata = false;

            options.ApiName = "api1";
        });

Microsoft JWT 验证中间件存在时钟偏差。默认设置为 5 分钟。建议保留默认值(300 秒/5 分钟)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

阻止过期的访问令牌从资源服务器检索数据 的相关文章

随机推荐

  • 适用于移动设备的 HTML5 拖放

    这是我对 WHATWG HTML5 的实现拖放 function allowDrop ev ev preventDefault function drag ev ev dataTransfer setData Text ev target
  • CodenameOne:VKB改变画面

    我有一个在 CodenameOne 平台上开发的应用程序 其中有用于手动输入的文本字段 每次当 VKB 在 Android 上显示时 屏幕内容都会被推到底部 尤其是文本字段变得如此之薄 以至于看不到任何字符 我怎样才能防止这种情况发生 在
  • 将几个不连续的列放入数组中

    我尝试尽可能高效地将 4 列加载到数组中 我试过 dim ar ar sheet1 Range C2 C2681 G2 G2681 J2 J2681 T2 T2681 但只有第一列被加载到数组中 我也尝试过 ar Range C2 T la
  • 是否可以使 col-md-3 彼此更靠近或居中? [复制]

    这个问题在这里已经有答案了 是否有可能使 col md 3 彼此更接近 这是我的代码 div class container div class row div class col md 3 p Lorem ipsum dolor sit
  • Eclipse 中的 Android 应用程序问题

    我是一名 NET 开发人员 但我喜欢 JAVA 所以在空闲时间我会使用它 我通常不使用 Eclipse 但我安装了 ADT eclipse 插件和 Andriod SDK 然后我开始学习 我用 TableLayout 制作了一个新项目 它看
  • $("#id").load 和 $.ajax 之间的区别?

    有谁知道有什么区别 id load and ajax 让我为您澄清一下 ajax 是 jQuery 提供的基本和低级 ajax 函数 这意味着您可以做任何您想做的事情XmlHttpRequest目的 但曾几何时 jQuery 开发者认为实际
  • 在 GraphQL 模式中创建类型时是否可以重命名字段?

    当定义userType在服务器上的以下 GraphQL 模式中 如何将 名称 字段重命名为 名字 同时仍然引用中的 名称 字段fakeDatabase 以下代码片段是从官方 GraphQL 文档 var express require ex
  • 为什么我每隔一天都会收到“太多获取失败”信息

    当我们运行两个处理大约 400 GB 数据的大猪作业时 我会从一个或其他任务跟踪器中收到此错误 我们发现 在杀死作业并使集群保持沉默一段时间后 一切又恢复正常 请提出真正的问题是什么 解决办法 修改datanode节点的 etc hosts
  • Magento 将产品批量分配到类别

    正如标题所示 我需要将产品批量分配到一个类别 并且从管理员那里我一次只能编辑一个产品 我不知道为什么从类别页面的 类别产品 选项卡中批量添加它们不起作用 这就是为什么我需要另一种快速的方法 例如使用 phpMyAdmin 或类似的方法 有什
  • Android 上的 MongoDB

    有谁知道 MongoDB 如何在 Android 上运行 它可以在本地工作并且数据稍后会被复制吗 是否只能通过网络后端在线工作 MongoDB 有几个版本的下载操作系统 然而 Android 并不是这些系统之一 人们使用 MongoDB 作
  • 如何将二进制文件的全部内容保存到 postgres 数据库中?

    我正在尝试将二进制数据保存到 postgres 中 部分代码如下所示 string readFile2 const string fileName ifstream ifs fileName c str ios in ios binary
  • 使用按钮更改另一个类的某些内容的状态

    我是 React 新手 很难理解状态的概念 下面我从 MUI 导出一个步进器 我使用状态 export default function CustomizedSteppers const steps Zoninfo Betals tt B
  • 为什么不能在函数文字中为变量分配占位符?

    我无法理解函数文字中的下划线 val l List 1 2 3 4 5 l filter gt 0 工作正常 l filter gt 0 工作正常 l filter val x 1 1 3 gt 0 ie you can have mult
  • 使用 `seaborn.objects` 堆叠到 100%

    我正在尝试绘制一个图 其中条形或区域使用新的比例调整为 100 seaborn objects界面 我似乎无法理解so Norm 工作 无论有没有by 这是我到目前为止所得到的 import seaborn as sns import se
  • 测试向量的所有元素是否相等

    我想测试非空向量是否包含相同的元素 这是最好的方法吗 count vecSamples begin 1 vecSamples end vecSamples front vecSamples size 1 在 c 11 中 或升压算法 std
  • Pygame OpenGL 3D 立方体滞后

    我正在关注 pyOpenGL 上相当老的教程系列 我正在做的和他完全一样 然而我遇到了延迟 我有带有 8GB 内存的 AMD FX 6300 GTX 1050ti 并且文件存储在闪存驱动器上 我读过一些地方使用glBegin and glE
  • 八顶点立方体的法向量

    我正在使用 WEBGL 今天遇到了我的立方体顶点法线的问题 我用立方体网格检查了我的代码来自互联网而且效果很好 问题是 来自互联网的立方体有 24 个顶点 每个面 4 个顶点 6 个面 我认为这对于我的立方体来说太多了 摆弄我的立方体 Fi
  • 如何查询DOTNET_CLI_TELEMETRY_OPTOUT是否永久设置为TRUE?

    如果我输入 set DOTNET CLI TELEMETRY OPTOUT 1 or setx DOTNET CLI TELEMETRY OPTOUT 1 要永久保存此设置 则应将设置 DOTNET CLI TELEMETRY OPTOUT
  • 如何在CSV文件中同时转义逗号和双引号?

    我正在编写一个 Java 应用程序以将数据从 Oracle 导出到 csv 文件 不幸的是 数据的内容可能相当棘手 逗号仍是分隔符 但行上的某些数据可能如下所示 ID FN LN AGE COMMENT 123 John Smith 39
  • 阻止过期的访问令牌从资源服务器检索数据

    我一直在摆弄 IDS 4 但遇到了一个小问题 我将令牌生命周期设置为大约 15 秒 即使它们已过期 我仍然可以从资源服务器检索日期 如果我从客户端调用的标头中删除令牌 则会收到 401 错误 Client Authorize public