当前位置: 首页 > 知识库问答 >
问题:

Servicestack导致承载令牌无效

葛哲彦
2023-03-14

我们有一个由Angular网站访问的ServiceStack服务。随机的,我们无法确定它发生的原因或时间,承载令牌正在失效。我们可以看到不接受承载令牌,并显示错误消息。“令牌已失效”。我确信我们没有重新启动servicestack服务,我们仍然在请求中传递原始的承载令牌。我们没有实现任何使承载令牌无效的逻辑。我知道这有点模糊。如果有人能告诉我如何在ServiceStack中解决这个问题。这就是我需要的。

使用servicestack 5.4.1

namespace cbw.mvc.web.service
{

    public class AppHost : AppHostBase
    {
        public AppHost() : base("ServiceStack + .NET Core", typeof(StartupService).Assembly) { }

        public override void Configure(Funq.Container container)
        {
            Plugins.Add(new SwaggerFeature());

            Plugins.Add(new RazorFormat());

            //Works but recommend handling 404 at end of .NET Core pipeline
            //this.CustomErrorHttpHandlers[HttpStatusCode.NotFound] = new RazorHandler("/notfound");
            this.CustomErrorHttpHandlers[HttpStatusCode.Unauthorized] = new RazorHandler("/login");

            //To include null values in the json globally
            JsConfig.IncludeNullValues = true;
            //This is mandate. We need "IncludeNullValuesInDictionaries = true" to include null values
            JsConfig.IncludeNullValuesInDictionaries = true;


            var corsWhitelist = AppSettings.GetList("cors.whitelist.urls");

            //To automatically wired up for you on all HTTP Verbs (GET, POST, etc) 
            //And built-in endpoints, i.e. DeviceConfigValues, XML, JSV, HTML, CSV, SOAP
            Plugins.Add(new CorsFeature(
                allowOriginWhitelist: corsWhitelist,
                allowCredentials: true,
                allowedHeaders: "Content-Type, Allow, Authorization,UserId,CompanyId"));

            //To add registration feature
            Plugins.Add(new RegistrationFeature());

            //To add validation feature
            Plugins.Add(new ValidationFeature());
            container.RegisterValidators(
                typeof(InsertCompanyValidator).Assembly,
                typeof(UpdateCompanyValidator).Assembly,
                typeof(DeleteCompanyValidator).Assembly,

                typeof(InsertDeviceTypeValidator).Assembly,
                typeof(UpdateDeviceTypeValidator).Assembly,
                typeof(DeleteDeviceTypeValidator).Assembly,

                typeof(InsertLocationValidator).Assembly,
                typeof(UpdateLocationValidator).Assembly,
                typeof(DeleteLocationValidator).Assembly,

                //typeof(InsertRolePermissionValidator).Assembly,
                //typeof(UpdateRolePermissionValidator).Assembly,

                //Page Validator
                typeof(AddSecPageValidator).Assembly,
                typeof(UpdateSecPageValidator).Assembly,
                typeof(DeleteSecPageValidator).Assembly,

                //Page Permission Validator
                typeof(AddPagePermissionValidator).Assembly,
                typeof(UpdatePagePermissionValidator).Assembly,

                //SecGroup Validator
                typeof(AddSecGroupValidator).Assembly,
                typeof(UpdateSecGroupValidator).Assembly,
                typeof(DeleteSecGroupValidator).Assembly,

                //GroupRole Validator
                typeof(AddGroupRoleValidator).Assembly,
                typeof(UpdateGroupRoleValidator).Assembly,
                typeof(DeleteGroupRoleValidator).Assembly,

                //UserGroup Validator
                typeof(AddUserGroupValidator).Assembly,
                typeof(UpdateUserGroupValidator).Assembly,
                typeof(DeleteUserGroupValidator).Assembly,

                //GroupCompany Validator
                typeof(AddGroupCompanyValidator).Assembly,
                typeof(UpdateGroupCompanyValidator).Assembly,
                typeof(DeleteGroupCompanyValidator).Assembly,

                //Document Validator
                typeof(AddDocumentValidator).Assembly,
                typeof(UpdateDocumentValidator).Assembly,
                typeof(DeleteDocumentValidator).Assembly,

                //DocumentType Validator
                typeof(AddDocumentTypeValidator).Assembly,
                typeof(UpdateDocumentValidator).Assembly,
                typeof(DeleteDocumentValidator).Assembly,

                 // IoSetup Validator
                 typeof(DeviceIOSetupLocalDigitalInputAddValidator).Assembly,
                 typeof(DeviceIOSetupRemoteDigitalInputAddValidator).Assembly,
                 typeof(DeviceIOSetupExpansionDigitalInputAddValidator).Assembly,
                 typeof(DeviceIOSetupLocalRelayAddValidator).Assembly,
                 typeof(DeviceIOSetupRemoteRelayAddValidator).Assembly,
                 typeof(DeviceIOSetupExpansionRelayAddValidator).Assembly,
                 typeof(DeviceIOSetupRemoteAnalogOutputAddValidator).Assembly,
                 typeof(DeviceIOSetupLocalAnalogInputAddValidator).Assembly,
                 typeof(DeviceIOSetupRemoteAnalogInputAddValidator).Assembly,
                 typeof(DeviceIOSetupExpansionAnalogInputAddValidator).Assembly,
                 typeof(DeviceIOSetupLocalDigitalIOAddValidator).Assembly,
                 typeof(DeviceIOSetupRemoteDigitalIOAddValidator).Assembly,
                 typeof(DeviceIOSetupLocalOneWireAddValidator).Assembly,
                 typeof(DeviceIOSetupRemoteOneWireAddValidator).Assembly,
                 typeof(DeviceIOSetupRemoteThermocoupleAddValidator).Assembly,
                 typeof(DeviceIOSetupExpansionThermocoupleAddValidator).Assembly,
                 typeof(DeviceIOSetupLocalRegisterAddValidator).Assembly,
                 typeof(DeviceIOSetupRemoteRegisterAddValidator).Assembly,
                 typeof(DeviceIOSetupLocalVinAddValidator).Assembly,
                 typeof(DeviceIOSetupRemoteVinAddValidator).Assembly,
                 typeof(DeviceIOSetupLocalTimerAddValidator).Assembly,
                 typeof(DeviceIOSetupRemoteBatteryAddValidator).Assembly,
                 typeof(DeviceIOSetupLocalFrequencyInputAddValidator).Assembly,
                 typeof(DeviceIOSetupRemoteFrequencyInputAddValidator).Assembly
            );

            Plugins.Add(new AuthFeature(() => new CustomUserSession(),
                new IAuthProvider[]
                {
                    //new BasicAuthProvider(),                    //Sign-in with HTTP Basic Auth
                    new JwtAuthProvider(AppSettings) {
                        //HashAlgorithm = "HM256",
                        //PrivateKey = privateKey.ExportParameters(true),
                        AuthKeyBase64 = AppSettings.GetString("jwt.auth.key"),
                        RequireSecureConnection = false,
                        InvalidateTokensIssuedBefore = DateTime.Now,
                        ExpireTokensIn = TimeSpan.FromHours(24)
                        //Turn on for Prod: EncryptPayload = true
                        }, //JWT TOKENS
                    new CredentialsAuthProvider(AppSettings)
                })
            {
                HtmlRedirect = "/",
                //IncludeRegistrationService = true,
            });

            //Permit modern browsers (e.g. Firefox) to allow sending of any HTTP Method
            //SetConfig(new HostConfig
            //{
            //    GlobalResponseHeaders = {
            //        { "Access-Control-Allow-Origin", "*" },
            //        { "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" },
            //        { "Access-Control-Allow-Headers", "Content-Type" },
            //    },
            //});


            //AutoQuery
            Plugins.Add(new AutoQueryFeature { MaxLimit = 100000 });
            //Cache
            container.Register<ICacheClient>(new MemoryCacheClient());

            container.Register<IAuthRepository>(c =>
                new MyOrmLiteAuthRepository(c.Resolve<IDbConnectionFactory>())
                {
                    UseDistinctRoleTables = AppSettings.Get("UseDistinctRoleTables", true),
                });
            OrmLiteConfig.BeforeExecFilter = dbCmd => Debug.WriteLine(dbCmd.GetDebugString());

            bool ShouldWipeAndReloadDb = false;
            var environmentVariable = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

            if (environmentVariable == "LocalMemory" || environmentVariable == "LocalSQLServer")
            {
                ShouldWipeAndReloadDb = true;
                //Init auth tables
                container.Resolve<IAuthRepository>().InitSchema();
            }
            var authRepo = (MyOrmLiteAuthRepository)container.Resolve<IAuthRepository>();

            //Wipe and reload if using in memory SQL
            if (ShouldWipeAndReloadDb)
            {
                DatabaseInitService dis = new DatabaseInitService();
                dis.ResetDatabase();
                SessionService.ResetUsers(authRepo);
                dis.InitializeTablesAndData();
            }
        }
    }
}

public class CustomUserSession : AuthUserSession
{
    [DataMember]
    public string CustomName { get; set; }

    [DataMember]
    public string CustomInfo { get; set; }

}

共有1个答案

蓬意致
2023-03-14

只有在JWT令牌的发行日期早于您配置为:

InvalidateTokensIssuedBefore = DateTime.Now,

每当应用程序域重新启动时,您不太可能希望使令牌无效,这类似于从未拥有持久身份验证密钥(即,仅使用瞬态AesUtils.CreateKey()),因为在应用程序域重新启动/恢复之间创建的任何JWT都会自动无效。

 类似资料:
  • null null 问题-需要输入如何使此令牌无效或过期?或者有没有其他方法可以解决这个问题呢?

  • 我正在尝试在API网关(Apache APISIX)后面使用KeyClope。 我使用minikube来运行KeyClope和API网关。 网关正常工作,KeyClope也正常工作: 使用KeyClope,我可以使用不同的endpoint(使用发现endpoint(http://127.0.0.1:7070/auth/realms/myrealm/.well-已知/uma2配置),询问访问令牌并进

  • 我在调用rest api时尝试使用承载令牌时遇到一些问题。 我尝试了两种方法,结果相同: 我在azure门户中创建了一个应用注册,并授予它使用devops api进行用户模拟的权限。 我在中创建了一个应用程序https://app.vsaex.visualstudio.com/并授予it项目/团队管理权限。 对于我的代码,我使用了这个(当我使用PAT进行身份验证时有效) 我使用以下示例获取令牌:h

  • 我正在使用改型2.0在Android上构建一个Bitbucket REST客户端。 就我而言,OAuth2.0提供了“隐式授权”,当用户在提示下登录到他们的帐户时,它立即向客户机提供访问承载令牌。 承载令牌是可用于访问受保护资源的令牌。任何拥有承载令牌的人与其他拥有承载令牌的人一样,都有权访问受保护的资源。(根据IETF的这份文件) 如果我错了,请纠正我,但我认为使用隐式授权,在用户登录到他们的B

  • 如何使用Live PayPal ClientID和密钥从PayPal https://api-M.PayPal.com/v1/oauth2/Token API调用中获得访问/承载令牌。 我在调用Postman中的API之前使用了下面的设置 基本Auth类型。主体tab=x-www-form-urlencoded。grant_type=client_credentials 我得到以下响应时调用以上A