如何在ASP.NET MVC 5 Web应用程序中实现授权。 [英] How to implement authorization in ASP.NET MVC 5 web application.

查看:168
本文介绍了如何在ASP.NET MVC 5 Web应用程序中实现授权。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我浏览过很多网站和Youtube视频。但无法在我的项目中正确理解和实施。有人可以告诉我如何使用asp.net mvc 5 web应用程序中的授权(不认证)吗?



我尝试过:



我提供的注释如[授权]& [AllowAnonymous]到Controller的方法,只能由管理员访问。但我无法做到。甚至管理员也无法访问这些页面。

I have gone through many websites and Youtube videos. but couldn't understood and implemented in my project properly. Can anybody please tell me how to work with authorization(Not authentication) in asp.net mvc 5 web application?

What I have tried:

I have provided annotations like [Authorize] & [AllowAnonymous] to Controller's method which can be accessed by admin only. But i am not able to do it. Even admin can't access these pages.

推荐答案

由于您将用户的角色存储在数据库中,因此您必须检查数据库。

因此,请尝试在global.asax中包含此方法

Since you stored the roles of the users in the database, you have to check to the database.
So try to include this method in the global.asax
protected void Application_AuthenticateRequest(object sender, EventArgs args)
    {
        if (Context.User != null)
        {
            IEnumerable<role> roles = new UsersService.UsersClient().GetUserRoles(
                                                    Context.User.Identity.Name);


            string[] rolesArray = new string[roles.Count()];
            for (int i = 0; i < roles.Count(); i++)
            {
                rolesArray[i] = roles.ElementAt(i).RoleName;
            }

            GenericPrincipal gp = new GenericPrincipal(Context.User.Identity, rolesArray);
            Context.User = gp;
        }
    }
</role>





然后你就可以使用它了控制器中的actionResult方法。



Then you could use this on top of the actionResult methods in the controllers.

[Authorize(Roles = "Administrator")]





希望这有帮助。



Hope this helps.


这篇关于如何在ASP.NET MVC 5 Web应用程序中实现授权。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆