-
Notifications
You must be signed in to change notification settings - Fork 10.3k
Blazor Authorization Should Redirect to Challenge When Default Challenge Scheme is Set #13709
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Thanks for contacting us, @ryanelian. |
Thank you for the confirmation. Can we have the redirect just so the app behaves like any other ASP.NET MVC web app? Our customers love (cough demand cough) the ASP.NET MVC redirect URI behavior / feature whenever an unauthorized user access a random page. (e.g. It'll be a hard sell to our customers if Blazor cannot do that... Please add a last-minute addition to Blazor for this specific feature? I know you guys are going GA at the end of September, but I would highly value this feature being available without waiting for version 3.1.0 |
This scenario can be accomplished by first defining a @inject NavigationManager Navigation
@code {
protected override void OnInitialized()
{
Navigation.NavigateTo("Identity/Account/Login", true);
}
} and then use <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
<NotAuthorized>
<RedirectToLogin />
</NotAuthorized>
</AuthorizeRouteView> |
Amazing. Thank you. This should probably do the trick... // I'm not sure the redirectUri here is secure, but whatever, it works. // razor page login page
public class LoginModel : PageModel
{
public async Task OnGet(string redirectUri)
{
await HttpContext.ChallengeAsync(new AuthenticationProperties
{
RedirectUri = redirectUri
});
}
}
// razor page logout page
public class LogoutModel : PageModel
{
public async Task<IActionResult> OnGet()
{
await HttpContext.SignOutAsync();
return Redirect("/");
}
}
// blazor component redirect to login WHEN NOT authenticated
@inject NavigationManager Navigation
@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor ctx
@code {
protected override void OnInitialized()
{
if (ctx.HttpContext.User.Identity.IsAuthenticated == false)
{
var challengeUri = "/login?redirectUri=" + System.Net.WebUtility.UrlEncode(Navigation.Uri);
Navigation.NavigateTo(challengeUri, true);
}
}
}
<p>
You are not authorized to access this page.
</p>
// app razor
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
<NotAuthorized>
<Challenge></Challenge>
</NotAuthorized>
</AuthorizeRouteView> Although, I still insist that this feature is critical, and must be in the base framework without requiring developers to write that on our own. |
This issue still seems to be present in the RTM release. I am authenticating with AzureAD so when I add the following to my Blazor page I am expecting it to automatically challenge, it is not.
Do I need to do something else for this to work? |
@daver77 You need to follow @danroth27 suggestion, Blazor apps follow a different model than traditional web pages and performing a traditional ASP.NET Core challenge is not possible. As an alternative, add an additional endpoint, redirect the user there as @danroth27 suggests. perform the challenge from there and redirect back to the blazor app at the end of the login flow. |
You should do validation over that redirect uri to ensure its local, otherwise you are opening yourself to open redirect attacks. |
@javiercn thanks, that may be a work-around but the fact is that the Authorize attribute does not work. |
@daver77 That is not the case. The Authorize attribute is just metadata that each framework decides how to interpret. Performing a challenge is just the most common behavior, but it is not a prescriptive one. |
I think the issue is that Blazor simply doesn't interpret the behavior as expected. I just started porting a bunch of our apps over and ran into this myself and was pretty surprised that it did not follow the same behavior we see in controllers and razor pages. Not a big deal to resolve it, but the documentation should be updated at the very least with the information on how to make it work generically. |
Hi Dan, I tried your suggestion, but it doesn't work, there is nothing happen when I come to an authorized page. Seems like "NotAuthorized" only displays content instead of a component. Thanks. |
I appreciate the workaround shown by @danroth27 and @ryanelian but seen from a .NET Core enthusiast we really need Also, it seems that |
@quoctuancqt You need to add a "using" statement to wherever you added the If you added it to a folder called
|
The solution above will result in an "Microsoft.AspNetCore.Components.NavigationException" because you are disrupting the page build process. |
Not sure if people are aware, you can use this Razor Page method to secure Blazor Pages |
But this isn't relevant to Blazor webassembly: those razor page options aren't available as methods on the WebAssemblyHostBuilder.Services property. However, it's difficult to ascertain whether or not the original question is regarding Blazor webassembly or not. I'm also encountering the same issue with the AuthroiseRouteView not redirecting, 'NotAuthorized' requests to my custom login component. |
Putting this code
in the However, putting that same code in a razor component such as
I would have expected a redirect in either case. |
I am not a very experienced webdeveloper but it seems to me that the [Authorize] attribute not directly redirecting to the login page, is far more flexible because you can decide what happens when the user tries to access a page that requires authentication. Alternate content that explains the problem and offers a login button is far more user-friendly than redirect and gives the user an option to bail out and select non-authorized content instead of beeing confronted with a login dialog. The solution as described here ( the razor page as model in _host.cshtml ) combined with both the component and maybe some manual login / logout links on the top navbar is far more flexible. I've been busy with this problem for about 3 days now and the solution here is workable and flexible because it does not affect the authorization strategy of Blazor. |
Hi, I'm trying to make my app available only for logged in users. I set App.razor: < CascadingAuthenticationState> < AuthorizeView> < Authorized> < Router AppAssembly="@typeof(Program).Assembly"> < Found Context="routeData"> < AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" /> < /Found> < NotFound> < LayoutView Layout="@typeof(MainLayout)"> < p>Sorry, there's nothing at this address.< /p> < /LayoutView> < /NotFound> < /Router> < /Authorized> < NotAuthorized> < RedirectToLogin/> < /NotAuthorized> < /AuthorizeView> < /CascadingAuthenticationState> When I click Continue application is redirected to login page. So it's working ok except this exception. I'm doing something wrong ? |
As far as i can see, the error is in the app.razor. You are using the Navigation Manager to navigate to the login page but for that to work, routing should be initialized... The problem is in the fact that you have the Routing initialization within an AuthorizeView which, of which the NotAuthorized section is triggered directly... before routing is initialized... So, you should remove the AuthorizeView from the app.razor. Another thing is that, if you use Role authorization, the application will check that if you reach a section that has an authorization attribute. If you are logged in, but not authorized for a section, the current implementation of the RedirecToLogin component will end up in a loop logging you in. A way to resolve this is to create a check inside the RedirecToLogin component in order to determine if the user is currently logged in. A redirection is not necessary in that case. Also, if you want to secure your entire (hosted) application, you should configure it in the or Startup.cs and modify:
Anybody who thinks this reaction sucks, please correct me... |
Sorry, my fail
services.AddMvc(config =>
{
//only allow authenticated users
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
});
Regards,
Evert
Verzonden vanuit Mail voor Windows 10
Van: Tom Thunderforest
Verzonden: woensdag 6 mei 2020 07:42
Aan: dotnet/aspnetcore
CC: everttimmer; Comment
Onderwerp: Re: [dotnet/aspnetcore] Blazor Authorization Should Redirect toChallenge When Default Challenge Scheme is Set (#13709)
Adding RequireAuthorization() didn't do nothing :/ You can see index page without log in.
—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub, or unsubscribe.
|
@TomaszGrzmilas I think the NavigationException you are getting is normal - that's how the NavigationManager aborts the operation when Navigating to another view. You would only see it in debug, and you can select the VS option to not break on such navigation exceptions. If you want to implement the login view also as a Blazor component, rather than a razor page, for consistent look and feel, then you can use the SignInManager from the Xomega.Framework.Blazor package to do the Challenge for the login redirect, as well as SignIn and SignOut. Here is the full explanation of how it works with references to the appropriate code: #19148 (comment) |
Thanks to this post, I was able to achieve forcing the user to log in, after the MainLayout.razor has been loaded, which was not my desired behaviour. I was able to overcome this with the help of a couple SO answers.
This will immedietaly redirect to RedirectToLogin.razor, which then redirects to Authentication.razor. This component tries to render the layout, which creates an infinite loop. To overcome that behaviour, you can create a seperate component redirecting to your Log In page, or change the Authentication.razor component, which I will show here.
|
When use you My Code if Authorized&NotAuthorized work App.razor
RedirectToLogin .razor
|
So what's the official solution for webassembly and third party authentication? I'm trying these various workaround, seems to getting infinite loop or not working. |
@imtrobin Take a look at https://docs.microsoft.com/aspnet/core/blazor/security/webassembly/standalone-with-authentication-library and see if it helps. |
Thanks dan, it's close what I have pieced together over the internet but it's really not situation. I'm not using ODIC, it's a custom authentication library with jwtoken/refresh tokens. I used this which gets me closer , but it's missing quite a few bits. |
Thank you for contacting us. Due to a lack of activity on this discussion issue we're closing it in an effort to keep our backlog clean. If you believe there is a concern related to the ASP.NET Core framework, which hasn't been addressed yet, please file a new issue. This issue will be locked after 30 more days of inactivity. If you still wish to discuss this subject after then, please create a new issue! |
If you believe you have an issue that affects the security of the platform please do NOT create an issue and instead email your issue details to [email protected]. Your report may be eligible for our bug bounty but ONLY if it is reported through email.
Describe the bug
I expected using
@attribute [Authorize]
to bounce me to my OpenID Connect login page, but instead it displays "Not Authorized" message.To Reproduce
Steps to reproduce the behavior:
3.0.0-preview9.19424.4
Startup.cs - ConfigureServices
Startup.cs - Configure
Index.Razor
App.Razor
Expected behavior
I should get redirected using my default challenge scheme
Screenshots
Additional context
Add any other context about the problem here.
Include the output of
dotnet --info
Following tutorial from:
The text was updated successfully, but these errors were encountered: