Why page redirect to login Blazor WASM

Prathamesh Shende 376 Reputation points
2022-09-21T09:53:52.927+00:00

Every page is going to login first and after login success I can see other pages.

Please check my code -

App.razor

<CascadingAuthenticationState>
<Router AppAssembly="@typeof(App).Assembly">
<Found Context="routeData">
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
<FocusOnNavigate RouteData="@routeData" Selector="h1" />
</Found>
<NotFound>
<PageTitle>Not found</PageTitle>
<LayoutView Layout="@typeof(MainLayout)">
<p role="alert">Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
</CascadingAuthenticationState>

appSetting.json

"OIDC": {
"Authority": "https://localhost:44385",
"ClientId": "brekon",
"DefaultScopes": [
"openid",
"profile",
"email",
"api1"
],

"PostLogoutRedirectUri": "/authentication/logout-callback",  
"RedirectUri": "/authentication/login-callback",  
"ResponseType": "code"  

}

program.cs

builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme,
options =>
{
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.SignOutScheme = OpenIdConnectDefaults.AuthenticationScheme;
// Set Authority to setting in appsettings.json. This is the URL of the IdentityServer4
options.Authority = builder.Configuration["OIDC:Authority"];
// Set ClientId to setting in appsettings.json. This Client ID is set when registering the Blazor Server app in IdentityServer4
options.ClientId = builder.Configuration["OIDC:ClientId"];
// Set ClientSecret to setting in appsettings.json. The secret value is set from the Client > Basic tab in IdentityServer Admin UI
options.ClientSecret = builder.Configuration["OIDC:ClientSecret"];
//Login
options.CallbackPath = builder.Configuration["OIDC:RedirectUri"];
//Logout
options.SignedOutCallbackPath = builder.Configuration["OIDC:PostLogoutRedirectUri"];
// When set to code, the middleware will use PKCE protection
options.ResponseType = "code";
// Add request scopes. The scopes are set in the Client > Basic tab in IdentityServer Admin UI
options.Scope.Add("openid");
options.Scope.Add("profile");
options.Scope.Add("email");
options.Scope.Add("api1");
// Save access and refresh tokens to authentication cookie. the default is false
options.SaveTokens = true;
// It's recommended to always get claims from the
// UserInfoEndpoint during the flow.
options.GetClaimsFromUserInfoEndpoint = true;
options.TokenValidationParameters = new TokenValidationParameters
{
//map claim to name for display on the upper right corner after login. Can be name, email, etc.
NameClaimType = "email"
};

                    options.Events = new OpenIdConnectEvents  
                    {  
                        OnAccessDenied = context =>  
                        {  
                            context.HandleResponse();  
                            context.Response.Redirect("/");  
                            return Task.CompletedTask;  
                        }  
                    };  
                });  

builder.Services.AddAuthorization(options =>
{
// By default, all incoming requests will be authorized according to the default policy
options.FallbackPolicy = options.DefaultPolicy;
});
//builder.Services.AddHttpContextAccessor();
//builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

endregion

Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,403 questions
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 56,931 Reputation points
    2022-09-21T21:55:36.28+00:00

    a browser or WASM can not call oauth directly. it needs a server to do this. it redirects to the server passing the return url (which will reload the blazor app after authentication is done). you appear to an asp.net core webapi hosting the blazor.

    https://localhost:44382/authentication/login?returnUrl=https%3A%2F%2Flocalhost%3A44382%2Ffetchdata

    this is how the blazor app asks the webapi to login. the /authentication/login page should generate oauth server url and redirect to the oauth server. then oauth server after login will redirect back to the oauth callback, which in return will redirect back to the reload the razor app, and blazor will render the /fetchdata page.

    note: before oauth security was tightened spa apps would open an iframe to host the login, and this will happen with some systems. but more often the spa application has to redirect to oauth server and redirect back.

    if you want the blazor to directly call the oauth server, use the MSAL library to get an access token.

    https://learn.microsoft.com/en-us/aspnet/core/blazor/security/webassembly/standalone-with-azure-active-directory?view=aspnetcore-6.0

    0 comments No comments

0 additional answers

Sort by: Most helpful