今天,我们将研究spring安全基于角色的访问和授权示例。然而,在阅读这篇文章之前,请仔细阅读我之前关于“;Spring4安全MVC登录注销示例了解一些关于Spring4安全性的基本知识。
Spring安全角色
在这篇文章中,我们将讨论如何在springweb应用程序中定义、使用和管理Spring Security角色,如“;USER”;,“;ADMIN”。
像我以前的文章一样,这个post示例还使用spring4mvc安全性和内存存储以及Spring Java配置特性来开发应用程序。这意味着我们不会使用web.xml文件文件,也不写哪怕一行springxml配置。
我们将使用“;内存存储”;选项来存储和管理用户凭据。
我们将使用spring4.0.2.RELEASE、springsts3.7suiteide、springtcserver3.1withjava1.8和Maven构建工具来开发这个示例。
- 使用以下详细信息在springsts套件中创建一个简单的springwebmaven”;项目。
- 使用相同的pom.xml文件文件从我以前的文章与以下变化
- 使用我上一篇文章中的所有Java和JSP文件。我们将在这里只讨论更新或新添加的内容。
- 更新登录安全配置.java文件以配置用户角色,如“;用户”;和“;管理员”;。
- 在configureGlobal()方法中,我们添加了两个用户:一个用户具有“;角色#user”;角色;另一个用户同时具有“;角色”;和“;角色”;角色的用户。这意味着第二个用户将作为管理员用户。像这样,我们可以配置任意数量的用户和角色。
- 我们可以使用authorities(ROLE)或roles(ROLE)方法来配置应用程序中的角色。
- authorities()和roles()方法之间的区别:
- authorities()需要完整的角色名,如“roleu USER”
- roles()需要像“USER”这样的角色名。它将自动向这个“用户”角色名添加“角色”值。
- 我们在配置方法中定义了不同的Access()角色。
- 更新登录控制器.java定义新的URL访问路径的控制器文件,如下所示。
- “;/userPage”;由用户角色用于访问和执行正常的用户活动。
- “;/adminPage”;由管理员角色用于访问和执行管理员用户活动。管理员角色也可以访问“;/userPage”;URL。
- 更新主页.jsp提供用户和管理员角色特定活动的文件。
- JD用户:用户和管理员都可以访问
- JD Admin:只有“;管理员和#8221;角色都可以访问
- 添加新的管理页面.jsp文件用作“;管理员”;角色的主页。
- 添加新的用户页.jsp用作“;用户”;角色的主页的文件。
- 最终项目结构如下:
项目名称:SpringMVCSecruityMainRolesApp
<artifactId>SpringMVCSecruityMavenRolesApp</artifactId>
<build>
<finalName>SpringMVCSecruityMavenRolesApp</finalName>
</build>
</project>
登录安全配置.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 {
@Autowired
public 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");
}
@Override
protected 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");
}
}
代码说明
antMatchers("/homePage")
.access("hasRole("ROLE_USER") or hasRole("ROLE_ADMIN")")
此代码片段配置了“;/homePage”;可用于用户和管理员角色。
.antMatchers("/userPage").access("hasRole("ROLE_USER")")
.antMatchers("/adminPage").access("hasRole("ROLE_ADMIN")")
此代码段配置为“;/userPage”;只能由“;用户”;角色访问,”;/adminPage”;只能由“;管理员”;角色访问。
如果其他角色访问这些页面,我们将得到access&Š8220;403 access is Denied&8221;错误消息。
登录控制器.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;
}
}
代码说明除了前面的post示例之外,我们还添加了两个新的url。
主页.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>
在这里,我们在顶部框架添加了三个类似菜单的选项。我在上一篇文章中已经讨论过注销。
新的两个链接是:
注:-在实时应用程序中,我们将只显示“;JD用户”;链接到“;用户”;角色和隐藏“;JD管理”;链接。为了测试“;用户”;角色是否可以访问它并查看确切的错误消息,我们没有隐藏此链接。
管理页面.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>
用户页.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>
我们现在已经完成了我们的应用程序开发。现在是时候查看我们的项目最终结构并测试应用程序了。
Spring安全角色示例应用程序测试
- 右键单击springstside中的Project并选择“;runas>>runonserver8221;选项。
- 单击“;登录到JournalDEV”;链接。现在您在登录页面。
- 第一次使用“;用户和角色凭据登录:
- 现在登录并再次使用管理员角色凭据登录
它将访问默认的应用程序欢迎页面,如下所示:
用户名:jduser密码:jdu@123
现在我们将看到带有3个菜单选项的应用程序主页:JD用户和JD管理员;。
单击“;JD用户”;链接。由于我们已使用“;用户”;角色凭据登录到应用程序,因此我们可以访问此链接,如下所示。
只需在springstside中使用backword箭头,这次单击“;JD Admin”;链接。
由于我们已使用“;用户”;角色凭据登录,因此无法访问此链接。这就是我们看到此错误消息的原因:403访问被拒绝;。
用户名:jdadmin密码:jda@123
这次我们可以成功访问“;JD Admin”;链接,如下所示。
测试并链接注销应用程序。
这就是Spring安全角色示例的全部内容,它提供对web应用程序页面的授权访问。