danroth27 / BlazorWebAppApiCall

Blazor Web App that calls an API
MIT License
6 stars 0 forks source link

Auth integration #1

Open OrihuelaConde opened 10 months ago

OrihuelaConde commented 10 months ago

Thank you for the sample app. I am trying to integrate this solution with the template that has authentication, but I don't know how to ignore the "Router" in the case of accessing my API controllers. For example, if I am not authenticated it returns the login page, instead of the corresponding API status code (401) because of the component "RedirectToLogin ". This behaviour causes that httpClient.GetFromJsonAsync fail trying to parse the login page.

Here is the default "Router" of the template.

`

`

And here is a part of my Program.cs

image

Maybe, the solution is easy, but I am stuck on this problem.

danroth27 commented 9 months ago

For example, if I am not authenticated it returns the login page, instead of the corresponding API status code (401)

@OrihuelaConde It sounds like you might be hitting https://github.com/dotnet/aspnetcore/issues/9039 because you have a mix of authenticated web UI and APIs in the same app. Are the API endpoints you're trying to access the Identity Endpoints?

@JeremyLikness @halter73 FYI.

OrihuelaConde commented 9 months ago

@danroth27 Thank you for your reply. I tried the solution provided in "https://github.com/dotnet/aspnetcore/issues/9039#issuecomment-1483912271" and it worked. I adapted it to function with both a Blazor Web App (Auth) and an API Controller within the same application.

builder.Services.ConfigureApplicationCookie(options => {
    options.Events.OnRedirectToAccessDenied = context => {
        if (context.Request.Path.StartsWithSegments("/api"))
        {
            context.Response.StatusCode = 403;
            return Task.CompletedTask;
        }
        else
        {
            context.Response.Redirect(options.AccessDeniedPath);
            return Task.CompletedTask;
        }
    };
    options.Events.OnRedirectToLogin = context =>
    {
        if (context.Request.Path.StartsWithSegments("/api"))
        {
            context.Response.StatusCode = 401;
            return Task.CompletedTask;
        }
        else
        {
            context.Properties.RedirectUri = context.Request.Path + context.Request.QueryString;
            var redirectUri = context.Properties.RedirectUri;
            var queryString = new QueryString().Add(options.ReturnUrlParameter, redirectUri);
            var loginUrl = options.LoginPath + queryString;
            context.Response.Redirect(loginUrl);
            return Task.CompletedTask;
        }
    };
});