本文以Spring Boot Thymeleaf为例,用Spring Security 保护 /admin 和 /user 页面

本例涉及的技术:

1. Spring Boot 1.5.6.REALEASE

2. Spring 4.3.8.REALEASE

3. Spring Security 4.2.2

4. Thymeleaf 2.2.5.REALEASE

5. Tomcat embed 8.5.14

6. Maven 3

7. Java 8

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/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>org.thinkingingis</groupId><artifactId>spring-boot-security</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging><name>spring-boot-security</name><url>http://maven.apache.org</url><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.6.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><java.version>1.8</java.version></properties><dependencies><!-- Spring Security --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><dependency><groupId>org.thymeleaf.extras</groupId><artifactId>thymeleaf-extras-springsecurity4</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><optional>true</optional></dependency><dependency><groupId>org.webjars</groupId><artifactId>bootstrap</artifactId><version>3.3.7</version></dependency></dependencies><build><plugins><!-- Package as an executable jar/war --><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

3. Spring Security

3.1 继承自WebSecurityConfigurerAdapter 同时在configure方法中定义了安全角色

对于admin(管理员)角色来说:

a. 可以访问/admin.html页面

b. 不能访问/user.html页面,并重定向到403页面

对于user(用户)角色来说:

a.可以访问/user.html页面

b.不能访问/admin.html页面,并重定向到403页面

SpringSecurityConfig.java

@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredprivate AccessDeniedHandler accessDeniedHandler;protected void configure(HttpSecurity http) throws Exception{http.csrf().disable().authorizeRequests().antMatchers("/", "/home", "/about").permitAll().antMatchers("/admin/**").hasAnyRole("ADMIN").antMatchers("/user/**").hasAnyRole("USER").anyRequest().authenticated().and().formLogin().loginPage("/login").permitAll().and().logout().permitAll().and().exceptionHandling().accessDeniedHandler(accessDeniedHandler);}//create two users admin and user@Autowiredpublic void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{auth.inMemoryAuthentication().withUser("user").password("password").roles("USER").and().withUser("admin").password("password").roles("ADMIN");}}

3.2 定义403无权限访问的处理,重定向到/403页面

MyAccessDeniedHandler.java

@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {private static Logger logger = LoggerFactory.getLogger(MyAccessDeniedHandler.class);@Overridepublic void handle( HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e)throws IOException, ServletException {Authentication auth = SecurityContextHolder.getContext().getAuthentication();if(auth != null) {logger.info("User '" + auth.getName() + "' attempted to access the protected URL: " + httpServletRequest.getRequestURI());}httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/403");}}

4. Spring Boot

4.1 DefaultController.java

定义http请求和视图名

@Controller
public class DefaultController {@GetMapping("/")public String index() {return "/home";}@GetMapping("/home")public String home() {return "/home";}@GetMapping("/admin")public String admin() {return "/admin";}@GetMapping("/user")public String user() {return "/user";}@GetMapping("/about")public String about() {return "/about";}@GetMapping("/login")public String login() {return "/login";}@GetMapping("/403")public String error403() {return "/error/403";}
}

4.2 Spring Boot的启动程序

SpringBootWebApplication.java

@SpringBootApplication
public class SpringBootWebApplication {public static void main(String[] args) throws Exception {SpringApplication.run(SpringBootWebApplication.class, args);}}

5.Thymeleaf及静态资源

对于 thymeleaf 文件,均放到 src/main/resources/templates/目录下

header.html

<html xmlns:th="http://www.thymeleaf.org">
<head><div th:fragment="header-css"><link rel="stylesheet" type="text/css" href="webjars/bootstrap/3.3.7/css/bootstrap.min.css" /><link rel="stylesheet" th:href="@{/main.css}"/></div>
</head>
<body>
<div th:fragment="header"><!-- this is header --><nav class="navbar navbar-inverse"><div class="container"><div class="navbar-header"><a class="navbar-brand" th:href="@{/}">ThinkingInGIS</a></div><div id="navbar" class="collapse navbar-collapse"><ul class="nav navbar-nav"><li class="active"><a th:href="@{/}">Home</a></li></ul></div></div></nav>
</div>

footer.html

<html xmlns="http://www.w3.org/1999/xhtml"xmlns:th="http://www.thymeleaf.org"xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
</head>
<body>
<div th:fragment="footer"><div class="container"><footer><!-- this is footer -->© 2017 ThinkingInGIS<span sec:authorize="isAuthenticated()">| Logged user: <span sec:authentication="name"></span> |Roles: <span sec:authentication="principal.authorities"></span> |<a th:href="@{/logout}">登出</a></span></footer></div>
</div>
</body>
</html>

home.html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head><title>Spring Boot Thymeleaf + Spring Security</title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/><link rel="stylesheet" type="text/css" href="webjars/bootstrap/3.3.7/css/bootstrap.min.css"/><link rel="stylesheet" type="text/css" th:href="@{/main.css}"/><script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
</head>
<body>
<div th:replace="fragments/header :: header"></div>
<div class="container"><div class="starter-template"><h1>Spring Boot + Thymeleaf + Spring Security 示例</h1><h2>1. 打开 <a th:href="@{/admin}">管理员页面 (受 Spring Security 保护, 需要管理员权限)</a></h2><h2>2. 打开 <a th:href="@{/user}">用户页面 (受 Spring Security 保护, 需要用户权限)</a></h2><h2>3. 打开 <a th:href="@{/about}">游客页面</a></h2></div>
</div>
<div th:replace="fragments/footer :: footer"></div>
</body>
</html>

admin.html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head><link rel="stylesheet" type="text/css" href="webjars/bootstrap/3.3.7/css/bootstrap.min.css"/><script type="text/javascript" src="webjars/jquery/2.2.4/jquery.min.js"></script>
</head>
<body><div class="container"><div class="starter-template"><h1>GORGEOUS! 管理员页面 (受 Spring Security 保护, 需要管理员权限)</h1><h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1><form th:action="@{/logout}" method="post"><input type="submit" class="btn btn-danger" value="登出"/></form></div>
</div>
<div class="container"><footer><p>© <a >ThinkingInGIS</a> 2017</p></footer>
</div>
</body>
</html>

user.html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head><link rel="stylesheet" type="text/css" href="webjars/bootstrap/3.3.7/css/bootstrap.min.css"/><script type="text/javascript" src="webjars/jquery/2.2.4/jquery.min.js"></script>
</head>
<body><div class="container"><div class="starter-template"><h1>普通用户页面 (受 Spring Security 保护, 需要用户权限)</h1><h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1><form th:action="@{/logout}" method="post"><input type="submit" class="btn btn-danger" value="登出"/></form></div>
</div>
<div class="container"><footer><p>© <a >ThinkingInGIS</a> 2017</p></footer>
</div>
</body>
</html>

about.html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head><link rel="stylesheet" type="text/css" href="webjars/bootstrap/3.3.7/css/bootstrap.min.css"/><script type="text/javascript" src="webjars/jquery/2.2.4/jquery.min.js"></script>
</head>
<body><div class="container"><div class="starter-template"><h1>游客页面 无需登录</h1></div>
</div>
<div class="container"><footer><p>© <a >ThinkingInGIS</a> 2017</p></footer>
</div>
</body>
</html>

login.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head><link rel="stylesheet" type="text/css" href="webjars/bootstrap/3.3.7/css/bootstrap.min.css"/><script type="text/javascript" src="webjars/jquery/2.2.4/jquery.min.js"></script>
</head>
<body>
<div th:replace="fragments/header :: header"></div>
<div class="container"><div class="row" style="margin-top:20px"><div class="col-xs-12 col-sm-8 col-md-6 col-sm-offset-2 col-md-offset-3"><form th:action="@{/login}" method="post"><fieldset><h1>登录</h1><div th:if="${param.error}"><div class="alert alert-danger">Invalid username and password.</div></div><div th:if="${param.logout}"><div class="alert alert-info">You have been logged out.</div></div><div class="form-group"><input type="text" name="username" id="username" class="form-control input-lg"placeholder="用户名" required="true" autofocus="true"/></div><div class="form-group"><input type="password" name="password" id="password" class="form-control input-lg"placeholder="密码" required="true"/></div><div class="row"><div class="col-xs-6 col-sm-6 col-md-6"><input type="submit" class="btn btn-lg btn-primary btn-block" value="登录"/></div><div class="col-xs-6 col-sm-6 col-md-6"></div></div></fieldset></form></div></div></div><div th:replace="fragments/footer :: footer"></div></body>
</html>

403.html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/><title>403</title><link rel="stylesheet" type="text/css" href="webjars/bootstrap/3.3.7/css/bootstrap.min.css"/><script type="text/javascript" src="webjars/jquery/2.2.4/jquery.min.js"></script>
</head>
<body>
<div th:replace="fragments/header :: header"></div>
<div class="container"><div class="starter-template"><h1>403 - 没有访问权限</h1><div th:inline="text">Hello '[[${#httpServletRequest.remoteUser}]]',你没有权限访问此页面.</div></div>
</div>
<!-- /.container -->
<div th:replace="fragments/footer :: footer"></div></body>
</html>

6.启动程序

6.1 /admin 下面的需要用admin用户登录才能访问

6.2 启动程序,访问 http://localhost:8080/

6.3 访问http://localhost:8080/admin 会被重定向到 http://localhost:8080/login

6.4 当输入无效的用户名和密码后...

6.5 用户名输入admin  密码输入 password 登录,页面会进入到 http://localhost:8080/admin

6.6 输入http://localhost:8080/user 会被重定向到 http://localhost:8080/403 最下面显示了登录的角色及用户名

6.7 点击 登出 会重定向到http://localhost:8080/login?logout

最后,自己试试 用 'user' 访问admin页面可看会有上面结果吧。

源码地址:https://github.com/ThinkingInGIS/spring-boot-security.git

至此,一个简单的spring boot + thymeleaf + spring security 程序 就搭建好了。

(如遇到问题,请留言给作者,以便共同探讨gis知识。thinkingingis@qq.com)

更多干货 欢迎关注微信公众号: ThinkingInGIS

如果觉得本文对你有帮助,是可以赞赏作者的哦

Spring Boot + Spring Security + Thymeleaf 举例相关推荐

  1. spring boot(四):thymeleaf使用详解

    spring boot(四):thymeleaf使用详解 在上篇文章springboot(二):web综合开发中简单介绍了一下thymeleaf,这篇文章将更加全面详细的介绍thymeleaf的使用. ...

  2. 【Bug档案01】Spring Boot的控制器+thymeleaf模板 -使用中出现静态资源加载路径不当的问题 -解决时间:3h

    [Bug档案01]Spring Boot的控制器+thymeleaf模板 -使用中出现静态资源加载路径不当的问题 -解决时间:3h 参考文章: (1)[Bug档案01]Spring Boot的控制器+ ...

  3. spring boot 学习(二)spring boot 框架整合 thymeleaf

    spring boot 框架整合 thymeleaf spring boot 的官方文档中建议开发者使用模板引擎,避免使用 JSP.因为若一定要使用 JSP 将无法使用. 注意:本文主要参考学习了大神 ...

  4. springboot jwt token前后端分离_基于Spring Boot+Spring Security+JWT+Vue前后端分离的开源项目...

    一.前言 最近整合Spring Boot+Spring Security+JWT+Vue 完成了一套前后端分离的基础项目,这里把它开源出来分享给有需要的小伙伴们 功能很简单,单点登录,前后端动态权限配 ...

  5. Spring Boot + Spring Security + JWT + 微信小程序登录

    Spring Boot + Spring Security + JWT + 微信小程序登录整合教程 参考文章 文章目录 整合思想 整合步骤 1. AuthenticationToken 2. Auth ...

  6. Spring Boot系列之Thymeleaf模板布局

    PS:原文首发于微信公众号:躬行之(jzman-blog) 前面几篇文章尝试了接口开发.Thymeleaf 模板及其常用语法,阅读本文之前可以阅读前面几篇: Spring Boot系列之开发一个接口 ...

  7. 8.Spring Boot中使用thymeleaf

    Spring Boot中使用thymeleaf Spring Boot支持FreeMarker.Groovy.Thymeleaf和Mustache四种模板解析引擎,官方推荐使用Thymeleaf. s ...

  8. Spring Boot+Spring Security+JWT 实现token验证

    Spring Boot+Spring Security+JWT 实现token验证 什么是JWT? JWT的工作流程 JWT的主要应用场景 JWT的结构 SpringBoot+Spring Secur ...

  9. Spring Boot+Spring Cloud实现itoken项目

    itoken项目简介 开发环境 操作系统: Windows 10 Enterprise 开发工具: Intellij IDEA 数据库: MySql 5.7.22 Java SDK: Oracle J ...

  10. Spring Boot Spring MVC 异常处理的N种方法

    默认行为 根据Spring Boot官方文档的说法: For machine clients it will produce a JSON response with details of the e ...

最新文章

  1. Entity Framework简介
  2. bzoj1051 [HAOI2006]受欢迎的牛 tarjan缩点
  3. JavaFX图表(七)之散点图
  4. onkeydown为什么会无限回调_为什么投资者总喜欢在股票下跌时买入?只有傻瓜才能在股市里挣钱...
  5. Qt4_使用预定义模型
  6. 《流畅的Python》读书笔记——Python文本和字节序列
  7. DataGridView 动态绑定列
  8. 第二篇:基于小米手机的,第三方recovery教学
  9. openwrt编译qca驱动不成功。gcc -isystem问题。
  10. 全国勘察设计注册暖通空调工程师专业基础考试大纲(送审稿)
  11. sever企业版密钥 sql_SQL Server2016企业版 附全版本key(转载)
  12. ADO的七个对象详情解读
  13. 软件工程第五次作业-项目选题
  14. android钟表,Android打造属于自己的时间钟表
  15. oracle重做日志论文,Oracle重做日志文件相关概念
  16. python| requests 访问 https网站
  17. 三合一剪弦器怎么用_吉他换弦时多余的弦用什么工具剪掉?
  18. 交换机当做路由器使用的两种方法
  19. 惊魂一小时:全国域名解析首遭大规模污染
  20. 容器集群k8s从入门到精通实战第一天 kubernetes集群简介及其实例

热门文章

  1. [转]侯捷对进入IT行业的年轻人的建议
  2. DM中一个热门问题的解惑
  3. uvalive4835(模拟)
  4. GeoHash -------寻找附近人
  5. 利用Fiddler模拟通过Dynamics 365的OAuth 2 Client Credentials认证后调用Web API
  6. git stash封存分支 以及关于开发新功能的处理
  7. C#设计模式(1)——单例模式
  8. poj 1092 Farmland (Geometry)
  9. 用filter实现web程序的统一认证
  10. httpclient 学习