How to throw a valid usefule message when security token expires. RRS feed

  • Question

  • User585649674 posted

    I am using Owin authentication with JWT tokens. My application is webapi, with ui in angularJs. Right now, when the token expires I get 401, unauthorized. I am showing the message "Un authorized" from status code to user and log him out. The new requirement is to show the message "User session expired". I searched google for 3 hours could not  find solution.

    My code is as below 

    OAuthAuthorizationServerOptions oauthOptions = new OAuthAuthorizationServerOptions
                    AllowInsecureHttp = true,
                    TokenEndpointPath = new PathString("/oauth2/token"),
                    AccessTokenExpireTimeSpan = TimeSpan.FromHours(0.5),
                    Provider = new CustomAuthProvider(),
                    AccessTokenFormat = new CustomJWTFormat(),
                    RefreshTokenProvider = new RefreshTokenProvider(AdminManager) 
                    new JwtBearerAuthenticationOptions
                        AuthenticationMode = AuthenticationMode.Active,
                        AllowedAudiences = new[] { audience },
                        IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                            new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
                        TokenHandler=new CustomTokenHandler()
    // custom token handler
    public class CustomTokenHandler : JwtSecurityTokenHandler
            protected override void ValidateLifetime(DateTime? notBefore, DateTime? expires, SecurityToken securityToken, TokenValidationParameters validationParameters)
                    base.ValidateLifetime(notBefore, expires, securityToken, validationParameters);
                catch (SecurityTokenExpiredException ex)
                    //IOwinResponse response = new OwinResponse();
                    //response.StatusCode = 500;
                    //response.Write("session expired");
                    //return response;
                    //throw new DomainException(HttpStatusCode.Forbidden, "Session has expired. Please log in again.");
                    //return HttpRequestMessage
                    //return new HttpRequestHeader(HttpStatusCode.OK);

    Monday, March 14, 2016 2:03 PM