简体   繁体   中英

How to always return login/sign in view when I'm unauthorized in asp.net core mvc?

I've a problem with the implementation of the functionality which always returns view to sign in when I'm unauthorized. My project is created in ASP.NET CORE MVC 3.1 with JWT Bearer. I can sign in when I go to the view Login.cshtml directly (after click Sign In), and then my methods with [Autorize] attribute working fine. I'd like to always return view to sign in, when I go to the method with [Authorize] attribute.

I've found some examples with cookie which return sign in view, but I'm using JWT Bearer with Session and I don't know it's necessary. Thank's in advance for help.

Finnally I found way which working in .NET Core 3.1. This code redirect to login/signIn page when status code is 401 - unauthorized.

app.UseStatusCodePages(async context => {
   var request = context.HttpContext.Request;
   var response = context.HttpContext.Response;

   if (response.StatusCode == (int)HttpStatusCode.Unauthorized)
   {
    response.Redirect("/Home/Login?returnUrl=" + request.Path);
   }

});

Whenever you call an API with authorize attribute, if the bearer token is expired you must be returning 401 - Unauthorized error code to the caller. As soon as you get a 401 error code, you can redirect to sign-in page with your frontend logic only.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM