简体   繁体   English

创建基于角色的Web应用程序的最佳方法是什么?

[英]What is the best approach to create a role based web application?

I need to create a web application for a School and I need to have different roles such as: 我需要为学校创建一个Web应用程序,我需要具有不同的角色,例如:

  • Student 学生
  • Professor 教授
  • Admin 管理员

I need to have a login at the beginning and then after entering the credentials the application needs to redirect to the home page. 我需要在开始时登录,然后在输入凭据后,应用程序需要重定向到主页。

The question here is: How should I handle the roles? 这里的问题是:我该如何处理这些角色? Should I have a namespace for each role? 我应该为每个角色都有一个命名空间吗? ie: students/index.jsp, professors/index.jsp, admin/index.jsp or have a common namespace for all roles? 即:students / index.jsp,professors / index.jsp,admin / index.jsp或所有角色都有一个共同的命名空间? something like home/index.jsp? 像home / index.jsp这样的东西? and then use decorator/composite pattern to have the menus have different options based on the role? 然后使用装饰器/复合模式让菜单根据角色有不同的选项?

For this question I know that I must store the users and the roles, each on in it's own table, this question is more related abour handling presentation/navigation/permission roles and how to create the webapp structure, ie have a directory under webapp folder called students, another folder admin, and another one students and about the point I mentioned above (decorator or composite pattern) 对于这个问题,我知道我必须存储用户和角色,每个都在自己的表中,这个问题与处理演示文稿/导航/权限角色以及如何创建webapp结构更相关,即在webapp文件夹下有一个目录叫学生,另一个文件夹管理员,另一个学生和我上面提到的点(装饰者或复合图案)

Of course I am not making an app this small but I wanted to simplify the issues I am facing in order to create a big role web based application, and I believe these are the main principles. 当然,我不是在制作这么小的应用程序,但我想简化我面临的问题,以便创建一个基于Web的大型应用程序,我相信这些是主要原则。

Thank you for your time and help. 感谢您的时间和帮助。

You definitely do NOT want to have separate pages ("namespaces") for different roles as that would almost inevitably lead to code duplication. 你绝对不希望为不同的角色提供单独的页面(“命名空间”),因为这几乎不可避免地导致代码重复。

You should have a page for each function and restrict access based on the roles of the users. 您应该拥有每个功能的页面,并根据用户的角色限制访问。 (eg some menu items are not visible for a Student, but shown for Professors and Admins.) (例如,某些菜单项对学生不可见,但为教授和管理员显示。)

You absolutely should not try re-inventing the wheel for managing role based permissions, as there are battle proven frameworks for that purpose: as others pointed out already, in Java world, Spring and Spring Security is the way to go. 你绝对不应该尝试重新发明轮子来管理基于角色的权限,因为有经验证的框架用于此目的:正如其他人已经指出的那样,在Java世界中,Spring和Spring Security是可行的方法。

I think JSP as technology is getting aged, so you should probably start learning Angular instead. 我认为JSP作为技术正在老化,所以你应该开始学习Angular

Since getting a working Spring / Angular project setup is not trivial, I would recommend you to use JHipster application generator that guides you through the whole process with a wizard (you have to just answer some questions -- when asked about the type select monolithic web application ): it then creates a working project configuration with role based security in place following modern recommendations. 由于获得一个有效的Spring / Angular项目设置并非易事 ,我建议您使用JHipster应用程序生成器 ,通过向导指导您完成整个过程(当您被问及类型选择monolithic web application时,您必须回答一些问题) monolithic web application ):然后根据现代建议创建一个基于角色的安全性的工作项目配置。

If you want to learn about proper role based access control in a modern web application, looking at the solutions used in a JHipster generated application is I believe the best and fastest solution: 如果您想在现代Web应用程序中了解基于角色的正确访问控制,那么查看JHipster生成的应用程序中使用的解决方案是我认为最好和最快的解决方案:

  • it uses Spring Security features to restrict calls in the Java backend: look for the usages of org.springframework.security.access.annotation.Secured annotation in the generated project 它使用Spring Security功能来限制Java后端中的调用:在生成的项目中查找org.springframework.security.access.annotation.Secured注释的用法
  • shows some custom frontend tricks to show/hide certain UI parts based on roles, like this: <h1 *jhiHasAnyAuthority="'ROLE_ADMIN'">Hello, admin user</h1> , which you could easily adopt to your own use case. 显示一些自定义前端技巧,根据角色显示/隐藏某些UI部分,如下所示: <h1 *jhiHasAnyAuthority="'ROLE_ADMIN'">Hello, admin user</h1> ,您可以轻松采用自己的用例。
  • you can have a working project in like 2 minutes: ideal for learning (go for the most simple monolithic web application !) 你可以在2分钟内完成一个工作项目:学习的理想选择(去寻找最简单的monolithic web application !)

I'm not sure my solution will work against your problem. 我不确定我的解决方案是否可以解决您的问题。 But in my case, I do it as follow: 但就我而言,我这样做如下:

User 0..n --- 0..m Role 用户0..n --- 0..m角色

Role 0..n --- 0..m Privilege 角色0..n --- 0..m特权

Production code 生产代码

In your case you may want: 在您的情况下,您可能需要:

  • Admin cannot view, edit student score. Admin无法查看,编辑学生成绩。
  • Student can view score but cannot edit. Student可以查看分数但无法编辑。
  • Professor can view, edit, add score. Professor可以查看,编辑,添加分数。

You can do as below: 你可以这样做:

Role 角色

  • ROLE_SCORE_EDITOR ROLE_SCORE_EDITOR
  • ROLE_SCORE_VIEWER ROLE_SCORE_VIEWER

Privilege 特权

  • OP_READ_SCORE OP_READ_SCORE
  • OP_CREATE_SCORE OP_CREATE_SCORE
  • OP_UPDATE_SCORE OP_UPDATE_SCORE
  • OP_DELETE_SCORE ---> Probably dont need this one but it enough for an example. OP_DELETE_SCORE --->可能不需要这个,但它足以作为一个例子。

Role - Privilege 角色 - 权限

ROLE_SCORE_EDITOR ROLE_SCORE_EDITOR

  • OP_READ_SCORE OP_READ_SCORE
  • OP_CREATE_SCORE OP_CREATE_SCORE
  • OP_UPDATE_SCORE OP_UPDATE_SCORE

ROLE_SCORE_VIEWER ROLE_SCORE_VIEWER

  • OP_READ_SCORE OP_READ_SCORE

User - Role 用户 - 角色

Admin (It's really depends on you, In my case I should leave it empty) 管理员(这真的取决于你,在我的情况下我应该留空)

Professor 教授

  • ROLE_SCORE_EDITOR ROLE_SCORE_EDITOR

Studen 斯图登

  • ROLE_SCORE_VIEWER ROLE_SCORE_VIEWER

Then in your template just guard your view with user.hasPrivilege or user.hasRole . 然后在您的模板中使用user.hasPrivilegeuser.hasRole保护您的视图。 It's will work fine. 它会工作正常。

P/s: Sorry for my bad English. P / s:抱歉我的英语不好。 If you need any thing please comment below or comment into my gist 如果您需要任何东西,请在下面评论或评论我的要点

There is no single answer to your question. 你的问题没有一个单一的答案。 Everything depends on the structure of the project. 一切都取决于项目的结构。 If there is much in common between the roles you mentioned, then it's better to use a single index.jsp for all roles. 如果您提到的角色之间存在许多共同点,那么最好对所有角色使用单个index.jsp。 Then you do not have to duplicate the common logic ( js and css libraries, custom common scripts, views and styles inclusion). 然后,您不必复制通用逻辑( jscss库,自定义通用脚本,视图和样式包含)。 If there is little in common between the roles, then it's better to have separate index.jsp files for each role, since single index.jsp file will be dynamically created during the execution of the program depending on selected role (I think it's still possible to fix by caching). 如果角色之间几乎没有共同点,那么最好为每个角色分别使用index.jsp文件,因为在执行程序期间将根据所选角色动态创建单个index.jsp文件(我认为它仍然可能通过缓存修复)。

In our projects, we use an approach with a single index.jsp file. 在我们的项目中,我们使用单个index.jsp文件的方法。 This is due in the first place to the fact that they have a lot of common logic. 这首先是因为它们有很多共同的逻辑。 But in any case decision will be taken by you. 但无论如何,您将做出决定。

Additionally, if you are using Spring Security and it's possible to add new roles during the process of developing of the project, then the @PreAuthorize ("hasRole ('ROLE_USER')") approach will be not good. 此外,如果您正在使用Spring Security并且可以在项目开发过程中添加新角色,那么@PreAuthorize ("hasRole ('ROLE_USER')")方法将不会很好。 Because if you'll add new role to the data base you will have to add a lot of code to the project to grant this new role required access. 因为如果您要向数据库添加新角色,则必须向项目添加大量代码,以授予此新角色所需的访问权限。 So, in this case will be better to grant access via permissions. 因此,在这种情况下,最好通过权限授予访问权限。 And create relationship many to many between roles <-> permissions 并在roles < - > permissions之间创建many to many关系

You can create different roles to give access to different restricted areas. 您可以创建不同的角色以访问不同的受限区域。 For example, you can have Student, Professor and Admin roles. 例如,您可以拥有学生,教授和管理员角色。 Later you can allow or prevent the access to the content based on the roles. 稍后,您可以根据角色允许或阻止对内容的访问。 Spring Security may be good for you. Spring Security可能对您有好处。

Having different pages violates the DRY (Don't repeat yourself) principle. 拥有不同的页面违反了DRY(不要重复自己)的原则。 If you want a simple solution, add Filters in your web app and do your authorisation there (delegate to 3rd party app). 如果您想要一个简单的解决方案,请在您的网络应用中添加过滤器并在那里进行授权(委托给第三方应用)。 You would need to add conditions in the jsp page at a group level so that it need not be changed every time. 您需要在组级别的jsp页面中添加条件,以便不必每次都更改它。

You can also use Spring security and jdbc authentication. 您还可以使用Spring安全性和jdbc身份验证。

I am in a similar situation right now. 我现在处于类似情况。 My Project(s) need Authentication and role-based Authorization. 我的项目需要身份验证和基于角色的授权。 There are a number of solutions available for Java applications. Java应用程序有许多可用的解决方案。 Our team decided to use Keycloak , which is an extra app where you can handle most of the user management. 我们的团队决定使用Keycloak ,这是一个额外的应用程序,您可以处理大部分用户管理。 It can run on a seperate server. 它可以在单独的服务器上运行。 Though, depending on the scope of your app, it might be overkill. 但是,根据您的应用程序的范围,它可能是矫枉过正。

As I see it, you have not yet implemented any Authentication. 在我看来,你还没有实现任何身份验证。 That part is finished in my case and it was mostly done through configuration in Keycloak + web server. 这部分是在我的情况下完成的,它主要是通过Keycloak + web服务器中的配置完成的。

Generally, you can use Java EE security for Authorization in most modern web servers. 通常,您可以在大多数现代Web服务器中使用Java EE安全性进行授权。 This will allow you to use Annotations like @RolesAllowed to grant or deny access and can work regardless of Keycloak. 这将允许您使用@RolesAllowed等注释来授予或拒绝访问权限,并且无论Keycloak如何都可以使用。 Examples . 例子 This way you can keep a unified structure for all your different roles and only decide the legitimacy of a request just before it is executed. 通过这种方式,您可以为所有不同的角色保留统一的结构,并且只在执行之前决定请求的合法性。

you can create table based named like role_user based on that you can segregate 您可以根据可以隔离的名称创建基于role_user的表

different roles 不同的角色

尝试使用弹簧框架和弹簧安全性开发您的Web应用程序请参考以下示例http://websystique.com/spring-security/spring-security-4-role-based-login-example/

I believe you should go forward with Spring Security . 我相信你应该继续使用Spring Security It provides you many features out of the box and configuring and maintaining your application becomes so much easier. 它为您提供了许多开箱即用的功能,配置和维护您的应用程序变得更加容易。 Also, you will be able to focus more on building the logic of your application while the library handles the Authentication and Authorization(the roles in simple words) for you. 此外,您将能够更专注于构建应用程序的逻辑,同时库为您处理身份验证和授权(简单的角色)。 Plus it has a lot of community support. 此外,它还有很多社区支持。

Here is an example to get started: Spring security - hello world 这是一个入门的例子: Spring security - hello world

From the example above, let me show a snippet of code to give more weight to my claim: 从上面的例子中,让我展示一段代码,以更加重视我的主张:

@Override
    protected void configure(HttpSecurity http) throws Exception {

      http.authorizeRequests()
        .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
        .antMatchers("/dba/**").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_DBA')")
        .and().formLogin();

    }

So what the above config will do is, whenever you try to access the /admin page or any url under admin pages eg /admin/profile , /admin/home etc., you will be asked to authenticate yourself ( with a username and password in your case). 那么上面的配置会做什么,每当你试图访问/admin页面或管理页面下的任何网址,例如/admin/profile/admin/home等时,你将被要求自己进行身份验证(使用用户名和密码)在你的情况下)。 The spring security will check whether the username and password is correct. spring security将检查用户名和密码是否正确。 In addition to this, it will also check if the provided username has role admin. 除此之外,它还将检查提供的用户名是否具有角色admin。 If both (password and role) check succeed, then only you will be allowed to access that page. 如果两者(密码和角色)检查都成功,则只允许您访问该页面。

So with just few lines of code you are controlling entire security with role management for your application. 因此,只需几行代码,您就可以通过应用程序的角色管理来控制整个安全性。

Although in the example post, hard coded usernames are used but plugging your db is also pretty easy. 虽然在示例帖子中,使用了硬编码的用户名,但插入数据库也很容易。 But the example is a good way to get started and see for yourself if it fits your use case. 但是这个例子是一个很好的入门方式,如果它适合您的用例,请自己查看。

There are multiple approaches for this problem. 这个问题有多种方法。 For example, you can use a filter to authenticate and authorise the access of your resources to different users/roles. 例如,您可以使用过滤器对不同用户/角色的资源进行身份验证和授权。 Other than this, Spring Security provides builtin mechanism to ensure authorised access to the web resources. 除此之外,Spring Security还提供内置机制来确保对Web资源的授权访问。 Other than this, you can create an admin panel in your application, and you can assign different pages to different roles (but, this approach involves more programming work). 除此之外,您可以在应用程序中创建管理面板,并且可以将不同的页面分配给不同的角色(但是,这种方法涉及更多的编程工作)。 You can also think to create security constraints in web.xml and you can associate web-resource-collections with different roles. 您还可以考虑在web.xml中创建安全性约束,并且可以将Web资源集合与不同的角色相关联。

Best approach would be : Spring Security 最好的方法是: Spring Security

But it needs time and studying to do it the right way, so till then I do something like this: 但它需要时间和学习,以正确的方式做到这一点,所以在那之前我做这样的事情:

  1. Say you have a table user in your database. 假设您的数据库中有一个表用户 Add a column name eg user_rights . 添加列名称,例如user_rights
  2. In your application this column is a field of your User model class 在您的应用程序中,此列是User模型类的字段
  3. Create a method which checks this field and handles the roles as you wish 创建一个方法来检查此字段并根据需要处理角色

For instance, if a users role determines on what pages they have access, this is a simplified code example: 例如,如果用户角色确定他们有权访问哪些页面,则这是一个简化的代码示例:

At the begining of your web-page: 在您的网页开头:

<h:body>

<f:metadata>
    <f:viewAction action="#{userService.checkIfLogged()}" />
    <f:viewAction action="#{userService.accessCheck('page 2')}" />
</f:metadata>

and in your bean method: 在你的bean方法中:

@Override
@Transactional
public String accessCheck(String page) {
    try {
       HttpSession sess = Util.getSession();
       String user = sess.getAttribute("username").toString();
       Session session = this.sessionFactory.getCurrentSession();
       User logged = (User) session.createQuery("select u from User u where 
                     u.username = :logged").setParameter("logged", 
                                            user).uniqueResult();
       if (page.equals("page 1")) {
        if (logged.getRights().equals("simple")) {
            return "profile?faces-redirect=true";
        } 
        else {
            return "#";
        }
    }   ... etc.

Hope this is helpful, I still recommend Spring framework's features, but in the meantime this works perfect for me for small web apps. 希望这很有用,我仍然推荐Spring框架的功能,但同时这对我来说对于小型网络应用程序来说非常适合。

Good question. 好问题。 Actually extension of this is complete authentication module For your small case A common page is the best solution. 实际上,这是完整认证模块的扩展。对于您的小案例,常见页面是最佳解决方案。 As per the role desired text boxes or fields will appear. 根据所需的角色,将出现文本框或字段。 For Example, in case Role Student: subject, roll number will be available. 例如,如果是Role Student:subject,则卷号将可用。 But in case Professor logs in into same page, he can see additional fields like numbers, attendance etc. Easiest solution can be: To Create a master table, with Name, Id, TYPE(With there type whether student/Professor/Admin etc.), and use this TYPE as the decisive factor for showing fields. 但是如果教授登录到同一页面,他可以看到其他字段,如数字,出勤等。 最简单的解决方案可以是:创建一个主表,名称,ID,类型(有类型是否学生/教授/管理员等。 ),并使用此TYPE作为显示字段的决定性因素。

您可以在数据库中使用保存角色的字段,但您可以阅读有关ACL和RBAC的信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 开发BlackBerry Web应用程序(WebWorks Application)的最佳方法是什么? - What's the best approach for developing a BlackBerry web application (WebWorks Application) 什么是访问数据库的最佳基于Web的应用程序 - What is the best web based application to access a database 保护REST服务和Web应用程序的最佳方法 - Best approach for securing REST services and a web application 基于价值观拆分Arraylist的最佳方法是什么? - What is the best approach to split an Arraylist based on their values 实现基于令牌的身份验证的最佳方法是什么 - What is the best approach to implement token based authentication 将Android应用程序移植到Windows的最佳方法是什么? - What is the best approach to port an Android application to Windows? 在基于多语言Java的Web应用程序中构建的最佳编码是什么,为什么? - What is the best encoding for buildin a multilingual java based web application, and why? 审核大型java / j2ee Web应用程序的最佳方法是什么? - What's the best approach in auditing a big java/j2ee web application 创建聚合表的最佳方法是什么? - What is the best approach to create aggregation tables? 是否可以在同一个Java Web应用程序中使用xml创建一些bean,并使用基于注释的方法创建其余bean? - Is it possible to create some beans using xml and the remaining beans using annotation based approach in the same java web application
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM