gpt4 book ai didi

blazor - 如何为 Blazor 页面实现自定义授权过滤器

转载 作者:行者123 更新时间:2023-12-04 13:14:14 26 4
gpt4 key购买 nike

Blazor 服务器端,.NET Core 3.1.x
查看授权示例,我正在尝试获取自定义授权过滤器/属性的解决方案。我只需要在授权期间检查用户身份。

https://docs.microsoft.com/en-us/aspnet/core/security/blazor/?view=aspnetcore-3.1

在 Blazor 页面的顶部,@page 之后

@attribute [MyAuthFilter]

过滤器。然而,OnAuthorization 永远不会被击中。
public class MyAuthFilter: AuthorizeAttribute,IAuthorizationFilter
{
public void OnAuthorization(AuthorizationFilterContext context)
{
var httpContext = context.HttpContext;


// get user name
string userName = httpContext.User.Identity.Name;

// todo - call method to check user access
// check against list to see if access permitted
//context.Result = new UnauthorizedResult();

}
}

最佳答案

以下代码片段描述了如何执行授权过程,以及如何以及在何处为授权用户显示内容。您可以根据此处显示的代码构建自己的组件:

Profile.razor

@page "/profile"
@page "/profile/{id}"


<AuthorizeView Policy="CanEditProfile" Resource="@ID">
<NotAuthorized>
<h2 class="mt-5">You are not authorized to view this page</h2>
</NotAuthorized>
<Authorized>
<div class="container my-profile">
<h2>My Profile</h2>
--- Place here all the content you want your user to view ----
</div>
</Authorized>
</AuthorizeView>

@code {

[Parameter]
public string ID { get; set; }
}

ProfileHandler.cs
public class ProfileHandler : IAuthorizationHandler
{
public Task HandleAsync(AuthorizationHandlerContext context)
{
if (context.User != null)
{
var pendingRequirements = context.PendingRequirements.ToList();

foreach (var requirement in pendingRequirements)
{
if (requirement is ProfileOwnerRequirement)
{
// get profile id from resource, passed in from blazor
// page component
var resource = context.Resource?.ToString();
var hasParsed = int.TryParse(resource, out int
profileID);
if (hasParsed)
{

if (IsOwner(context.User, profileID))
{
context.Succeed(requirement);
}
}
}
}

}
return Task.CompletedTask;
}
private bool IsOwner(ClaimsPrincipal user, int profileID)
{
// compare the requested memberId to the user's actual claim of
// memberId
// var isAuthorized = context.User.GetMemberIdClaim();
// now we know if the user is authorized or not, and can act
// accordingly

var _profileID = user.GetMemberIDClaim();


return _profileID == profileID;
}

}

ProfileOwnerRequirement.cs
 public class ProfileOwnerRequirement : IAuthorizationRequirement
{
public ProfileOwnerRequirement() { }

}

创业类
services.AddSingleton<IAuthorizationHandler, ProfileHandler>();

services.AddAuthorization(config =>
{
config.AddPolicy("CanEditProfile", policy =>
policy.Requirements.Add(new ProfileOwnerRequirement()));
});

希望这可以帮助!

关于blazor - 如何为 Blazor 页面实现自定义授权过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61959852/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com