【问题标题】:Blazor App Server - Using Claims in a blazor similar to asp.net core Mvc?Blazor App Server - 在类似于 asp.net core Mvc 的 blazor 中使用声明?
【发布时间】:2021-08-01 13:13:38
【问题描述】:

我在 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);
            }
        }

但 HttpContext 是用于 mvc 的

我如何使用此代码?

我不能在剃刀视图中使用这个?

 @if (User.Identity.IsAuthenticated)

请帮帮我?

【问题讨论】:

    标签: c# asp.net asp.net-core blazor blazor-server-side


    【解决方案1】:

    但 HttpContext 是用于 mvc 我如何使用此代码?我不能 在剃刀视图中使用它?

     @if (User.Identity.IsAuthenticated)
    

    从您的代码和描述来看,您似乎正在创建一个带有 cookie 身份验证的 Asp.net Core Blazor 服务器应用程序,现在您想检查用户是否在 Razor 页面或 Razor 组件中经过身份验证,对吧?

    要在 Blazor 页面中获取当前用户详细信息,我们需要注入依赖项 IHttpContextAccessor

    首先,我们需要在startup.cs中配置IHttpContextAccessor服务,如下所示。

      services.AddHttpContextAccessor();
    

    然后,在 Blazor 组件中,参考以下方法检查用户是否通过身份验证:

    @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}";
        }
    }
    

    结果如下:

    有关使用 Cookie 身份验证创建 Blazor 服务器端应用程序的更多详细信息,您可以参考此示例:A Demonstration of Simple Server-side Blazor Cookie Authentication

    【讨论】:

    • 但我不知道如何将我的模型的价值赋予身份?
    猜你喜欢
    • 2020-02-21
    • 2021-05-23
    • 2022-09-28
    • 1970-01-01
    • 2023-02-23
    • 2020-08-09
    • 2021-05-18
    • 2020-09-30
    • 2021-04-14
    相关资源
    最近更新 更多