SpringSecurity学习四----------基于不同角色跳转到不同URL
© 版权声明:本文为博主原创文章,转载请注明出处
1.项目结构
2.pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.springsecurity</groupId>
<artifactId>SpringSecurity</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>SpringSecurity Maven Webapp</name>
<url>http://maven.apache.org</url> <!-- 统一版本 -->
<properties>
<jdk.version>1.7</jdk.version>
<spring.version>4.3.5.RELEASE</spring.version>
<spring.security.version>4.2.1.RELEASE</spring.security.version>
</properties> <dependencies>
<!-- junit依赖 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- spring依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring security依赖 -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring.security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring.security.version}</version>
</dependency>
<!-- SpringSecurity标签库依赖 -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>${spring.security.version}</version>
</dependency>
<!-- jsp、servlet依赖 -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
</dependencies>
<build>
<finalName>SpringSecurity</finalName>
</build>
</project>
3.mvc-dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 开启包扫描 -->
<context:component-scan base-package="org.springsecurity.*"/> <!-- 不拦截静态资源 -->
<mvc:annotation-driven/>
<mvc:resources location="/static/" mapping="/static/**"/> <!-- 定义视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean> </beans>
4.web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0" metadata-complete="true"> <!-- Spring MVC -->
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:mvc-dispatcher-servlet.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping> <listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <!-- 加载spring-security配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-security.xml</param-value>
</context-param> <!-- spring security -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> </web-app>
5.CustomSuccessHandler.java
package org.springsecurity.configuration; import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List; import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component; @Component
public class CustomSuccessHandler extends SimpleUrlAuthenticationSuccessHandler { private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); /**
* 重定向登录成功后的URL
*/
@Override
protected void handle(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException { String targetUrl = determineTargetUrl(authentication);
if(response.isCommitted()) {
System.out.println("重定向失败!");
return ;
}
redirectStrategy.sendRedirect(request, response, targetUrl); } /**
* 根据用户角色给定URL
*
* @param authentication
* 用户权限信息
* @return
*/
private String determineTargetUrl(Authentication authentication) { String url = "";
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
List<String> roles = new ArrayList<String>();
for(GrantedAuthority a: authorities) {
roles.add(a.getAuthority());
}
if(isDba(roles)) {
url = "/dba";
} else if(isAdmin(roles)) {
url = "/admin";
} else if(isUser(roles)) {
url = "/home";
} else {
url = "accessDenied";
}
return url; } /**
* 判断是否具有USER角色
*
* @param roles
* 角色列表
* @return
*/
private boolean isUser(List<String> roles) { if(roles.contains("ROLE_USER")) {
return true;
}
return false; } /**
* 判断是否具有ADMIN角色
*
* @param roles
* 角色列表
* @return
*/
private boolean isAdmin(List<String> roles) { if(roles.contains("ROLE_ADMIN")) {
return true;
}
return false; } /**
* 判断是否具有DBA权限
*
* @param roles
* 角色列表
* @return
*/
private boolean isDba(List<String> roles) { if(roles.contains("ROLE_DBA")) {
return true;
}
return false; } public RedirectStrategy getRedirectStrategy() {
return redirectStrategy;
} public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy;
} }
6.HelloController.java
package org.springsecurity.controller; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; @Controller
public class HelloController { @RequestMapping(value = {"/", "/home**"}, method = RequestMethod.GET)
public String homePage(ModelMap model) { model.addAttribute("user", getPrincipal());
return "welcome"; } @RequestMapping(value = "/admin", method = RequestMethod.GET)
public String adminPage(ModelMap model) { model.addAttribute("user", getPrincipal());
return "admin"; } @RequestMapping(value = "/dba", method = RequestMethod.GET)
public String dbaPage(ModelMap model) { model.addAttribute("user", getPrincipal());
return "dba"; } @RequestMapping(value = "/Access_Denied", method = RequestMethod.GET)
public String accessDeniedPage(ModelMap model) { model.addAttribute("user", getPrincipal());
return "accessDenied"; } @RequestMapping(value = "/login", method = RequestMethod.GET)
public String loginPage() { return "login"; } @RequestMapping(value = "/logout", method = RequestMethod.GET)
public String logoutPage(HttpServletRequest request, HttpServletResponse response) { Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if(auth != null) {
new SecurityContextLogoutHandler().logout(request, response, auth);
}
return "redirect:/login?logout"; } private String getPrincipal() { String username = null;
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if(principal instanceof UserDetails) {
username = ((UserDetails) principal).getUsername();
} else {
username = principal.toString();
}
return username; } }
7.login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登录界面</title>
<link href="<c:url value='/static/css/bootstrap.css'/>" rel="stylesheet" />
<link href="<c:url value='/static/css/app.css'/>" rel="stylesheet" />
<link href="//cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet" />
</head>
<body>
<div id="mainWrapper">
<div class="login-container">
<div class="login-card">
<div class="login-form">
<c:url value="/login" var="loginUrl"/>
<form action="${loginUrl }" method="post" class="form-horizontal">
<c:if test="${param.error != null }">
<div class="alert alert-danger">
<p>用户名或密码错误</p>
</div>
</c:if>
<c:if test="${param.logout != null }">
<div class="alert alert-success">
<p>注销成功</p>
</div>
</c:if>
<div class="input-group input-sm" style="padding-bottom: 10px;">
<label class="input-group-addon" for="username">
<i class="fa fa-user"></i>
</label>
<input type="text" class="form-control" id="username" name="username"
placeholder="请输入用户名" required>
</div>
<div class="input-group input-sm" style="padding-bottom: 10px;">
<label class="input-group-addon" for="username">
<i class="fa fa-lock"></i>
</label>
<input type="password" class="form-control" id="password" name="password"
placeholder="请输入密码" required>
</div>
<input type="hidden" name="${_csrf.parameterName }" value="${_csrf.token }"/>
<div class="form-actions">
<input type="submit" value="登录"
class="btn btn-block btn-primary btn-default">
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
8.app.css
html {
backgroud-color: #2F2F2F;
} body, #mainWrapper {
height: 100%;
} body, #mainWrapper, .form-control {
font-size: 14px!important;
} #mainWrapper {
height: 100%;
padding-left: 10px;
padding-right: 10px;
padding-bottom: 10px;
} #authHeaderWrapper {
clear: both;
width: 100%;
height: 3%;
padding-top: 5px;
padding-bottom: 5px;
} .login-container {
margin-top: 100px;
background-color: floralwhite;
width: 40%;
left: 30%;
position: absolute;
} .login-card {
width: 80%;
margin: auto;
} .login-form {
padding: 10%;
}
9.bootstrap.css(bootstrap官网下载即可)
10.admin.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Admin page</title>
</head>
<body>
Dear <strong>${user }</strong>, Welcome to Admin Page.
<a href="<c:url value='/logout'/>">Logout</a>
</body>
</html>
11.dba.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Dba page</title>
</head>
<body>
Dear <strong>${user }</strong>, Welcome to DBA Page.
<a href="<c:url value='/logout'/>">Logout</a>
</body>
</html>
12.welcome.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Welcome page</title>
</head>
<body>
Dear <strong>${user }</strong>, Welcome to Welcome Page.
<a href="<c:url value='/logout'/>">Logout</a>
</body>
</html>
13.accessDenied.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>AccessDenied page</title>
</head>
<body>
Dear <strong>${user }</strong>, You are not authorized to access this page.
<a href="<c:url value='/logout'/>">Logout</a>
</body>
</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
SpringSecurity学习四----------基于不同角色跳转到不同URL的更多相关文章
- SpringSecurity学习之基于数据库的用户认证
SpringSecurity给我们提供了一套最基本的认证方式,可是这种方式远远不能满足大多数系统的需求.不过好在SpringSecurity给我们预留了许多可扩展的接口给我们,我们可以基于这些接口实现 ...
- TCP/IP协议学习(四) 基于C# Socket的Web服务器---静态资源处理
目录 1. C# Socket通讯 2. HTTP 解析引擎 3. 资源读取和返回 4. 服务器测试和代码下载 Web服务器是Web资源的宿主,它需要处理用户端浏览器的请求,并指定对应的Web资源返回 ...
- {django模型层(二)多表操作}一 创建模型 二 添加表记录 三 基于对象的跨表查询 四 基于双下划线的跨表查询 五 聚合查询、分组查询、F查询和Q查询
Django基础五之django模型层(二)多表操作 本节目录 一 创建模型 二 添加表记录 三 基于对象的跨表查询 四 基于双下划线的跨表查询 五 聚合查询.分组查询.F查询和Q查询 六 xxx 七 ...
- Android JNI学习(四)——JNI的常用方法的中文API
本系列文章如下: Android JNI(一)——NDK与JNI基础 Android JNI学习(二)——实战JNI之“hello world” Android JNI学习(三)——Java与Nati ...
- SpringSecurity学习三----------通过Security标签库简单显示视图
© 版权声明:本文为博主原创文章,转载请注明出处 1.项目结构 2.pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0& ...
- day 83 Vue学习四之过滤器、钩子函数、路由、全家桶等
Vue学习四之过滤器.钩子函数.路由.全家桶等 本节目录 一 vue过滤器 二 生命周期的钩子函数 三 vue的全家桶 四 xxx 五 xxx 六 xxx 七 xxx 八 xxx 一 Vue的过滤 ...
- Python基础学习四
Python基础学习四 1.内置函数 help()函数:用于查看内置函数的用途. help(abs) isinstance()函数:用于判断变量类型. isinstance(x,(int,float) ...
- jsp九大内置对象、四种作用域、跳转方式
jsp有四种属性范围: page -> 页面级别,显然只有在一个页面内可用. request -> 请求级别 服务器跳转,一次请求之后消失. session -> 会话级别 客户端跳 ...
- struts2 Result Type四个常用转跳类型
Result的四个常用转跳类型分别为 Dispatcher 用来转向页面,是Struts的默认形式 Redirect 重定向到一个URL Chain 用来处理Action链 RedirectAc ...
随机推荐
- MVC5 ModelState
ModelState.IsValid 总是false的原因 在做添加功能的时候,发现这个IsValid总是false,这个是它自己的验证机制. 因为是添加,就是说主键是自增的,添加的时候不需要指定这个 ...
- (3)WPF 布局
一.布局原则 二.布局过程 三.布局容器 核心布局面板 布局属性
- Python的程序结构[1] -> 方法/Method[3] -> 魔术方法 __getattr__ 与代理模式
__getattr__ 方法 __getattr__ 方法当对象调用内部属性(包括方法等)且未找到对应属性的时候会调用的特殊方法.利用这一特性,可是对函数实现一个代理模式. __getattr__方法 ...
- 洛谷——P1991 无线通讯网
P1991 无线通讯网 题目描述 国防部计划用无线网络连接若干个边防哨所.2 种不同的通讯技术用来搭建无线网络: 每个边防哨所都要配备无线电收发器:有一些哨所还可以增配卫星电话. 任意两个配备了一条卫 ...
- mac-command-line-doing
创建文件夹 mkdir myDirectory 新建文件 touch a.html 编辑文件 vim a.html 删除文件 rm a.html 删除整个文件夹 rm -rf myDirectory ...
- 3.非标准的NDEF格式数据解析--IsoDep
1.使用目的:正常开发是针对NDEF格式数据进行开发,但实际情况并非如此,以厦门公交卡为例,厦门公交卡保存的是非NDEF格式数据.其类型是IsoDep类型. 2.非标准的NDEF格式数据流程:当厦门公 ...
- Jenkins的安装方法(Windows/Linux)
前提:要确定本机全部安装了JDK 一.先说官方的安装方式 打开网址:https://wiki.jenkins-ci.org/display/JENKINS/Installing+Jenkins,会留意 ...
- 使用TensorFlow实现神经网络的介绍
http://www.toutiao.com/i6414029277641048577/
- ASIHTTPRequest框架使用总结系列之阿堂教程3(异步请求)
在上一节中,阿堂和网友们分享了ASIHTTPRequest框架对于get,post的同步请求方式.很显然,如果网速比较慢,查询的时候会一直很黑屏,直到请求结束界面才出现结果,这样用户体验肯定很不好了. ...
- andriod 剪贴板操作
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=&quo ...