public void ConfigureOAuth(IServiceCollection services) { var tokenValidationParameters = new TokenValidationParameters { // The signing key must match! ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration["AppSettings:Auth:Secret"])), // Validate the JWT Issuer (iss) claim ValidateIssuer = true, ValidIssuer = Configuration["AppSettings:Auth:Issuer"], // Validate the JWT Audience (aud) claim ValidateAudience = true, ValidAudience = Configuration["AppSettings:Auth:Audience"], // Validate the token expiry ValidateLifetime = true, // If you want to allow a certain amount of clock drift, set that here: ClockSkew = TimeSpan.Zero }; services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = tokenValidationParameters; options.Events = new JwtBearerEvents() { OnAuthenticationFailed = (context) => { if (context.Exception is SecurityTokenExpiredException) { //set this state makes it works. I got 440 statuscode in Postman. //context.State = Microsoft.AspNetCore.Authentication.EventResultState.HandledResponse; context.NoResult(); context.Response.StatusCode = 498; context.Response.ContentType = "application/json"; var error = new AlpineCreateResponse().Error(498, "Access token has expired.", null, false); return(context.Response.WriteAsync(JsonConvert.SerializeObject(error))); } return(Task.FromResult(0)); } }; }); }
public override void OnException(ExceptionContext context) { Exception exception = context.Exception; string message = exception.Message; Exception ex = context.Exception; //Get Inner Most Exeption while (ex.InnerException != null) { ex = ex.InnerException; message = ex.Message; } var error = new AlpineCreateResponse().Error(( int )HttpStatusCode.BadRequest, "An error has occured.", message, false); if (exception is AlpineException) { error = new AlpineCreateResponse().Error(( int )HttpStatusCode.BadRequest, exception.Message, "", (exception is AlpineException)); } if (exception is UnauthorizedAccessException) { error.Meta.Code = ( int )HttpStatusCode.Unauthorized; context.HttpContext.Response.StatusCode = ( int )HttpStatusCode.Unauthorized; } else { context.HttpContext.Response.StatusCode = ( int )HttpStatusCode.BadRequest; } context.Result = new JsonResult(error); base.OnException(context); }