Today we will look into spring security role based access and authorization example. However before reading this post, please go through my previous post about “Spring 4 Security MVC Login Logout Example” to get some basic knowledge about Spring 4 Security.

今天,我们将研究基于Spring安全角色的访问和授权示例。 但是,在阅读本文之前,请仔细阅读我以前关于“ Spring 4 Security MVC登录注销示例 ”的文章,以获取有关Spring 4 Security的一些基本知识。

Spring安全角色 (Spring Security Role)

In this post, we will discuss how to define, use and manage spring security roles like “USER”, “ADMIN” in Spring Web Application.

在本文中,我们将讨论如何在Spring Web Application中定义,使用和管理Spring安全角色,例如“ USER”,“ ADMIN”。

Like my previous post, this post example is also using Spring 4 MVC Security with In-Memory Store and Spring Java Configuration Feature to develop the application. That means we are not going to use web.xml file and also not writing even single line of Spring XML Configuration.

就像我以前的文章一样,这个例子还使用Spring 4 MVC Security和内存中存储以及Spring Java配置功能来开发应用程序。 这意味着我们将不会使用web.xml文件,甚至不会编写Spring XML Configuration的一行。

We will use “In-Memory Store” option to store and manage User Credentials.

我们将使用“内存中存储”选项来存储和管理用户凭据。

We are going to use Spring 4.0.2.RELEASE, Spring STS 3.7 Suite IDE, Spring TC Server 3.1 with Java 1.8 and Maven build tool to develop this example.

我们将使用Spring 4.0.2.RELEASE,Spring STS 3.7 Suite IDE,带有Java 1.8的Spring TC Server 3.1和Maven构建工具来开发此示例。

基于Spring Security角色的访问授权示例 (Spring Security Role Based Access Authorization Example)

  1. Create a “Simple Spring Web Maven” Project in Spring STS Suite with the following details.在Spring STS Suite中使用以下详细信息创建“ Simple Spring Web Maven”项目。
  2. Project Name : SpringMVCSecruityMavenRolesApp

    项目名称:SpringMVCSecruityMavenRolesApp

  3. Use same pom.xml file from my previous post with the following changes使用与我以前的帖子相同的pom.xml文件,并进行以下更改
  4. <artifactId>SpringMVCSecruityMavenRolesApp</artifactId><build><finalName>SpringMVCSecruityMavenRolesApp</finalName>
    </build>
    </project>
  5. Use all Java and JSP files from my previous post. We will discuss only updated or newly added content here.使用我以前的文章中的所有Java和JSP文件。 我们将仅在此处讨论更新或新增的内容。
  6. Update LoginSecurityConfig.java file to configure User roles like “USER” and “ADMIN”.更新LoginSecurityConfig.java文件以配置用户角色,例如“ USER”和“ ADMIN”。
  7. LoginSecurityConfig.java

    LoginSecurityConfig.java

    package com.journaldev.spring.secuity.config;import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;@Configuration
    @EnableWebSecurity
    public class LoginSecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredpublic void configureGlobal(AuthenticationManagerBuilder authenticationMgr) throws Exception {authenticationMgr.inMemoryAuthentication().withUser("jduser").password("jdu@123").authorities("ROLE_USER").and().withUser("jdadmin").password("jda@123").authorities("ROLE_USER","ROLE_ADMIN");}@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/homePage").access("hasRole('ROLE_USER') or hasRole('ROLE_ADMIN')").antMatchers("/userPage").access("hasRole('ROLE_USER')").antMatchers("/adminPage").access("hasRole('ROLE_ADMIN')").and().formLogin().loginPage("/loginPage").defaultSuccessUrl("/homePage").failureUrl("/loginPage?error").usernameParameter("username").passwordParameter("password")               .and().logout().logoutSuccessUrl("/loginPage?logout"); }
    }

    Code Explanation

    代码说明

    1. In configureGlobal() method, we have added two users: One user with “ROLE_USER” role and another user with both “ROLE_USER” and “ROLE_ADMIN” roles. That means this second user will act as a Admin User. Like this we can configure any number of users and roles.在configureGlobal()方法中,我们添加了两个用户:一个具有“ ROLE_USER”角色的用户,另一个具有“ ROLE_USER”和“ ROLE_ADMIN”角色的用户。 这意味着该第二个用户将充当管理员用户。 这样,我们可以配置任意数量的用户和角色。
    2. We can use either authorities(ROLE) or roles(ROLE) methods to configure Roles in our application.我们可以使用Authority(ROLE)或Roles(ROLE)方法在我们的应用程序中配置Roles。
    3. Difference between authorities() and roles() methods:Authoritys()和Roles()方法之间的区别:
  • authorities() needs complete role name like “ROLE_USER”Authority()需要完整的角色名称,例如“ ROLE_USER”
  • roles() needs role name like “USER”. It will automatically adds “ROLE_” value to this “USER” role name.role()需要角色名称,例如“ USER”。 它将自动向该“ USER”角色名称添加“ ROLE_”值。
  • In configure() method, we have defined different URLs with required Access Roles.在configure()方法中,我们使用所需的访问角色定义了不同的URL。
  • antMatchers("/homePage").access("hasRole('ROLE_USER') or hasRole('ROLE_ADMIN')")

    This code snippet configures that “/homePage” is available for both USER and ADMIN Roles.

    此代码段配置“ / homePage”可用于USER和ADMIN角色。

    .antMatchers("/userPage").access("hasRole('ROLE_USER')").antMatchers("/adminPage").access("hasRole('ROLE_ADMIN')")

    This code snippet configures that “/userPage” is accessible by “USER” role only and .”/adminPage” is accessible by “ADMIN” role only.

    此代码段配置“ / userPage”只能由“ USER”角色访问,而“ / adminPage”只能由“ ADMIN”角色访问。

    If other roles access these pages, we will get access “403 Access is Denied” Error message.

    如果其他角色访问这些页面,我们将获得“ 403访问被拒绝”错误消息。

  • Update LoginController.java Controller file to define new URL access paths as shown below.更新LoginController.java控制器文件以定义新的URL访问路径,如下所示。
  • LoginController.java

    LoginController.java

    package com.journaldev.spring.web.controller;import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.servlet.ModelAndView;@Controller
    public class LoginController {@RequestMapping(value = { "/"}, method = RequestMethod.GET)public ModelAndView welcomePage() {ModelAndView model = new ModelAndView();model.setViewName("welcomePage");return model;}@RequestMapping(value = { "/homePage"}, method = RequestMethod.GET)public ModelAndView homePage() {ModelAndView model = new ModelAndView();model.setViewName("homePage");return model;}@RequestMapping(value = {"/userPage"}, method = RequestMethod.GET)public ModelAndView userPage() {ModelAndView model = new ModelAndView();model.setViewName("userPage");return model;}@RequestMapping(value = {"/adminPage"}, method = RequestMethod.GET)public ModelAndView adminPage() {ModelAndView model = new ModelAndView();model.setViewName("adminPage");return model;}@RequestMapping(value = "/loginPage", method = RequestMethod.GET)public ModelAndView loginPage(@RequestParam(value = "error",required = false) String error,@RequestParam(value = "logout",  required = false) String logout) {ModelAndView model = new ModelAndView();if (error != null) {model.addObject("error", "Invalid Credentials provided.");}if (logout != null) {model.addObject("message", "Logged out from JournalDEV successfully.");}model.setViewName("loginPage");return model;}}

    Code Explanation
    In addition to the previous post Example, here we have added two more new URLs.

    代码说明
    除了上一个示例,我们在这里还添加了两个新的URL。

    1. “/userPage” is used by USER Role to access and perform Normal user activities.用户角色使用“ / userPage”来访问和执行普通用户活动。
    2. “/adminPage” is used by ADMIN Role to access and perform Admin user activities. ADMIN role can access “/userPage” URL too.ADMIN角色使用“ / adminPage”来访问和执行Admin用户活动。 ADMIN角色也可以访问“ / userPage” URL。
  • Updated homePage.jsp file to provide User and Admin Roles specific activities.更新了homePage.jsp文件,以提供特定于用户和管理员角色的活动。
  • homePage.jsp

    homePage.jsp

    <%@taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core"%>
    <a href="${pageContext.request.contextPath}/userPage">JD User</a> | <a href="${pageContext.request.contextPath}/adminPage">JD Admin</a> | <a href="javascript:document.getElementById('logout').submit()">Logout</a><h3>Welcome to JournalDEV Tutorials</h3>
    <ul><li>Java 8 tutorial</li><li>Spring tutorial</li><li>Gradle tutorial</li><li>BigData tutorial</li>
    </ul><c:url value="/logout" var="logoutUrl" />
    <form id="logout" action="${logoutUrl}" method="post" ><input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
    </form>

    Here we have add three Menu like options at top frame. “Logout” is already discussed in my previous post.

    在这里,我们在顶部添加了三个类似于菜单的选项。 在我之前的文章中已经讨论了“注销”。

    New two links are:

    新的两个链接是:

    1. JD User: Accessible by both “USER” and “ADMIN” RolesJD用户:“ USER”和“ ADMIN”角色均可访问
    2. JD Admin: Accessible only by both “ADMIN” RolesJD Admin:只能由两个“ ADMIN”角色访问

    NOTE:- In Real-time applications, we will show only “JD User” link to “USER” Role and hide “JD Admin” link. To test whether it is accessible by “USER” Role or not and also to see the exact error message, we have not hidden this link.

    注意:-在实时应用程序中,我们将仅显示“ JD用户”链接到“用户”角色,并隐藏“ JD管理员”链接。 为了测试“用户”角色是否可以访问它,并查看确切的错误消息,我们没有隐藏此链接。

  • Add new adminPage.jsp file to act as a Homepage for “ADMIN” role.添加新的adminPage.jsp文件,以充当“ ADMIN”角色的主页。
  • adminPage.jsp

    adminPage.jsp

    <%@taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core"%>
    <h3>Welcome to JournalDEV Tutorials</h3>
    <h3>Admin Page</h3><c:url value="/logout" var="logoutUrl" />
    <form id="logout" action="${logoutUrl}" method="post" ><input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
    </form>
    <c:if test="${pageContext.request.userPrincipal.name != null}"><a href="javascript:document.getElementById('logout').submit()">Logout</a>
    </c:if>
  • Add new userPage.jsp file to act as a Homepage for “USER” role.添加新的userPage.jsp文件以充当“用户”角色的主页。
  • userPage.jsp

    userPage.jsp

    <%@taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core"%>
    <h3>Welcome to JournalDEV Tutorials</h3>
    <h3>User Page</h3><c:url value="/logout" var="logoutUrl" />
    <form id="logout" action="${logoutUrl}" method="post" ><input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
    </form>
    <c:if test="${pageContext.request.userPrincipal.name != null}"><a href="javascript:document.getElementById('logout').submit()">Logout</a>
    </c:if>

    We have completed our application development now. It’s time to see our project final structure and test the application.

    现在,我们已经完成了应用程序开发。 现在是时候查看我们项目的最终结构并测试应用程序了。

  • Final Project Structure looks like this:最终项目结构如下所示:
  • Spring安全角色示例应用程序测试 (Spring Security Roles Example Application Test)

    1. Right Click on Project in Spring STS IDE and select “Run AS >> Run on Server” option.在Spring STS IDE中右键单击Project,然后选择“运行AS >>在服务器上运行”选项。
    2. It will access default Application welcome page as shown below:

      它将访问默认的应用程序欢迎页面,如下所示:

    3. Click on “Login to JournalDEV” link.Now you are at Login Page.单击“登录到JournalDEV”链接。现在您位于登录页面。
    4. First login with “USER” Role Credentials:首次使用“ USER”角色凭证登录:
    5. Username: jduser
      Password: jdu@123

      用户名:jduser
      密码:jdu @ 123

      Now we will see Application HomePage with 3 Menu Options: “JD User”, “JD Admin” and “Logout”.

      现在,我们将看到带有三个菜单选项的“应用程序主页”:“ JD用户”,“ JD管理员”和“注销”。

      Click on “JD User” link. As we have logged into application using “USER” Role Credentials, We can access this link as shown below.

      单击“ JD用户”链接。 当我们使用“用户”角色凭证登录到应用程序后,我们可以如下所示访问此链接。

      Just use backword arrow in Spring STS IDE and this time click on “JD Admin” Link.

      只需在Spring STS IDE中使用后退箭头,然后单击“ JD Admin”链接。

      As we have logged in with “USER” Role Credentials, We cannot access this link. That’s why we saw this error message: “403 Access is denied”.

      由于我们已经使用“ USER”角色凭证登录,因此无法访问此链接。 这就是为什么我们看到以下错误消息的原因:“ 403访问被拒绝”。

    6. Now Logged and again login with ADMIN Role Credentials现在已登录,然后再次使用ADMIN角色凭据登录
    7. Username: jdadmin
      Password: jda@123

      用户名:jdadmin
      密码:jda @ 123

      This time we can access “JD Admin” Link successfully as shown below.

      这次我们可以成功访问“ JD Admin”链接,如下所示。

      Test “Logout” link to Logged out of the Application.

      测试“注销”链接以注销应用程序。

    That’s all about Spring security roles example to provide authorised access to web application pages.

    这就是关于Spring安全角色示例的全部内容,以提供对Web应用程序页面的授权访问。

    翻译自: https://www.journaldev.com/8748/spring-security-role-based-access-authorization-example

基于Spring Security角色的访问授权示例相关推荐

  1. 基于Spring安全角色的访问授权示例

    基于Spring安全角色的访问授权示例 今天我们将研究基于Spring安全角色的访问和授权示例.但是在阅读这篇文章之前,请先阅读我之前关于" Spring 4 Security MVC Lo ...

  2. 基于 Spring Security 的开源统一角色访问控制系统 URACS

    URACS Java语言开发的统一角色访问控制系统(Unified Role Access Control System),基于Spring Security 3实现的权限控制系统 程序框架版本说明: ...

  3. Spring Security MVC登录注销示例教程

    Spring Security MVC登录注销示例教程 今天我们将了解Spring Security Login Example.在阅读这篇文章之前,请先阅读我在"Spring 4 Secu ...

  4. 基于 Spring Security OAuth2和 JWT 构建保护微服务系统

    我们希望自己的微服务能够在用户登录之后才可以访问,而单独给每个微服务单独做用户权限模块就显得很弱了,从复用角度来说是需要重构的,从功能角度来说,也是欠缺的.尤其是前后端完全分离之后,我们的用户信息不一 ...

  5. 基于Spring Security 的Java SaaS应用的权限管理

    1. 概述 权限管理,一般指根据系统设置的安全规则或者安全策略,用户可以访问而且只能访问自己被授权的资源.资源包括访问的页面,访问的数据等,这在传统的应用系统中比较常见.本文介绍的则是基于Saas系统 ...

  6. 基于Spring Security与JWT实现单点登录

    基于RBAC的权限管理 RBAC(Role-Based Access Control):基于角色的访问控制 当前项目中,RBAC具体的表现为: 管理员表:ams_admin 角色表:ams_role ...

  7. 基于 Spring Security 搭建用户权限系统(二) - 自定义配置

    说明 本文的目的是如何基于 Spring Security 去扩展实现一个基本的用户权限模块, 内容会覆盖到 Spring Security 常用的配置. 文中涉及到的业务代码是不完善的, 甚至会存在 ...

  8. 基于Spring Security实现权限管理系统

    基于Spring Security实现权限管理系统 稍微复杂一点的后台系统都会涉及到用户权限管理.何谓用户权限?我的理解就是,权限就是对数据(系统的实体类)和数据可进行的操作(增删查改)的集中管理.要 ...

  9. Eurynome Cloud Athena 基于Spring Security OAuth2 的前后端分离脚手架

    Eurynome Cloud Athena 是什么? Eurynome Cloud Athena 是从 Eurynome Cloud 中提取出来的.可以独立运行的.基于OAuth2认证的.前后端分离的 ...

最新文章

  1. 怎么远程虚拟机中的mysql_如何从本地远程访问虚拟机内的Mysql服务器?
  2. C++~回溯+贪心法解决01背包问题
  3. 多态部分作业 1.按要求编写Java程序:(1)编写一个接口:InterfaceA,只含有一个方法int method(int n);
  4. shell讲解-小案例
  5. SAP CRM BCSet activation debug
  6. mysql increment by_Mysql设置auto_increment_increment和auto_increment_offset
  7. linux未知设备驱动程序,未知Android设备 - linux mint
  8. 分布式块设备复制:客户端
  9. MobileNetV1
  10. OpenGL:纹理映射bmp图像
  11. mysql存储日期 jsp_JSP+MySql的时间处理
  12. Combres库 学习小结以及部分源码分析
  13. [c++]常对象的特点
  14. C#事件-什么是事件
  15. Linux新建文件和目录的默认权限 - Umask
  16. Stale branches 设置_交通规划软件之TransCAD如何设置立交模型的步骤
  17. 超实用干货丨通过率90%的软件测试简历长什么样?
  18. 21世纪十大营销法则
  19. Java后端技术面试汇总(第一套)
  20. Python与C++语法比较--字符串篇

热门文章

  1. [转载] 朴素贝叶斯python实现预测_Python实现朴素贝叶斯分类器的方法详解
  2. [转载] 【Java核心技术卷】关于除以0的计算
  3. [转载] 面试常见问题总结
  4. Vue.js 学习笔记 四 用一,二,三的知识做个跑马灯
  5. 使用图片拉伸resizableImageWithCapInsets
  6. IOS view的圆角和阴影并存
  7. golang语言os.Stat()用法及功能
  8. pku1631 Bridging signals
  9. 线段树详解(转)这个博客很棒~
  10. Python3中的魔术方法汇总