SpringBoot 整合 SpringSecurity;

用户认证和授权、注销及权限控制、记住我和登录页面定制。

SpringSecurity(安全)

搭建环境

版本: 先使用 SpringBoot 2.2.4.RELEASE

后面会切换到 SpringBoot 2.0.9.RELEASE

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-web</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-test</artifactId>
  8. <scope>test</scope>
  9. <exclusions>
  10. <exclusion>
  11. <groupId>org.junit.vintage</groupId>
  12. <artifactId>junit-vintage-engine</artifactId>
  13. </exclusion>
  14. </exclusions>
  15. </dependency>
  16. <!--thymeleaf模板-->
  17. <dependency>
  18. <groupId>org.thymeleaf</groupId>
  19. <artifactId>thymeleaf-spring5</artifactId>
  20. </dependency>
  21. <dependency>
  22. <groupId>org.thymeleaf.extras</groupId>
  23. <artifactId>thymeleaf-extras-java8time</artifactId>
  24. </dependency>

资料下载地址

编写网页对应的Controller:

  1. package com.rainszj.controller;
  2. import org.springframework.stereotype.Controller;
  3. import org.springframework.web.bind.annotation.PathVariable;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5. @Controller
  6. public class RouterController {
  7. @RequestMapping({"/", "/index"})
  8. public String index() {
  9. return "index";
  10. }
  11. @RequestMapping("/toLogin")
  12. public String toLogin() {
  13. return "views/login";
  14. }
  15. @RequestMapping("/level1/{id}")
  16. public String level1(@PathVariable("id") int id) {
  17. System.out.println(id);
  18. return "views/level1/" + id;
  19. }
  20. @RequestMapping("/level2/{id}")
  21. public String level2(@PathVariable("id") int id) {
  22. return "views/level2/" + id;
  23. }
  24. @RequestMapping("/level3/{id}")
  25. public String level3(@PathVariable("id") int id) {
  26. return "views/level3/" + id;
  27. }
  28. }

测试的时候,关闭 thymeleaf 的缓存

  1. spring.thymeleaf.cache=false

访问:http://localhost:8080,测试是否可以成功跳转视图!

简介

Spring Security 是针对Spring项目的安全框架,也是Spring Boot 底层安全模块默认的技术选型,它可以实现强大的 Web安全控制,对于安全控制,我们仅需要引入 spring-boot-starter-security 模块,进行少量配置,即可实现强大的安全管理!

记住几个类:

  • WebSecurityConfigurerAdapter:自定义 Security 策略
  • AuthenticationManagerBuilder:自定义认证策略
  • @EnableWebSecurity:开启 WebSecurity模式

Spring Security 的两个主要目标是"认证" 和 "授权"(访问控制)

认证(Authentication )

授权( Authorization)

这个概念是通用的,而不是只在 Spring Security 中存在。

Spring Security官网

官方文档

使用

要使用它只需要在Spring Boot中导入Spring Security 的启动器:

  1. <!--security-->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-security</artifactId>
  5. </dependency>

导入依赖后,我们来看看 @EnableWebSecurity这个注解

  1. @Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME)
  2. @Target(value = { java.lang.annotation.ElementType.TYPE })
  3. @Documented
  4. @Import({ WebSecurityConfiguration.class,
  5. SpringWebMvcImportSelector.class,
  6. OAuth2ImportSelector.class })
  7. @EnableGlobalAuthentication
  8. @Configuration
  9. public @interface EnableWebSecurity {
  10. /**
  11. * Controls debugging support for Spring Security. Default is false.
  12. * @return if true, enables debug support with Spring Security
  13. */
  14. boolean debug() default false;
  15. }

从源码中看出,加了@EnableWebSecurity注解的类本质上也是一个配置类!

从注释中,可以看到它的用法:

要使用 Spring Security,只需要 添加 @EnableWebSecurity,并让该类继承WebSecurityConfigurerAdapter,重写其中的 一些configure()方法即可

用户认证和授权

我们新建一个文件夹:config,编写一个类:SecurityConfig

  1. @EnableWebSecurity
  2. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  3. // 授权
  4. @Override
  5. protected void configure(HttpSecurity http) throws Exception {
  6. // 链式编程
  7. // 请求权限的规则
  8. http.authorizeRequests()
  9. .antMatchers("/").permitAll()
  10. .antMatchers("/level1/**").hasRole("vip1")
  11. .antMatchers("/level2/**").hasRole("vip2")
  12. .antMatchers("/level3/**").hasRole("vip3")
  13. .and()
  14. .formLogin();
  15. // 没有权限默认会到登录页面,需要开启登录的页面
  16. // 默认会跳到 /login 请求中
  17. // http.formLogin();
  18. }
  19. /**
  20. * 认证
  21. * 需要密码编码:PasswordEncoder
  22. * 在 SpringSecurity 5.0+ 中新增了很多加密方法
  23. */
  24. @Override
  25. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  26. // 这些数据正常应该从数据库中读取
  27. auth.inMemoryAuthentication()
  28. .withUser("rainszj").password("123456").roles("vip2", "vip3")
  29. .and()
  30. .withUser("root").password("123456").roles("vip1", "vip2", "vip3")
  31. .and()
  32. .withUser("guest").password("123456").roles("vip1");
  33. }
  34. }

There is no PasswordEncoder mapped for the id "null"

必须要对密码进行加密才能使用!

密码编码:PasswordEncoder

重写该方法:protected void configure(AuthenticationManagerBuilder auth)

  1. @Override
  2. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  3. // 这些数据正常应该从数据库中读取
  4. auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
  5. .withUser("rainszj").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2", "vip3")
  6. .and()
  7. .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip2", "vip3")
  8. .and()
  9. .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
  10. }

OK!

关于这些要重写的方法,具体如何操作,我们可以点击WebSecurityConfigurerAdapter这个类中,里面有大量的注释介绍如何重写该方法!

例如:

  1. /**
  2. * Used by the default implementation of {@link #authenticationManager()} to attempt
  3. * to obtain an {@link AuthenticationManager}. If overridden, the
  4. * {@link AuthenticationManagerBuilder} should be used to specify the
  5. * {@link AuthenticationManager}.
  6. *
  7. * <p>
  8. * The {@link #authenticationManagerBean()} method can be used to expose the resulting
  9. * {@link AuthenticationManager} as a Bean. The {@link #userDetailsServiceBean()} can
  10. * be used to expose the last populated {@link UserDetailsService} that is created
  11. * with the {@link AuthenticationManagerBuilder} as a Bean. The
  12. * {@link UserDetailsService} will also automatically be populated on
  13. * {@link HttpSecurity#getSharedObject(Class)} for use with other
  14. * {@link SecurityContextConfigurer} (i.e. RememberMeConfigurer )
  15. * </p>
  16. *
  17. * <p>
  18. * For example, the following configuration could be used to register in memory
  19. * authentication that exposes an in memory {@link UserDetailsService}:
  20. * </p>
  21. *
  22. * <pre>
  23. * @Override
  24. * protected void configure(AuthenticationManagerBuilder auth) {
  25. * auth
  26. * // enable in memory based authentication with a user named
  27. * // &quot;user&quot; and &quot;admin&quot;
  28. * .inMemoryAuthentication().withUser(&quot;user&quot;).password(&quot;password&quot;).roles(&quot;USER&quot;).and()
  29. * .withUser(&quot;admin&quot;).password(&quot;password&quot;).roles(&quot;USER&quot;, &quot;ADMIN&quot;);
  30. * }
  31. *
  32. * // Expose the UserDetailsService as a Bean
  33. * @Bean
  34. * @Override
  35. * public UserDetailsService userDetailsServiceBean() throws Exception {
  36. * return super.userDetailsServiceBean();
  37. * }
  38. *
  39. * </pre>
  40. *
  41. * @param auth the {@link AuthenticationManagerBuilder} to use
  42. * @throws Exception
  43. */
  44. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  45. this.disableLocalConfigureAuthenticationBldr = true;
  46. }

注销及权限控制

Semantic UI

前端添加 注销按钮, http.logout() 默认会跳转到:/logout 请求

  1. <!--注销-->
  2. <a class="item" th:href="@{/logout}">
  3. <i class="sign-out icon"></i> 注销
  4. </a>

SecurityConfig中配置:

  1. // 授权
  2. @Override
  3. protected void configure(HttpSecurity http) throws Exception {
  4. // 链式编程
  5. // 请求权限的规则
  6. http.authorizeRequests()
  7. .antMatchers("/").permitAll()
  8. .antMatchers("/level1/**").hasRole("vip1")
  9. .antMatchers("/level2/**").hasRole("vip2")
  10. .antMatchers("/level3/**").hasRole("vip3")
  11. .and()
  12. // 没有权限默认会到登录页面,需要开启登录的页面
  13. // /login
  14. // http.formLogin();
  15. .formLogin();
  16. // 简单的可定制化的登出
  17. // .logout().deleteCookies("remove").invalidateHttpSession(false);
  18. // .logoutUrl("/custom-logout").logoutSuccessUrl("/logout-success");
  19. // 注销,开启了注销功能,跳到首页,默认会跳到 /login
  20. http.logout().logoutSuccessUrl("/");
  21. }

访问:http://localhost:8080/login 登录

点击 注销,会跳转到首页,OK!

thymeleaf 整合 Spring Secuirty:

在 Spring Boot 2.2.4.RELEASE 版本中使用:

  1. <!--thymeleaf Spring Security整合包-->
  2. <dependency>
  3. <groupId>org.thymeleaf.extras</groupId>
  4. <artifactId>thymeleaf-extras-springsecurity5</artifactId>
  5. <version>3.0.4.RELEASE</version>
  6. </dependency>

sec 的命名空间:

  1. xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5"

在Spring Boot 2.0.9.RELEASE 版本中使用:

  1. <!--thymeleaf Spring Security整合包-->
  2. <dependency>
  3. <groupId>org.thymeleaf.extras</groupId>
  4. <artifactId>thymeleaf-extras-springsecurity4</artifactId>
  5. <version>3.0.4.RELEASE</version>
  6. </dependency>

sec 的命名空间:

  1. xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"

现在切换到:SpringBoot 2.0.9.RELEASE

引入 thymeleaf-extras-springsecurity4 版本的命名空间后,IDEA会有提示,但引入thymeleaf-extras-springsecurity5 后,没有提示,很奇怪!

在index.html 中做如下修改:

  1. <div class="right menu">
  2. <!--如果未登录,显示登录-->
  3. <div sec:authorize="!isAuthenticated()">
  4. <a class="item" th:href="@{/toLogin}">
  5. <i class="address card icon"></i> 登录
  6. </a>
  7. </div>
  8. <!--如果已登录,显示用户名和注销-->
  9. <div sec:authorize="isAuthenticated()">
  10. <!--用户名-->
  11. <a class="item">
  12. 用户名:<span sec:authentication="name"></span>
  13. &nbsp;&nbsp;
  14. 角色:<span sec:authentication="principal.authorities"></span>
  15. </a>
  16. </div>
  17. <div sec:authorize="isAuthenticated()">
  18. <!--注销-->
  19. <a class="item" th:href="@{/logout}">
  20. <i class="sign-out icon"></i> 注销
  21. </a>
  22. </div>

目前了解到的有关SpringSecurity的标签属性有以下几个:

  • sec:authorize="isAuthenticated()"

    判断用户是否已经登陆认证,引号内的参数必须是isAuthenticated()
  • sec:authentication=“name”

    获得当前用户的用户名,引号内的参数必须是name
  • sec:authorize=“hasRole(‘role’)”

    判断当前用户是否拥有指定的权限。引号内的参数为权限的名称。
  • sec:authentication="principal.authorities"

    获得当前用户的全部角色,引号内的参数必须是principal.authorities

注意:注销失败可能的原因

在 SpringBoot 2.2.4.RELEASE 中,点击注销功能时,有个确认按钮,内部使用了post方法,而 SpringBoot 2.0.9.RELEASE 中没有提示按钮,默认使用了get方式,get 请求不安全,明文传输,为防止网站攻击,Spring Boot默认会开启csrf(跨站请求伪造),想要注销成功,需要在授权功能中关闭 csrf 这个功能!

  1. // 授权
  2. @Override
  3. protected void configure(HttpSecurity http) throws Exception {
  4. // ......
  5. // 关闭 csrf 功能
  6. http.csrf().disable();
  7. }
  1. <!--菜单根据用户的角色动态实现-->
  2. <div class="column" sec:authorize="hasRole('vip1')">
  3. <div class="ui raised segment">
  4. <div class="ui">
  5. <div class="content">
  6. <h5 class="content">Level 1</h5>
  7. <hr>
  8. <div><a th:href="@{/level1/1}"><i class="bullhorn icon"></i> Level-1-1</a></div>
  9. <div><a th:href="@{/level1/2}"><i class="bullhorn icon"></i> Level-1-2</a></div>
  10. <div><a th:href="@{/level1/3}"><i class="bullhorn icon"></i> Level-1-3</a></div>
  11. </div>
  12. </div>
  13. </div>
  14. </div>
  15. <div class="column" sec:authorize="hasRole('vip2')">
  16. <div class="ui raised segment">
  17. <div class="ui">
  18. <div class="content">
  19. <h5 class="content">Level 2</h5>
  20. <hr>
  21. <div><a th:href="@{/level2/1}"><i class="bullhorn icon"></i> Level-2-1</a></div>
  22. <div><a th:href="@{/level2/2}"><i class="bullhorn icon"></i> Level-2-2</a></div>
  23. <div><a th:href="@{/level2/3}"><i class="bullhorn icon"></i> Level-2-3</a></div>
  24. </div>
  25. </div>
  26. </div>
  27. </div>
  28. <div class="column" sec:authorize="hasRole('vip3')">
  29. <div class="ui raised segment">
  30. <div class="ui">
  31. <div class="content">
  32. <h5 class="content">Level 3</h5>
  33. <hr>
  34. <div><a th:href="@{/level3/1}"><i class="bullhorn icon"></i> Level-3-1</a></div>
  35. <div><a th:href="@{/level3/2}"><i class="bullhorn icon"></i> Level-3-2</a></div>
  36. <div><a th:href="@{/level3/3}"><i class="bullhorn icon"></i> Level-3-3</a></div>
  37. </div>
  38. </div>
  39. </div>
  40. </div>

登录:http://localhost:8080/login

记住我及登录页面定制

如果不适用记住我功能,当我们在浏览器端输入用户名和密码登录,关闭浏览器时,会话结束,再次打开浏览器访问时,需要再次输入用户名和密码登录!

而记住我功能,本质上是一个 Cookie,而Spring Security 的记住我功能使用了Session和Cookie。

  • [ ] 记住我功能:

默认自带的

要使用Spring Security默认的登录表单实现 记住我 功能,只需在授权方法(configure(HttpSecurity http))中,添加一行代码即可:

  1. // 开启记住我功能,cookie默认保存两周
  2. http.rememberMe();

自定义

要使用自定义的表单实现记住我功能:

前端:

  1. <input type="checkbox" name="remberme"> 记住我

在原有remeberMe()方法中指定前端的 name 参数即可,名称可以任意写:

  1. // 开启记住我功能,cookie默认保存两周,需要自定义接收前端的参数
  2. http.rememberMe().rememberMeParameter("remberme");

登录页面定制:

开启默认登录页面

要使用Spring Security 默认的登录页面,在授权方法中添加一行代码即可!

  1. // 没有权限默认会到登录页面,需要开启登录的页面
  2. // 会默认跳转到 /login 请求
  3. http.formLogin();

自定义登录页面

方式一

同样在 configure(HttpSecurity http),授权方法中添加如下,但是 loginPage() 的请求要和表单提交的 action 请求地址一致!

  1. http.formLogin().loginPage("/toLogin");

前端登录的 form 表单:

  1. <form th:action="@{/toLogin}" method="post">
  2. <div class="field">
  3. <label>Username</label>
  4. <div class="ui left icon input">
  5. <input type="text" placeholder="Username" name="username">
  6. <i class="user icon"></i>
  7. </div>
  8. </div>
  9. <div class="field">
  10. <label>Password</label>
  11. <div class="ui left icon input">
  12. <input type="password" name="password">
  13. <i class="lock icon"></i>
  14. </div>
  15. </div>
  16. <div class="field">
  17. <input type="checkbox" name="remberme"> 记住我
  18. </div>
  19. <input type="submit" class="ui blue submit button"/>
  20. </form>

方式二

需要加上实际登录时处理的URL:loginProcessingUrl("/login");

  1. http.formLogin().loginPage("/toLogin").loginProcessingUrl("/login");

前端:

  1. <form th:action="@{/login}" method="post">
  2. <div class="field">
  3. <label>Username</label>
  4. <div class="ui left icon input">
  5. <input type="text" placeholder="Username" name="username">
  6. <i class="user icon"></i>
  7. </div>
  8. </div>
  9. <div class="field">
  10. <label>Password</label>
  11. <div class="ui left icon input">
  12. <input type="password" name="password">
  13. <i class="lock icon"></i>
  14. </div>
  15. </div>
  16. <div class="field">
  17. <input type="checkbox" name="remberme"> 记住我
  18. </div>
  19. <input type="submit" class="ui blue submit button"/>
  20. </form>

这里的表单参数能够提交成功,是因为在formLogin()的源码中,默认的用户名和密码的name参数默认是:username 和 password

假设我们前端提交参数名不是 username 和 password 的呢?

现在将用户名改为:name 密码改为:pwd,再试试,发现提交失败!,走到了 error 请求

那么该如何修改呢?通过看 formLogin() 方法的注释我们也能得知,只需指定提交的参数名即可

  1. http.formLogin()
  2. .loginPage("/toLogin")
  3. .loginProcessingUrl("/login")
  4. .usernameParameter("name")
  5. .passwordParameter("pwd");

测试即可,搞定!

SpringBoot:整合SpringSecurity的更多相关文章

  1. boke练习: springboot整合springSecurity出现的问题,传递csrf

    boke练习: springboot整合springSecurity出现的问题,传递csrf freemarker模板 在html页面中加入: <input name="_csrf&q ...

  2. SpringBoot整合SpringSecurity简单实现登入登出从零搭建

    技术栈 : SpringBoot + SpringSecurity + jpa + freemark ,完整项目地址 : https://github.com/EalenXie/spring-secu ...

  3. SpringBoot整合SpringSecurity示例实现前后分离权限注解

    SpringBoot 整合SpringSecurity示例实现前后分离权限注解+JWT登录认证 作者:Sans_ juejin.im/post/5da82f066fb9a04e2a73daec 一.说 ...

  4. 9、SpringBoot整合之SpringBoot整合SpringSecurity

    SpringBoot整合SpringSecurity 一.创建项目,选择依赖 选择Spring Web.Thymeleaf即可 二.在pom文件中导入相关依赖 <!-- 导入SpringSecu ...

  5. boke练习: springboot整合springSecurity出现的问题,post,delete,put无法使用

    springboot 与 SpringSecurity整合后,为了防御csrf攻击,只有GET|OPTIONS|HEAD|TRACE|CONNECTION可以通过. 其他方法请求时,需要有token ...

  6. SpringBoot整合SpringSecurity实现JWT认证

    目录 前言 目录 1.创建SpringBoot工程 2.导入SpringSecurity与JWT的相关依赖 3.定义SpringSecurity需要的基础处理类 4. 构建JWT token工具类 5 ...

  7. springboot整合springsecurity遇到的问题

    在整合springsecurity时遇到好几个问题,自动配置登录,下线,注销用户的操作,数据基于mybatis,模版引擎用的thymeleaf+bootstrap. 一.认证时密码的加密(passwo ...

  8. SpringBoot 整合 SpringSecurity 梳理

    文档 Spring Security Reference SpringBoot+SpringSecurity+jwt整合及初体验 JSON Web Token 入门教程 - 阮一峰 JWT 官网 Sp ...

  9. SpringBoot整合SpringSecurity简单案例

    在我们开发项目的过程中经常会用到一些权限管理框架,Java领域里边经常用的可能就是shiro了,与之对应的还有SpringSecurity,SpringSecurity可以说是非常强大,与Spring ...

  10. SpringBoot整合SpringSecurity,SESSION 并发管理,同账号只允许登录一次

    重写了UsernamePasswordAuthenticationFilter,里面继承AbstractAuthenticationProcessingFilter,这个类里面的session认证策略 ...

随机推荐

  1. Redis linux 下安装

    Redis linux 下安装 下载Redis安装包,可以从Redis中文网站中下载 下载地址:http://www.redis.cn/download.html Redis4.0 稳定版本 使用&l ...

  2. Gun N' Rose Team Review

    一看到这个项目就被他的功能给吸引了.回忆起以前看到一个东西很新奇想去网上查询它是什么,但是又不知道应该怎样去描述它,于是在搜索引擎的输入框中键入.删除.键入.删除的可笑经历的时候,我就越发感觉到这个a ...

  3. Laravel路由不生效,除了首页全部404解决方案Nginx环境

    原因: 请求根目录/ (http://www.xxx.com/public/),会请求public/index.php 输入其他路由地址时,会把你的请求定位到:http://www.xxx.com/i ...

  4. mysql 更改默认字符集

    mysql 默认字符集概述 首先,MySQL的字符集问题主要是两个概念: haracter Sets Collations 前者是字符内容及编码,后者是对前者进行比较操作的一些规则.这两个参数集可以在 ...

  5. 域名和服务器绑定及https协议更换

    服务器是之前已经购买了的 1.腾讯云产品中搜索域名注册(产品太多了懒得找,直接搜索来得快些) 2.进去之后可以选择各种后缀的域名,输入自己喜欢的,看看哪些后缀是没有被注册的.自己挑选一个就可以,按照指 ...

  6. 2019-2020-1 20199310《Linux内核原理与分析》第七周作业

    1.问题描述 在前面的文章中,学习了系统调用system_call的处理过程,在MenuOS中运行getpid命令,通过gdb跟踪调用time函数的过程,并分析system_call代码对应的工作过程 ...

  7. 2019-2020-1 20199329《Linux内核原理与分析》第十三周作业

    <Linux内核原理与分析>第十三周作业 一.本周内容概述 通过重现缓冲区溢出攻击来理解漏洞 二.本周学习内容 1.实验简介 注意:实验中命令在 xfce 终端中输入,前面有 $ 的内容为 ...

  8. Inno setup: check for new updates

    Since you've decided to use a common version string pattern, you'll need a function which will parse ...

  9. JVM原理以及深度调优(二)

    JVM内存分配 内存分配其实真正来讲是有三种的.但对于JVM来说只有两种 栈内存分配: 大家在调优的过程中会发现有个参数是-Xss 默认是1m,这个内存是栈内存分配, 在工作中会发现栈OutOfMem ...

  10. Maven+Jmeter+Jenkins的持续集成的新尝试

    前言: 这又是一篇迟到很久的文章,四月身体欠佳,根本不在状态. 好了,回到正题,相信大家也在很多博客,看过很多类似乎的文章,那么大家来看看我是如何实现的? 准备工作: 创建一个maven工程 创建一个 ...