sunboy_sunboy
sunboy_sunboy

Reputation: 263

Blazor App Server - Using Claims in a blazor similar to asp.net core Mvc?

I Used This Code in Blazor :

 if (UserAccont.LoginUser(loginuser) != null)
        {
            if (UserAccont.UserIsBlocked(loginuser.Mobile)) 
            {
                UserIsBlocked = true;
            }
            else
            {
                var user = UserAccont.LoginUser(loginuser);
                var claims = new List<Claim>()
                {
                  new Claim(ClaimTypes.Name,user.Mobile.ToString()),
                };
                var identity = new ClaimsIdentity(claims, 
                 CookieAuthenticationDefaults.AuthenticationScheme);
                var principal = new ClaimsPrincipal(identity);
                var properties = new AuthenticationProperties
                {
                    IsPersistent = true

                };
                 HttpContext.SignInAsync(principal, properties);
            }
        }

But HttpContext was for mvc

How I Can using this Code?

and

I cant use this at the razor view ?

 @if (User.Identity.IsAuthenticated)

please help me?

Upvotes: 1

Views: 1864

Answers (1)

Zhi Lv
Zhi Lv

Reputation: 21526

But HttpContext was for mvc How I Can using this Code? and I cant use this at the razor view ?

 @if (User.Identity.IsAuthenticated)

From your code and description, it seems that you are creating an Asp.net Core Blazor server application with cookie Authentication, and now you want to check whether the user is Authenticated or not in the Razor page or Razor component, right?

To get current user details in a Blazor page, we need to inject the dependency IHttpContextAccessor.

First, we need to configure the IHttpContextAccessor service in the startup.cs as follows.

  services.AddHttpContextAccessor();

Then, in the Blazor component, refer the following method to check if user is authenticated:

@page "/"
@using Microsoft.AspNetCore.Http;
@inject IHttpContextAccessor httpContextAccessor
<h1>Hello, world!</h1>

Welcome to your new app.
<br />

@if (httpContextAccessor.HttpContext.User.Identity.IsAuthenticated)
{
    <span> You have authenticated! </span>
}
<br />
@message

<SurveyPrompt Title="How is Blazor working for you?" />

@code{
    private string message;

    protected override void OnInitialized()
    {
        if (httpContextAccessor.HttpContext.User.Identity.IsAuthenticated)
            message = $"Initialized at {DateTime.Now}";
    }
}

The result as below:

enter image description here

More detail information about creating a Blazor Server side application with Cookie authentication, you can refer this sample: A Demonstration of Simple Server-side Blazor Cookie Authentication

Upvotes: 1

Related Questions