.net 在blazor应用程序中添加2个身份验证方案

e3bfsja2  于 2023-08-08  发布在  .NET
关注(0)|答案(1)|浏览(131)

我使用的是Blazor WebAssembly. NET 7,我试图添加一个“安全”身份验证方案来保护我的Blazor页面。然而,我注意到,当我尝试将Authorize属性与参数@attribute [Authorize(AuthenticationSchemes = CustomAuthenticationSchemesNames. Secure)]一起使用时,它会抛出一个错误:

NotSupportedException: The authorization data specifies an authentication scheme with value 'Secure'. Authentication schemes cannot be specified for components. Microsoft.AspNetCore.Components.Authorization.AuthorizeViewCore.EnsureNoAuthenticationSchemeSpecified(IAuthorizeData[] authorizeData).

字符串
所以,我决定使用策略并创建了一个“SecurePolicy”,但它仍然不起作用。在那之后,我创建了一个cshtml组件,我不知道为什么,但它是与剃刀页工作。
下面是一些代码:
Program.cs认证配置:

builder.Services.AddAuthentication(options =>
                {
                    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                })
                .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, opts =>
                {
                    opts.LoginPath = "/auth-group/select-group";
                    opts.ExpireTimeSpan = TimeSpan.FromMinutes(240);
                })
                .AddCookie(CustomAuthenticationSchemesNames.Secure, opts =>
                {
                    opts.LoginPath = "/secure-auth/secure-login";
                    opts.ExpireTimeSpan = TimeSpan.FromMinutes(240);
                });

            builder.Services.AddAuthorization(options =>
            {
                var securePolicy = new AuthorizationPolicyBuilder(CustomAuthenticationSchemesNames.Secure)
                    .RequireAuthenticatedUser()
                    .Build();

                options.AddPolicy("SecurePolicy", securePolicy);
            });
...

  app.UseAuthentication();
            app.UseAuthorization();


我的blazor测试页面组件:

@using Microsoft.AspNetCore.Authorization
@page "/test-blazor-auth"
@inject NavigationManager navigationManager
@attribute [Authorize(Policy = "SecurePolicy")]

<h3>Test_Blazor</h3>

@code {
    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
    }
}


和test-cshtml组件:

@page "/test-auth"

@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage
@using SimpleSignon.Shared.Util
@model SimpleSignon.TenantWeb.Pages.Blazor.TestModel

<h1>Hello, Secure auth here</h1>

@{

}


和这个test-cshtml组件的页面模型:

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace SimpleSignon.TenantWeb.Pages.Blazor
{
    [Authorize(Policy = "SecurePolicy")]
    public class TestModel : PageModel
    {
        public void OnGet()
        {
            var res = HttpContext.User;
        }
    }
}


在这里你可以看到我如何签名我的用户:

var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme));

                            var authProperties = new AuthenticationProperties()
                            {
                                RedirectUri = ReturnUrl,
                                IsPersistent = EnableLocalChromePassword,
                            };

                            if (FlowType == FlowTypeNames.Secure)
                            {
                                var securePrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, CustomAuthenticationSchemesNames.Secure));

                                await HttpContext.SignInAsync(
                                    CustomAuthenticationSchemesNames.Secure,
                                    securePrincipal,
                                    authProperties);
                            }

                            await HttpContext.SignInAsync(
                                CookieAuthenticationDefaults.AuthenticationScheme,
                                principal,
                                authProperties);


授权流程应如下:
当用户使用默认的Cookie方案进行身份验证时,它不应该允许用户访问test-blazor组件(但它目前确实如此)。
当用户使用“Secure”方案进行身份验证时,他们应该能够访问test-blazor组件。
当然,如果用户使用两种方案进行了身份验证,他们也应该被允许访问test-blazor组件。
你有什么想法,我如何修复我的代码,使授权工作,我的blazor组件?

y1aodyip

y1aodyip1#

这是添加和检查策略中的一些问题。首先尝试配置为

services.AddAuthorization(config =>
{
config.AddPolicy("IsAdmin", policy => policy.RequireRole("admin", "moderator", "superuser"));
});

字符串
和属性

Authorize(Policy = "IsAdmin")


在您的代码中,.RequireAuthenticatedUser()仅在配置时指定。

相关问题