Reputation: 231
Trying to get my around the the exact differences in setting up the authorization middle-ware for a MVC backend versus an API backend.
My understanding (basic) is that a controller decorated with the [Authorize] attribute will invoke an authorization handler to verify the identity of the client, and then
1) In the MVC backend, and if fails not authenticated, would redirect to a default login page where the use would input their credentials etc.
2) IN the case of an API back, the controller would simply respond with 401 message (redirect would not make sense in an API and the client, a SPA for example would have to figure out what to do next)
I would like to ask what differences exist when setting up the app builder in the startup class since I suppose the functionality of the authorization middleware is different depending on each case (one case redirects, while the other does not).
P.S. I am aware that MVC case will generally be using a cookie, while the API case would be JWT but was wondering where the decision to redirect or not is handled / configured?
Upvotes: 1
Views: 302
Reputation: 27548
If adding authorization middleware to application using app.UseAuthorization()
, and apply Authorize
attribute on controller/action means the controller/action requires a signed in user , if user is not authenticated , the authentication schema will be challenged . There is no different logic in MVC and web api .
MVC will redirect is because you add the cookie authentication :
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie();
CookieAuthenticationDefaults.AuthenticationScheme
passed to AddAuthentication
sets the default authentication scheme for the app , so if user is not authenticated , cookie authentication is fired , and Account/Login
is the default login path of Cookie authentication , so user will be redirect to that url .
On web api side , you will redirect to same path if you add cookie authentication also , but usually Web API is a service and doesn't have any UI elements. So, features such as redirection URL don't apply to a Web API. Moreover, a Web API can be consumed by variety of clients including Single Page Applications (SPAs) and non-browser clients. So we usually use JWT bearer authentication . JWT bearer authentication will return 401 if user is not authenticated and it won't(and not make sense) to redirect in web api .
Upvotes: 1