ASP.NET MVC中用户授权的智能方式(无需创建表等)
创始人
2024-09-16 19:01:13
0

在ASP.NET MVC中,可以使用Claims-based授权来实现智能的用户授权,而无需创建额外的表或数据库。

以下是一个示例解决方案:

  1. 在Startup.cs文件中配置身份验证和授权服务:
public void ConfigureServices(IServiceCollection services)
{
    // 添加身份验证服务
    services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    })
    .AddCookie(options =>
    {
        options.LoginPath = "/Account/Login";
    });

    // 添加授权服务
    services.AddAuthorization(options =>
    {
        options.AddPolicy("AdminOnly", policy =>
            policy.RequireClaim("Role", "Admin"));
    });

    services.AddControllersWithViews();
}
  1. 创建一个自定义AuthorizeAttribute类,用于检查用户的Claims:
public class CustomAuthorizeAttribute : TypeFilterAttribute
{
    public CustomAuthorizeAttribute(string role) : base(typeof(CustomAuthorizeFilter))
    {
        Arguments = new object[] { role };
    }
}

public class CustomAuthorizeFilter : IAuthorizationFilter
{
    private readonly string _role;

    public CustomAuthorizeFilter(string role)
    {
        _role = role;
    }

    public void OnAuthorization(AuthorizationFilterContext context)
    {
        var user = context.HttpContext.User;

        if (!user.Identity.IsAuthenticated || !user.HasClaim(c => c.Type == "Role" && c.Value == _role))
        {
            context.Result = new ForbidResult();
        }
    }
}
  1. 在需要授权的Controller或Action上使用自定义AuthorizeAttribute:
[CustomAuthorize("Admin")]
public class AdminController : Controller
{
    // 只有具有 "Admin" 角色的用户才能访问这个Action
    public IActionResult Index()
    {
        return View();
    }
}

这样,只有具有 "Admin" 角色的用户才能访问AdminController中的Index方法。

注意:在实际使用中,你可能需要根据你的用户和角色模型进行一些自定义的调整。此示例仅提供了一个基本的框架来实现智能用户授权。

相关内容

热门资讯

玩家必备科普!川蜀麻将有挂吗(... 玩家必备科普!川蜀麻将有挂吗(透视辅助)本来存在有挂(2024已更新)(哔哩哔哩);1、金币登录送、...
揭秘一下!nzt辅助器(透明挂... 揭秘一下!nzt辅助器(透明挂)原来有挂(2025已更新)(哔哩哔哩)1、nzt辅助器透视辅助简单,...
四分钟了解!微信里的麻将有挂吗... 四分钟了解!微信里的麻将有挂吗,微信小程序途游辅助器,揭秘攻略(有挂普及)1、这是跨平台的微信小程序...
安装程序教程!广西星悦字牌有挂... 安装程序教程!广西星悦字牌有挂么(辅助挂)竟然真的有挂(2020已更新)(哔哩哔哩)1、操作简单,无...
7分钟了解!河洛杠次老是输是外... 7分钟了解!河洛杠次老是输是外 挂吗,欢乐茶馆有外挂没有,揭秘教程(有挂技巧)暗藏猫腻,小编详细说明...
终于知道!越乡游斗地主有挂吗(... 终于知道!越乡游斗地主有挂吗(辅助挂)好像真的有挂(2025已更新)(哔哩哔哩)1、该软件可以轻松地...
八分钟了解!雀神广东麻雀辅助器... 八分钟了解!雀神广东麻雀辅助器,白金岛跑得快外挂,可靠教程(有挂插件);1)雀神广东麻雀辅助器辅助挂...
三分钟了解!约战荆门麻将有挂吗... 三分钟了解!约战荆门麻将有挂吗(透明挂)一直真的有挂(2022已更新)(哔哩哔哩)1、约战荆门麻将有...
十分钟了解!八闽掌上辅助软件,... 您好,八闽掌上辅助软件这款游戏可以开挂的,确实是有挂的,需要了解加微【757446909】很多玩家在...
教程辅助!永和备厅有挂吗(透视... 教程辅助!永和备厅有挂吗(透视辅助)总是是真的有挂(2022已更新)(哔哩哔哩)1、让任何用户在无需...