简体   繁体   中英

how to logout on blazor server side?

I have a problem with programming a logout in Blazor using HttpContextAccessor .

I tried to logout but it didn't do anything. What I want is just to delete some cookies in my browser and redirect to the hompage so I can and go to the login page again; I thought that by using the httpcontext signout I could automatically delete cookies because I'm logged out.

Here is the logout code:

      @page "/"
      @* @inject IJSRuntime JSRuntime *@
      @* @inherits FragmentNavigationBase *@
      @using System.Security.Claims
      @inject Microsoft.AspNetCore.Http.IHttpContextAccessor _httpContextAccessor
      @inject NavigationManager NavigationManager
      @using System;
      @using System.Threading.Tasks;
      @using Microsoft.AspNetCore.Authentication;
      @using Microsoft.AspNetCore.Authentication.Cookies;
      @inject Blazored.LocalStorage.ILocalStorageService localStorage



      <Layout>
          <div class="container">
              <Bar
        Breakpoint="Breakpoint.Desktop"
        Background="Background.Light"
        ThemeContrast="ThemeContrast.Light"
      >
        <div>
          Booking Crew
        </div>
        <BarToggler />
        <BarMenu>
          <BarStart>
            <BarItem>
              <BarLink To="">Home</BarLink>
            </BarItem>
            <BarItem>
              <BarDropdown>
                <BarDropdownToggle>Report</BarDropdownToggle>
                <BarDropdownMenu>
                  <BarDropdownItem><BarLink To="report_crews">Report Crew</BarLink></BarDropdownItem>
                  <BarDropdownItem><BarLink To="report_studio">Report Studio</BarLink></BarDropdownItem>
                  <BarDropdownItem><BarLink To="report_schedule">Report Schedule</BarLink></BarDropdownItem>
                </BarDropdownMenu>
              </BarDropdown>
            </BarItem>
          </BarStart>
        </BarMenu>
        Hai, @EmployeeName  <span style="cursor: pointer;" @onclick="OnLogOut"> Logout</span>
      </Bar>
          </div>
        
      </Layout>

      @code{
        public string EmployeeName {get;set;}
          public string Email {get;set;}
          public string Nik {get;set;}
          public string NikLama {get;set;}
          protected override void OnInitialized()
          {
              var name = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.Name).Value;
              name = name.ToString().ToLower();
              EmployeeName = name.Remove(1).ToUpper() + name.Substring(1);
              Email = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.Email).Value;
              Nik = _httpContextAccessor.HttpContext.User.FindFirst(c => c.Type == "urn:T7SSO:nik")?.Value;
              NikLama = _httpContextAccessor.HttpContext.User.FindFirst(c => c.Type == "urn:T7SSO:nik_lama")?.Value;
              var test = _httpContextAccessor.HttpContext.User.FindFirst(c => c.Type == "urn:T7SSO:nik")?.Value;;
              Console.WriteLine(test);
          }

          protected void OnLogOut()
          {
              _httpContextAccessor.HttpContext.SignOutAsync(
                      CookieAuthenticationDefaults.AuthenticationScheme);
              NavigationManager.NavigateTo("/");
          }

      }

I thought using signoutAsync was enough to sign the user out but, when I click on logout, nothing is happening. How can I solve that?

Blazor Server uses SignalR, which means after Startup.Configure has run its course, you can no longer safely access the HttpContext , ie from your component.

Additionally, again for security reasons, you must not use IHttpContextAccessor within Blazor apps. Blazor apps run outside of the context of the ASP.NET Core pipeline. The HttpContext isn't guaranteed to be available within the IHttpContextAccessor, nor is it guaranteed to be holding the context that started the Blazor app.

If you need to remove a cookie, navigate to a logout URL that can be handled by code where the HttpContext is valid, such as a Controller or Middleware.

If you just need simple logout functionality, use Middleware and to avoid adding calls to AddControllers and MapControllers . Here's an example using inline Middleware:

public void Configure(IApplicationBuilder app) {
    // ...
    app.Use(async (context, next) => {
    //             ^^^^^^^ the HttpContext
        if (context.Request.Path
                .Equals("/Logout", System.StringComparison.OrdinalIgnoreCase)) 
        {
            // Remove cookie, redirect to landing, and any other logout logic
        }
        await next();
    });
    // ...
}

If you go this route, consider making a custom middleware class instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM