SpringSecurity学习四----------基于不同角色跳转到不同URL
© 版权声明:本文为博主原创文章,转载请注明出处
1.项目结构
2.pom.xml
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 3 4 <modelVersion>4.0.0</modelVersion> 5 6 <groupId>org.springsecurity</groupId> 7 <artifactId>SpringSecurity</artifactId> 8 <packaging>war</packaging> 9 <version>0.0.1-SNAPSHOT</version> 10 <name>SpringSecurity Maven Webapp</name> 11 <url>http://maven.apache.org</url> 12 13 <!-- 统一版本 --> 14 <properties> 15 <jdk.version>1.7</jdk.version> 16 <spring.version>4.3.5.RELEASE</spring.version> 17 <spring.security.version>4.2.1.RELEASE</spring.security.version> 18 </properties> 19 20 <dependencies> 21 <!-- junit依赖 --> 22 <dependency> 23 <groupId>junit</groupId> 24 <artifactId>junit</artifactId> 25 <version>4.12</version> 26 <scope>test</scope> 27 </dependency> 28 <!-- spring依赖 --> 29 <dependency> 30 <groupId>org.springframework</groupId> 31 <artifactId>spring-core</artifactId> 32 <version>${spring.version}</version> 33 </dependency> 34 <dependency> 35 <groupId>org.springframework</groupId> 36 <artifactId>spring-web</artifactId> 37 <version>${spring.version}</version> 38 </dependency> 39 <dependency> 40 <groupId>org.springframework</groupId> 41 <artifactId>spring-webmvc</artifactId> 42 <version>${spring.version}</version> 43 </dependency> 44 <!-- spring security依赖 --> 45 <dependency> 46 <groupId>org.springframework.security</groupId> 47 <artifactId>spring-security-web</artifactId> 48 <version>${spring.security.version}</version> 49 </dependency> 50 <dependency> 51 <groupId>org.springframework.security</groupId> 52 <artifactId>spring-security-config</artifactId> 53 <version>${spring.security.version}</version> 54 </dependency> 55 <!-- SpringSecurity标签库依赖 --> 56 <dependency> 57 <groupId>org.springframework.security</groupId> 58 <artifactId>spring-security-taglibs</artifactId> 59 <version>${spring.security.version}</version> 60 </dependency> 61 <!-- jsp、servlet依赖 --> 62 <dependency> 63 <groupId>jstl</groupId> 64 <artifactId>jstl</artifactId> 65 <version>1.2</version> 66 </dependency> 67 <dependency> 68 <groupId>taglibs</groupId> 69 <artifactId>standard</artifactId> 70 <version>1.1.2</version> 71 </dependency> 72 <dependency> 73 <groupId>javax.servlet</groupId> 74 <artifactId>javax.servlet-api</artifactId> 75 <version>3.1.0</version> 76 </dependency> 77 </dependencies> 78 <build> 79 <finalName>SpringSecurity</finalName> 80 </build> 81 </project>
3.mvc-dispatcher-servlet.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:mvc="http://www.springframework.org/schema/mvc" 6 xsi:schemaLocation="http://www.springframework.org/schema/beans 7 http://www.springframework.org/schema/beans/spring-beans.xsd 8 http://www.springframework.org/schema/context 9 http://www.springframework.org/schema/context/spring-context.xsd 10 http://www.springframework.org/schema/mvc 11 http://www.springframework.org/schema/mvc/spring-mvc.xsd"> 12 13 <!-- 开启包扫描 --> 14 <context:component-scan base-package="org.springsecurity.*"/> 15 16 <!-- 不拦截静态资源 --> 17 <mvc:annotation-driven/> 18 <mvc:resources location="/static/" mapping="/static/**"/> 19 20 <!-- 定义视图解析器 --> 21 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 22 <property name="prefix"> 23 <value>/WEB-INF/pages/</value> 24 </property> 25 <property name="suffix"> 26 <value>.jsp</value> 27 </property> 28 </bean> 29 30 </beans>
4.web.xml
1 <web-app xmlns="http://java.sun.com/xml/ns/javaee" 2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 4 http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 5 version="3.0" metadata-complete="true"> 6 7 <!-- Spring MVC --> 8 <servlet> 9 <servlet-name>mvc-dispatcher</servlet-name> 10 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 11 <init-param> 12 <param-name>contextConfigLocation</param-name> 13 <param-value>classpath:mvc-dispatcher-servlet.xml</param-value> 14 </init-param> 15 </servlet> 16 <servlet-mapping> 17 <servlet-name>mvc-dispatcher</servlet-name> 18 <url-pattern>/</url-pattern> 19 </servlet-mapping> 20 21 <listener> 22 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 23 </listener> 24 25 <!-- 加载spring-security配置文件 --> 26 <context-param> 27 <param-name>contextConfigLocation</param-name> 28 <param-value>classpath:spring-security.xml</param-value> 29 </context-param> 30 31 <!-- spring security --> 32 <filter> 33 <filter-name>springSecurityFilterChain</filter-name> 34 <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> 35 </filter> 36 <filter-mapping> 37 <filter-name>springSecurityFilterChain</filter-name> 38 <url-pattern>/*</url-pattern> 39 </filter-mapping> 40 41 </web-app>
5.CustomSuccessHandler.java
1 package org.springsecurity.configuration; 2 3 import java.io.IOException; 4 import java.util.ArrayList; 5 import java.util.Collection; 6 import java.util.List; 7 8 import javax.servlet.ServletException; 9 import javax.servlet.http.HttpServletRequest; 10 import javax.servlet.http.HttpServletResponse; 11 12 import org.springframework.security.core.Authentication; 13 import org.springframework.security.core.GrantedAuthority; 14 import org.springframework.security.web.DefaultRedirectStrategy; 15 import org.springframework.security.web.RedirectStrategy; 16 import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler; 17 import org.springframework.stereotype.Component; 18 19 @Component 20 public class CustomSuccessHandler extends SimpleUrlAuthenticationSuccessHandler { 21 22 private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); 23 24 /** 25 * 重定向登录成功后的URL 26 */ 27 @Override 28 protected void handle(HttpServletRequest request, HttpServletResponse response, 29 Authentication authentication) throws IOException, ServletException { 30 31 String targetUrl = determineTargetUrl(authentication); 32 if(response.isCommitted()) { 33 System.out.println("重定向失败!"); 34 return ; 35 } 36 redirectStrategy.sendRedirect(request, response, targetUrl); 37 38 } 39 40 /** 41 * 根据用户角色给定URL 42 * 43 * @param authentication 44 * 用户权限信息 45 * @return 46 */ 47 private String determineTargetUrl(Authentication authentication) { 48 49 String url = ""; 50 Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities(); 51 List<String> roles = new ArrayList<String>(); 52 for(GrantedAuthority a: authorities) { 53 roles.add(a.getAuthority()); 54 } 55 if(isDba(roles)) { 56 url = "/dba"; 57 } else if(isAdmin(roles)) { 58 url = "/admin"; 59 } else if(isUser(roles)) { 60 url = "/home"; 61 } else { 62 url = "accessDenied"; 63 } 64 return url; 65 66 } 67 68 /** 69 * 判断是否具有USER角色 70 * 71 * @param roles 72 * 角色列表 73 * @return 74 */ 75 private boolean isUser(List<String> roles) { 76 77 if(roles.contains("ROLE_USER")) { 78 return true; 79 } 80 return false; 81 82 } 83 84 /** 85 * 判断是否具有ADMIN角色 86 * 87 * @param roles 88 * 角色列表 89 * @return 90 */ 91 private boolean isAdmin(List<String> roles) { 92 93 if(roles.contains("ROLE_ADMIN")) { 94 return true; 95 } 96 return false; 97 98 } 99 100 /** 101 * 判断是否具有DBA权限 102 * 103 * @param roles 104 * 角色列表 105 * @return 106 */ 107 private boolean isDba(List<String> roles) { 108 109 if(roles.contains("ROLE_DBA")) { 110 return true; 111 } 112 return false; 113 114 } 115 116 public RedirectStrategy getRedirectStrategy() { 117 return redirectStrategy; 118 } 119 120 public void setRedirectStrategy(RedirectStrategy redirectStrategy) { 121 this.redirectStrategy = redirectStrategy; 122 } 123 124 }
6.HelloController.java
1 package org.springsecurity.controller; 2 3 import javax.servlet.http.HttpServletRequest; 4 import javax.servlet.http.HttpServletResponse; 5 6 import org.springframework.security.core.Authentication; 7 import org.springframework.security.core.context.SecurityContextHolder; 8 import org.springframework.security.core.userdetails.UserDetails; 9 import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; 10 import org.springframework.stereotype.Controller; 11 import org.springframework.ui.ModelMap; 12 import org.springframework.web.bind.annotation.RequestMapping; 13 import org.springframework.web.bind.annotation.RequestMethod; 14 15 @Controller 16 public class HelloController { 17 18 @RequestMapping(value = {"/", "/home**"}, method = RequestMethod.GET) 19 public String homePage(ModelMap model) { 20 21 model.addAttribute("user", getPrincipal()); 22 return "welcome"; 23 24 } 25 26 @RequestMapping(value = "/admin", method = RequestMethod.GET) 27 public String adminPage(ModelMap model) { 28 29 model.addAttribute("user", getPrincipal()); 30 return "admin"; 31 32 } 33 34 @RequestMapping(value = "/dba", method = RequestMethod.GET) 35 public String dbaPage(ModelMap model) { 36 37 model.addAttribute("user", getPrincipal()); 38 return "dba"; 39 40 } 41 42 @RequestMapping(value = "/Access_Denied", method = RequestMethod.GET) 43 public String accessDeniedPage(ModelMap model) { 44 45 model.addAttribute("user", getPrincipal()); 46 return "accessDenied"; 47 48 } 49 50 @RequestMapping(value = "/login", method = RequestMethod.GET) 51 public String loginPage() { 52 53 return "login"; 54 55 } 56 57 @RequestMapping(value = "/logout", method = RequestMethod.GET) 58 public String logoutPage(HttpServletRequest request, HttpServletResponse response) { 59 60 Authentication auth = SecurityContextHolder.getContext().getAuthentication(); 61 if(auth != null) { 62 new SecurityContextLogoutHandler().logout(request, response, auth); 63 } 64 return "redirect:/login?logout"; 65 66 } 67 68 private String getPrincipal() { 69 70 String username = null; 71 Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); 72 if(principal instanceof UserDetails) { 73 username = ((UserDetails) principal).getUsername(); 74 } else { 75 username = principal.toString(); 76 } 77 return username; 78 79 } 80 81 }
7.login.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 5 <html> 6 <head> 7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 8 <title>登录界面</title> 9 <link href="<c:url value='/static/css/bootstrap.css'/>" rel="stylesheet" /> 10 <link href="<c:url value='/static/css/app.css'/>" rel="stylesheet" /> 11 <link href="//cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet" /> 12 </head> 13 <body> 14 <div id="mainWrapper"> 15 <div class="login-container"> 16 <div class="login-card"> 17 <div class="login-form"> 18 <c:url value="/login" var="loginUrl"/> 19 <form action="${loginUrl }" method="post" class="form-horizontal"> 20 <c:if test="${param.error != null }"> 21 <div class="alert alert-danger"> 22 <p>用户名或密码错误</p> 23 </div> 24 </c:if> 25 <c:if test="${param.logout != null }"> 26 <div class="alert alert-success"> 27 <p>注销成功</p> 28 </div> 29 </c:if> 30 <div class="input-group input-sm" style="padding-bottom: 10px;"> 31 <label class="input-group-addon" for="username"> 32 <i class="fa fa-user"></i> 33 </label> 34 <input type="text" class="form-control" id="username" name="username" 35 placeholder="请输入用户名" required> 36 </div> 37 <div class="input-group input-sm" style="padding-bottom: 10px;"> 38 <label class="input-group-addon" for="username"> 39 <i class="fa fa-lock"></i> 40 </label> 41 <input type="password" class="form-control" id="password" name="password" 42 placeholder="请输入密码" required> 43 </div> 44 <input type="hidden" name="${_csrf.parameterName }" value="${_csrf.token }"/> 45 <div class="form-actions"> 46 <input type="submit" value="登录" 47 class="btn btn-block btn-primary btn-default"> 48 </div> 49 </form> 50 </div> 51 </div> 52 </div> 53 </div> 54 </body> 55 </html>
8.app.css
1 html { 2 backgroud-color: #2F2F2F; 3 } 4 5 body, #mainWrapper { 6 height: 100%; 7 } 8 9 body, #mainWrapper, .form-control { 10 font-size: 14px!important; 11 } 12 13 #mainWrapper { 14 height: 100%; 15 padding-left: 10px; 16 padding-right: 10px; 17 padding-bottom: 10px; 18 } 19 20 #authHeaderWrapper { 21 clear: both; 22 width: 100%; 23 height: 3%; 24 padding-top: 5px; 25 padding-bottom: 5px; 26 } 27 28 .login-container { 29 margin-top: 100px; 30 background-color: floralwhite; 31 width: 40%; 32 left: 30%; 33 position: absolute; 34 } 35 36 .login-card { 37 width: 80%; 38 margin: auto; 39 } 40 41 .login-form { 42 padding: 10%; 43 }
9.bootstrap.css(bootstrap官网下载即可)
10.admin.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 5 <html> 6 <head> 7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 8 <title>Admin page</title> 9 </head> 10 <body> 11 Dear <strong>${user }</strong>, Welcome to Admin Page. 12 <a href="<c:url value='/logout'/>">Logout</a> 13 </body> 14 </html>
11.dba.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 5 <html> 6 <head> 7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 8 <title>Dba page</title> 9 </head> 10 <body> 11 Dear <strong>${user }</strong>, Welcome to DBA Page. 12 <a href="<c:url value='/logout'/>">Logout</a> 13 </body> 14 </html>
12.welcome.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 5 <html> 6 <head> 7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 8 <title>Welcome page</title> 9 </head> 10 <body> 11 Dear <strong>${user }</strong>, Welcome to Welcome Page. 12 <a href="<c:url value='/logout'/>">Logout</a> 13 </body> 14 </html>
13.accessDenied.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 5 <html> 6 <head> 7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 8 <title>AccessDenied page</title> 9 </head> 10 <body> 11 Dear <strong>${user }</strong>, You are not authorized to access this page. 12 <a href="<c:url value='/logout'/>">Logout</a> 13 </body> 14 </html>
14.效果预览
14.1 登录界面
14.2 登录失败
14.3 admin登录
14.4 dba登录
14.4 user登录
14.4 user登录后,通过url访问admin
14.5 注销
参考:http://www.yiibai.com/spring-security/spring-security-4-role-based-login-example.html
© 版权声明:本文为博主原创文章,转载请注明出处