How to handle expired access token in asp.net core using refresh token with OpenId Connect

前端 未结 3 2058
情书的邮戳
情书的邮戳 2020-12-01 14:18

I have configured an ASOS OpenIdConnect Server using and an asp.net core mvc app that uses the \"Microsoft.AspNetCore.Authentication.OpenIdConnect\": \"1.0.0 and \"Microsoft

3条回答
  •  星月不相逢
    2020-12-01 15:19

    It seems there is no programming in the openidconnect authentication for asp.net core to manage the access_token on the server after received.

    I found that I can intercept the cookie validation event and check if the access token has expired. If so, make a manual HTTP call to the token endpoint with the grant_type=refresh_token.

    By calling context.ShouldRenew = true; this will cause the cookie to be updated and sent back to the client in the response.

    I have provided the basis of what I have done and will work to update this answer once all work as been resolved.

    app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AutomaticAuthenticate = true,
                AutomaticChallenge = true,
                AuthenticationScheme = "Cookies",
                ExpireTimeSpan = new TimeSpan(0, 0, 20),
                SlidingExpiration = false,
                CookieName = "WebAuth",
                Events = new CookieAuthenticationEvents()
                {
                    OnValidatePrincipal = context =>
                    {
                        if (context.Properties.Items.ContainsKey(".Token.expires_at"))
                        {
                            var expire = DateTime.Parse(context.Properties.Items[".Token.expires_at"]);
                            if (expire > DateTime.Now) //TODO:change to check expires in next 5 mintues.
                            {
                                logger.Warn($"Access token has expired, user: {context.HttpContext.User.Identity.Name}");
    
                                //TODO: send refresh token to ASOS. Update tokens in context.Properties.Items
                                //context.Properties.Items["Token.access_token"] = newToken;
                                context.ShouldRenew = true;
                            }
                        }
                        return Task.FromResult(0);
                    }
                }
            });
    

提交回复
热议问题