Blazor Server Authentication with Identity Server 4

Prathamesh Shende 441 Reputation points
2022-09-15T19:10:10.12+00:00

I have created the project in Identity Server 4 which is on localhost:5001
and my blazor server is on localhost:5002. So when I hit the secure page blazor server project It should be redirect to 5001 to authenticate(login) and get back with the access code and token

I also add clientId and every in IS4 project but setting for blazor server im not getting what to add in program.cs.

"oidc": {
"Authority": "https://localhost:5001",
"ClientId": "innovustech",
"DefaultScopes": [
"openid",
"profile",
"email",
"api1"
],
"PostLogoutRedirectUri": "authentication/logout-callback",
"RedirectUri": "authentication/login-callback",
"ResponseType": "code"
}

this is in appsetting.json

Please help

Developer technologies | .NET | Blazor
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Chen Li - MSFT 1,231 Reputation points
    2022-09-16T07:33:52.79+00:00

    Hi @Prathamesh Shende ,

    If your path is correct and you are sure to pass validation, you can use OpenIdConnect.
    Program.cs:

    var builder = WebApplication.CreateBuilder(args);  
      
    builder.Services.AddHttpClient();  
      
    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("roles");  
                            // 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 = "name"  
                            };  
      
                            options.Events = new OpenIdConnectEvents  
                            {  
                                OnAccessDenied = context =>  
                                {  
                                    context.HandleResponse();  
                                    context.Response.Redirect("/");  
                                    return Task.CompletedTask;  
                                }  
                            };  
                        });  
      
      
    builder.Services.AddControllersWithViews()  
        .AddMicrosoftIdentityUI();  
      
    builder.Services.AddAuthorization(options =>  
    {  
        // By default, all incoming requests will be authorized according to the default policy  
        options.FallbackPolicy = options.DefaultPolicy;  
    });  
      
    builder.Services.AddRazorPages();  
    builder.Services.AddServerSideBlazor()  
        .AddMicrosoftIdentityConsentHandler();  
    builder.Services.AddSingleton<WeatherForecastService>();  
      
    var app = builder.Build();  
      
    // Configure the HTTP request pipeline.  
    if (!app.Environment.IsDevelopment())  
    {  
        app.UseExceptionHandler("/Error");  
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.  
        app.UseHsts();  
    }  
      
    app.UseHttpsRedirection();  
      
    app.UseStaticFiles();  
      
    app.UseRouting();  
      
    app.UseAuthentication();  
    app.UseAuthorization();  
      
    app.MapControllers();  
    app.MapBlazorHub();  
    app.MapFallbackToPage("/_Host");  
      
    app.Run();  
    

    Here is a complete example you can refer to:

    1. workcontrolgit/TokenProject.AdminUI — this is a repository of IdentityServer4 Admin UI written in C#. The Visual Studio solution consists of three web projects: Admin UI, Admin API, and IdentityServer4.
    2. workcontrolgit/BlazorServerId4 — this repo contains a Blazor server application pre-configured with Microsoft.AspNetCore.Authentication.OpenIdConnect library to login to IdentityServer4. The app provides login/logout features.

    Hope this can help you.


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our  documentation  to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best Regards,
    Chen Li

    0 comments No comments

  2. Prathamesh Shende 441 Reputation points
    2022-09-16T12:11:10.237+00:00

    It's thanks.
    but there is small problem.
    when I visit website it will direct redirect me to auth website login
    i just want to be specified page to be authorize not every.

    this app.razor

    ----------

    <CascadingAuthenticationState>
    <Router AppAssembly="@typeof(Program).Assembly">
    <Found Context="routeData">
    <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(ProfileLayout)">
    <Authorizing>

                    <div class="d-flex align-items-center justify-content-center flex-column vh-100">  
                        <div class="spinner-border" role="status">  
                            <span class="sr-only">Loading..</span>  
                        </div>  
                        <p class="text-center mt-2">Authorizing</p>  
                    </div>  
                    <FocusOnNavigate RouteData="@routeData" Selector="h1" />  
                </Authorizing>  
                <NotAuthorized>  
                    <RedirectToLogin />  
                    @*//@if (!context.User.Identity.IsAuthenticated)  
                    {  
                    }  
                    else  
                    {  
                    <p>You are not authorized to access this resource.</p>  
                    }*@  
                </NotAuthorized>  
            </AuthorizeRouteView>  
        </Found>  
        <NotFound>  
            <LayoutView Layout="@typeof(ProfileLayout)">  
                  
               nothing 404  
            </LayoutView>  
        </NotFound>  
    </Router>  
    

    </CascadingAuthenticationState>
    Also I dont see logged in user name/email

    I call it as context.User.Identity.Name nothing showup also I tried it by calling IHttpContextAccessor nothing happened.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.