gpt4 book ai didi

c# - 如何在自定义基于策略的授权中访问 dbcontext & session

转载 作者:太空狗 更新时间:2023-10-29 22:21:34 25 4
gpt4 key购买 nike

我们是否可以访问 dbcontext 以在自定义基于策略的授权中获取我的表数据和 session ?任何人都可以帮助如何实现它?

        services.AddAuthorization(options =>
{
options.AddPolicy("CheckAuthorize",
policy => policy.Requirements.Add(new CheckAuthorize()));
});

services.AddSingleton<IAuthorizationHandler, CheckAuthorize>();


public class CheckAuthorize : AuthorizationHandler<CheckAuthorize>, IAuthorizationRequirement
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, CheckAuthorize requirement)
{

if () //check session to verify user is logged in or not
{
//redirect to login page
}
else
{
if ()//access dbcontext get data from database table to validate user access
{
//redirect to access denied page
}
}
throw new NotImplementedException();

}
}

最佳答案

策略可以使用DI

所以,假设你的数据库上下文在 DI 中,你可以做类似的事情

public class CheckAuthorizeHandler : AuthorizationHandler<CheckAuthorizeRequirement>
{
MyContext _context;

public CheckAuthorizeHandler(MyContext context)
{
_context = context;
}

protected override Task HandleRequirementAsync(
AuthorizationHandlerContext context,
MyRequirement requirement)
{
// Do something with _context
// Check if the requirement is fulfilled.
return Task.CompletedTask;
}
}

请注意,当您执行此操作时,您必须将您的需求设为一个单独的类,您不能这样做 CheckAuthorize : AuthorizationHandler<CheckAuthorize>, IAuthorizationRequirement , 所以你必须做

public CheckAuthorizeRequirement : IAuthorizationRequirement
{
}

最后您需要在 DI 系统中注册您的处理程序

services.AddTransient<IAuthorizationHandler, CheckAuthorizeHandler>();

关于c# - 如何在自定义基于策略的授权中访问 dbcontext & session,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39590060/

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