c# - keycloak 不适用于 asp.net MVC5 web 应用程序 (C#)

标签 c# asp.net-mvc-5 keycloak

我正在尝试将我的 MVC5 Web 应用程序与 Keycloak 服务器 v1.98 连接起来。它是连接的。当我访问我的 Web 应用程序时,Keycloak 需要输入凭据,当我输入时,出现以下异常:

我的配置(startup.cs):

public void Configuration(IAppBuilder app)
    {
        const string persistentAuthType = "WebApplication1_cookie_auth";

        // --- Cookie Authentication Middleware - Persists user sessions between requests
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = persistentAuthType
        });
        app.SetDefaultSignInAsAuthenticationType(persistentAuthType); // Cookie is primary session store

        // --- Keycloak Authentication Middleware - Connects to central Keycloak database
        app.UseKeycloakAuthentication(new KeycloakAuthenticationOptions
        {
            // App-Specific Settings
            ClientId = "dotnettest", // *Required*

            VirtualDirectory = "", // Set this if you use a virtual directory when deploying to IIS

            // Instance-Specific Settings
            Realm = "dotnettest", // Don't change this unless told to do so
            KeycloakUrl = "http://127.0.0.1:9090/auth", // Enter your Keycloak URL here

            // Template-Specific Settings
            SignInAsAuthenticationType = persistentAuthType, // Sets the above cookie with the Keycloak data
            AuthenticationType = "WebApplication1_keycloak_auth", // Unique identifier for the auth middleware
            ClientSecret = "187a2ba7-91f9-479f-a290-2b249a64236a"
        });
    }

异常详情:

System.Exception: Both the access token and the refresh token have expired

堆栈跟踪:

[Exception: Both the access token and the refresh token have expired]
   KeycloakIdentityModel.<GetClaimsAsync>d__39.MoveNext() +708
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   KeycloakIdentityModel.<ToClaimsIdentityAsync>d__25.MoveNext() +156
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task) +11522180
   Owin.Security.Keycloak.Middleware.<InvokeAsync>d__1.MoveNext() +1066
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   Microsoft.Owin.Security.Infrastructure.<Invoke>d__0.MoveNext() +445
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.<RunApp>d__5.MoveNext() +187
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   Microsoft.Owin.Security.Infrastructure.<Invoke>d__0.MoveNext() +653
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.<RunApp>d__5.MoveNext() +187
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.<DoFinalWork>d__2.MoveNext() +185
   Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.StageAsyncResult.End(IAsyncResult ar) +69
   Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar) +64
   System.Web.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +380
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

我遵循了本教程:

https://github.com/dylanplecki/KeycloakOwinAuthentication/wiki/ASP.NET-MVC-Tutorial

谢谢。

最佳答案

通过将机器时区修改为(utc -1:00)解决,出现此问题是因为KeycloakOwinAuthentication项目中存在错误,并且该错误已报告给项目开发人员。

您可以通过编辑“KeycloakIdentity.cs”文件中的“GetClaimsAsync”方法来解决此问题,以比较 (UTC-1) 区域中的当前日期时间。

private async Task<IEnumerable<Claim>> GetClaimsAsync()
        {
            await _refreshLock.WaitAsync();
            try
            {
                // Check to update cached claims, but not if refresh token is missing (as in bearer mode)
                if ((_kcClaims == null || _accessToken.ValidTo <= DateTime.Now) && _refreshToken != null)
                {
                    var info = TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time");
                    DateTimeOffset localServerTime = DateTimeOffset.Now;
                    DateTimeOffset utc = localServerTime.ToUniversalTime();
                    // Validate refresh token expiration
                    if (_refreshToken.ValidTo <= utc.AddHours(-1))
                        throw new Exception("Both the access token and the refresh token have expired");
                    // Load new identity from token endpoint via refresh token
                    await RefreshIdentity(_refreshToken.RawData);
                }
                return GetCurrentClaims();
            }
            finally
            {
                _refreshLock.Release();
            }
        }

关于c# - keycloak 不适用于 asp.net MVC5 web 应用程序 (C#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37026875/

相关文章:

c# - 将来某个时间调用单个操作的最佳方式?

c# - 将 Samba 的 S-1-22-[12]-* SID 映射到名称中

javascript - Form.serialize() 似乎返回 null

keycloak - 仅向某些用户提供 Keycloak 中的 "Forgot Password"功能

c# - 多个 boolean 值的 GetHashCode

c# - 如何在打印 PDF 时设置打印机设置

javascript - 获取 MVC 模型数据并将其传递到 AngularJS Controller

asp.net - 从 MVC 3 迁移到 MVC 5 后,Razor 语法绑定(bind)属性不起作用

java - {{notification.header}} {{notification.message}} 在访问 Keycloak 管理控制台时加载

oauth-2.0 - Keycloak - 权限和策略仅在使用“评估”选项卡时有效