keycloak 不适用于 asp.net MVC5 网络应用程序 (C#)

keycloak doesn't work with asp.net MVC5 web app (C#)

我正在尝试将我的 MVC5 Web 应用程序与 Keycloak 服务器 v1.98 连接起来。它是连接的。当我访问我的网络应用程序时,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();
            }
        }