-
Notifications
You must be signed in to change notification settings - Fork 597
Auth 2.0 Part II: Revenge of AuthZ #1190
Comments
Hello, I've been reading the threads from aspnet/Announcements#232 I have a question, let's say I have an authentication setup like below: app.UseWhen(context => context.Request.Path.Value.StartsWith("/api", StringComparison.OrdinalIgnoreCase), builder =>
{
builder.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationScheme = AuthService.CookieAuthenticationScheme,
AutomaticAuthenticate = true,
AutomaticChallenge = false,
LoginPath = null,
LogoutPath = null,
AccessDeniedPath = null
});
});
app.UseWhen(context => context.Request.Path.Value.StartsWith("/api", StringComparison.OrdinalIgnoreCase) == false, builder =>
{
builder.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationScheme = AuthService.CookieAuthenticationScheme,
AutomaticAuthenticate = true,
AutomaticChallenge = true,
LoginPath = "/auth/login",
LogoutPath = "/auth/logout",
AccessDeniedPath = "/home/denied",
});
}); The goal of above code is to prevent API-type endpoints (that returns JSON) to redirect user to login page when authentication fails. (Instead just return 401 Unauthorized or 403 Forbidden) How can I do this using the new authentication middleware? Thank you for advice, in advance. |
@ryanelian The Policy recommendations in #1062 still work for your scenario. |
I just read that link. I don't understand. If I'm not mistaken, I'm supposed to put a policy in my Authorize attributes so it takes effect, like:
Can you please provide code sample specifically for the above case, please? |
You can't do that anymore, each scheme is now unique, and since they are no longer middleware you can't branch your app to use the same logical scheme for different middleware. You will need to setup two schemes, "Api", "Cookies" |
I have a mixed feeling about this. I feel that the change unnecessarily complicates the development. The service-based authentication feels like 10 steps backward to me, idk. There should be a simple way to define the default scheme used for controllers by route / request / context condition... But okay, let's say I can just explicitly tell the API Controller to use |
If there was a way to specify services per route/request/context that would just work, but there isn't today... I'm not sure what you are asking about with the cookie name, but you can keep using the cookies as the DefaultAuthenticateScheme for your non API requests, if your API controller is going to explicitly ask for the API. |
There was, it was called Middleware with I mean, look. I don't mind changing the authentication in my applications into Services but aren't we losing a crucial feature here?
Let's say in 1.1, I make a cookie authentication scheme called Apparently ASP.NET will make a cookie for that scheme named Now you're advising me to make 2 separate authentication schemes, 1 = cookie for UI, 1 = cookie for API. Let's say I do that,
However, the cookie for the schemes will be different, no?
Thus the question, can I use two different cookie authentication schemes, but targets the same cookie key / store / name? |
I don't think there should be any issues targeting the same cookie name with different schemes, you might have to make sure to configure the TicketFormat for both schemes to be the same if you are going to read the same cookie in either scheme. |
Awesome. So setting the same Sorry, I haven't heard about TicketFormat before. I saw https://docs.microsoft.com/en-us/aspnet/core/security/data-protection/compatibility/cookie-sharing but I don't really get what I am supposed to configure. Mind providing code sample for this? Thanks again. |
Just CookieName should be enough. That said, with AutomaticAuthenticate and AutomaticChallenge removed from CookieAuthOptions, why do you still need two auth middleware? Nulling out the paths has never had any effect. |
Oh did they in 1.1? TIL. I thought if you don't set them as false / nulled out , they'll kick you to login / access denied path, which is not preferable for API-type Controllers. (You'd want instead just a status code response indicating that the request is unauthorized / forbidden) I don't know, I've been using that technique since forever, never noticed if they don't have any effects anymore or something. |
No, that behavior was caused by AutomaticChallenge = false, the middleware was being bypassed for challenges. Null paths were always set to defaults by the middleware. I suspect that 401 status code was being set by the IISIntegration middleware, which always assumed windows auth was enabled (AutomaticChallenge = true). This is going away soon: aspnet/IISIntegration#371. A different approach that would still work (without two middleware) is to use the events to control the behavior: Security/src/Microsoft.AspNetCore.Authentication.Cookies/Events/CookieAuthenticationEvents.cs Line 43 in 1f5a27e
|
public Func<CookieRedirectContext, Task> OnRedirectToLogin { get; set; } = context =>
{
if (IsAjaxRequest(context.Request))
{
context.Response.Headers["Location"] = context.RedirectUri;
context.Response.StatusCode = 401;
}
else
{
context.Response.Redirect(context.RedirectUri);
}
return TaskCache.CompletedTask;
}; Ohhh yesss, that's what I'm talking about. 👍 🌶 🔥
EDIT: Oh I just remembered that header Thank you for solution, I guess. At least I know it's possible. Or I'll just stop caring altogether about API controllers redirecting on authorization failure... |
The Location header does not trigger redirects, the status code does. |
Oh okay. So to recap, the new cookie authentication scheme will not redirect when it's AJAX request, by default, but instead returns 401 when not authenticated, or 403 when access denied. Am I understanding that correctly? Alrighty then, thank you guys. Great job over there, keep it up. 👍 |
Note 1.0 behaved the same way. |
Huh... Now that's curious. I wonder why I did that in the first place then. I vaguely remembered long ago that it bounced me to other page when my Angular service hits an unauthorized / access denied controller. Oh well. Thanks for info. |
Sequel to: #1179
Authentication:
Host Wave PRs:
Cleanup PRs/Issues:
Issues:
Authorization: #1193
The text was updated successfully, but these errors were encountered: