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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48467948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 10:04:55  来源:igfitidea点击:

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

javawebloginroles

提问by Diego Ramos

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? i.e: students/index.jsp, professors/index.jsp, admin/index.jsp or have a common namespace for all roles? something like home/index.jsp? and then use decorator/composite pattern to have the menus have different options based on the role?

这里的问题是:我应该如何处理这些角色?我应该为每个角色都有一个命名空间吗?即:students/index.jsp、professors/index.jsp、admin/index.jsp 或所有角色都有一个共同的命名空间?类似 home/index.jsp 的东西?然后使用装饰器/复合模式让菜单根据角色有不同的选项?

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, i.e 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.

感谢您的时间和帮助。

采纳答案by Peter G. Horvath

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. (e.g. 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 Securityis the way to go.

您绝对不应该尝试重新发明轮子来管理基于角色的权限,因为有为此目的经过战斗验证的框架:正如其他人已经指出的那样,在 Java 世界中,Spring 和Spring Security是要走的路。

I think JSP as technology is getting aged, so you should probably start learning Angularinstead.

我认为 JSP 随着技术越来越老,所以你应该开始学习Angular

Since getting a working Spring / Angular project setup is not trivial, I would recommend you to use JHipster application generatorthat 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 应用程序生成器,该应用程序生成器通过向导引导您完成整个过程(您只需回答一些问题——当被问及类型 select 时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.Securedannotation in the generated project
  • 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.
  • you can have a working project in like 2 minutes: ideal for learning (go for the most simple monolithic web application!)
  • 它使用 Spring Security 特性来限制 Java 后端的调用:org.springframework.security.access.annotation.Secured在生成的项目中查找注解的用法
  • 展示了一些基于角色显示/隐藏某些 UI 部分的自定义前端技巧,例如: <h1 *jhiHasAnyAuthority="'ROLE_ADMIN'">Hello, admin user</h1>,您可以轻松地将其应用于您自己的用例。
  • 您可以在 2 分钟内完成一个工作项目:非常适合学习(追求最简单的monolithic web application!)

回答by Liem Le

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:

在您的情况下,您可能需要:

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

You can do as below:

您可以执行以下操作:

Role

角色

  • ROLE_SCORE_EDITOR
  • ROLE_SCORE_VIEWER
  • ROLE_SCORE_EDITOR
  • ROLE_SCORE_VIEWER

Privilege

特权

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

Role - Privilege

角色 - 权限

ROLE_SCORE_EDITOR

ROLE_SCORE_EDITOR

  • OP_READ_SCORE
  • OP_CREATE_SCORE
  • OP_UPDATE_SCORE
  • OP_READ_SCORE
  • OP_CREATE_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.hasPrivilegeor user.hasRole. It's will work fine.

然后在您的模板中使用user.hasPrivilege或保护您的视图user.hasRole。它会工作得很好。

P/s: Sorry for my bad English. If you need any thing please comment below or comment into my gist

P/s:抱歉我的英语不好。如果您需要任何东西,请在下面评论或评论我的要点

回答by amanzoor

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 Securitymay be good for you.

您可以创建不同的角色来授予对不同限制区域的访问权限。例如,您可以拥有学生、教授和管理员角色。稍后您可以根据角色允许或阻止对内容的访问。Spring Security可能对您有好处。

回答by Bohdan Petrenko

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. Then you do not have to duplicate the common logic (jsand csslibraries, custom common scripts, views and styles inclusion). 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。然后您不必复制公共逻辑(jscss库、自定义公共脚本、视图和样式包含)。如果角色之间几乎没有共同点,那么最好为每个角色拥有单独的 index.jsp 文件,因为在程序执行期间将根据所选角色动态创建单个 index.jsp 文件(我认为这仍然是可能的通过缓存修复)。

In our projects, we use an approach with a single index.jsp file. 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.

在我们的项目中,我们使用单一 index.jsp 文件的方法。这首先是因为它们有很多共同的逻辑。但无论如何,决定将由您做出。

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. 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 manybetween roles<-> permissions

此外,如果您使用的是 Spring Security,并且在项目开发过程中可能会添加新角色,那么这种@PreAuthorize ("hasRole ('ROLE_USER')")方法也不是很好。因为如果您将新角色添加到数据库中,您将不得不向项目添加大量代码以授予此新角色所需的访问权限。因此,在这种情况下,最好通过权限授予访问权限。并many to manyroles<->之间创建关系permissions

回答by DevEmani

Having different pages violates the DRY (Don't repeat yourself) principle. 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.

拥有不同的页面违反了 DRY(不要重复自己)原则。如果您想要一个简单的解决方案,请在您的网络应用程序中添加过滤器并在那里进行授权(委托给第 3 方应用程序)。您需要在组级别的 jsp 页面中添加条件,以便不必每次都更改。

You can also use Spring security and jdbc authentication.

您还可以使用 Spring 安全性和 jdbc 身份验证。

回答by P Laack

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. Our team decided to use Keycloak, which is an extra app where you can handle most of the user management. It can run on a seperate server. Though, depending on the scope of your app, it might be overkill.

我现在处于类似的情况。我的项目需要身份验证和基于角色的授权。有许多解决方案可用于 Java 应用程序。我们的团队决定使用Keycloak,这是一个额外的应用程序,您可以在其中处理大部分用户管理。它可以在单独的服务器上运行。但是,根据您的应用程序的范围,它可能有点矫枉过正。

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. This will allow you to use Annotations like @RolesAllowed to grant or deny access and can work regardless of 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.

通常,您可以在大多数现代 Web 服务器中使用 Java EE 安全性进行授权。这将允许您使用 @RolesAllowed 之类的注解来授予或拒绝访问权限,并且无论 Keycloak 如何都可以工作。例子。通过这种方式,您可以为所有不同的角色保持统一的结构,并且仅在请求执行之前确定请求的合法性。

回答by rohit raj

you can create table based named like role_user based on that you can segregate

您可以根据您可以隔离的方式创建基于命名的表,例如 role_user

different roles

不同的角色

回答by Sumesh TG

Try to develop your web app using spring framework and spring security Please refer the below example http://websystique.com/spring-security/spring-security-4-role-based-login-example/

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

回答by tryingToLearn

I believe you should go forward with 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.

我相信你应该继续前进Spring Security。它为您提供了许多开箱即用的功能,并且配置和维护您的应用程序变得更加容易。此外,您将能够更多地专注于构建应用程序的逻辑,而库会为您处理身份验证和授权(简单来说就是角色)。此外,它有很多社区支持。

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 /adminpage or any url under admin pages e.g. /admin/profile, /admin/homeetc., you will be asked to authenticate yourself ( with a username and password in your case). The spring security will check whether the username and password is correct. In addition to this, it will also check if the provided username has role admin. If both (password and role) check succeed, then only you will be allowed to access that page.

那么,上述的配置需要做的是,当您尝试访问/admin下的管理页面例如页面或任何URL /admin/profile/admin/home等等,你会被要求验证身份(与你的情况下,用户名和密码)。spring security 会检查用户名和密码是否正确。除此之外,它还将检查提供的用户名是否具有 admin 角色。如果(密码和角色)检查都成功,则只有您可以访问该页面。

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.

尽管在示例帖子中使用了硬编码的用户名,但插入数据库也很容易。但该示例是一个很好的入门方式,您可以亲自查看它是否适合您的用例。

回答by Dr. Muhammad Wasim Bhatti

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. 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.

这个问题有多种方法。例如,您可以使用过滤器对您的资源对不同用户/角色的访问进行身份验证和授权。除此之外,Spring Security 提供了内置机制来确保对 Web 资源的授权访问。除此之外,您可以在您的应用程序中创建一个管理面板,您可以将不同的页面分配给不同的角色(但是,这种方法涉及更多的编程工作)。您还可以考虑在 web.xml 中创建安全约束,并且可以将 web-resource-collections 与不同的角色相关联。