前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SpringBoot与安全(Spring Security)

SpringBoot与安全(Spring Security)

作者头像
OY
发布2022-03-12 14:22:57
6910
发布2022-03-12 14:22:57
举报
文章被收录于专栏:OY_学习记录

博客中涉及的源码,下载地址在博客文章底部,有需要的小伙伴自行下载

一、简介

​ SpringSecurity 是针对 Spring 项目的安全框架,也是 Spring Boot 底层安全模块的技术选项。他可以实现强大的 web 安全控制。对于安全控制,我们需要引入 spring-boot-starter-securiy 模块。

代码语言:javascript
复制
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

几个类

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

具体的参考 Spring 官网:https://spring.io/guides/gs/securing-web/

二、功能演示

配置 thymeleaf 模板依赖(springboot 2.3 版本)

代码语言:javascript
复制
// 其他有可能需要配置以下配置,2.3不需要
<properties>
    <thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
    <thymeleaf-layout-dialect.version>2.3.0</thymeleaf-layout-dialect.version>
</properties>

以下都需要配置

代码语言:javascript
复制
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

① 引入 SpringSecurity

代码语言:javascript
复制
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

② 编写 SpringSecurity 的配置类

代码语言:javascript
复制
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

}

③ 登入

控制请求的访问权限:

代码语言:javascript
复制
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //super.configure(http);
        // 定制请求的授权规则
        http.authorizeRequests().antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("VIP1")
                .antMatchers("/level2/**").hasRole("VIP2")
                .antMatchers("/level2/**").hasRole("VIP3");
    }
}

定义认证规则

注意:Security5 与之前的传输密码有部分的不同

参考我这篇博客:https://blog.csdn.net/qq_45738810/article/details/108912554

代码语言:javascript
复制
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        super.configure(auth);
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("zhangsan").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP1", "VIP2")
                .and()
                .withUser("lisi").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP2", "VIP3")
                .and()
                .withUser("wangwu").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP1", "VIP3");
    }

开启自动配置的登录功能

  • /login 来登录页
  • 重定项到/login?error 表示登录失败
  • 默认 post 形式的/login 代表处理登录
  • 一但定制 loginPage; 那么 loginPage 的 post 请求就是登录
代码语言:javascript
复制
@Override
protected void configure(HttpSecurity http) throws Exception {
    //super.configure(http);
    http.authorizeRequests().antMatchers("/").permitAll()
        .antMatchers("/level1/**").hasRole("VIP1")
        .antMatchers("/level2/**").hasRole("VIP2")
        .antMatchers("/level2/**").hasRole("VIP3");

    // 开启自动登录功能
    http.formLogin();
}

定制页面

代码语言:javascript
复制
http.formLogin().usernameParameter("username").passwordParameter("password").loginPage("/userlogin");

④ 注销

代码语言:javascript
复制
<form th:action="@{/logout}">
  <input type="submit" value="注销" />
</form>
代码语言:javascript
复制
@Override
protected void configure(HttpSecurity http) throws Exception {
    //super.configure(http);
    http.authorizeRequests().antMatchers("/").permitAll()
        .antMatchers("/level1/**").hasRole("VIP1")
        .antMatchers("/level2/**").hasRole("VIP2")
        .antMatchers("/level2/**").hasRole("VIP3");

    // 开启自动登录功能
    http.formLogin();
    // 开启注销功能
    http.logout(); // 注销成功会返回 /login?logout 页面
    // http.logout().logoutSuccessUrl("/"); 注销成功以后来到首页
}

⑤ 记住我

代码语言:javascript
复制
http.rememberMe();
  • 登陆成功以后,将 cookie 发给浏览器保存,以后访问页面带上这个 cookie,只要通过检查就可以免登录
  • 点击注销会删除 cookie

定制

代码语言:javascript
复制
<form th:action="@{/userlogin}" method="post">
  用户名:<input name="username" /><br />
  密码:<input name="password" /><br />
  <input type="checkbox" name="remeber" /> 记住我<br />
  <input type="submit" value="登陆" />
</form>
代码语言:javascript
复制
@Override
protected void configure(HttpSecurity http) throws Exception {

    .....跟上面一致,省略了

        // 记住我
        http.rememberMe().rememberMeParameter("remeber");
}

三、SpringSecurity 标签

  • 需要引入 thymeleaf-extras-springsecurity5
代码语言:javascript
复制
<properties>
   <thymeleaf-extras-springsecurity5.version>3.0.4.RELEASE</thymeleaf-extras-springsecurity5.version>
</properties>

<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity5</artifactId>
    <version>3.0.4.RELEASE</version>
</dependency>
代码语言:javascript
复制
<!DOCTYPE html>
<html
  xmlns:th="http://www.thymeleaf.org"
  xmlns:sec="http://www.thymeleaf.org/extras/spring-security"
></html>

示例:

代码语言:javascript
复制
<div sec:authorize="!isAuthenticated()">
  // 不登入显示以下
  <h2 align="center">
    游客您好,如果想查看武林秘籍 <a th:href="@{/userlogin}">请登录</a>
  </h2>
</div>

<div sec:authorize="isAuthenticated()">
  // 登录显示这个
  <h2>
    <span sec:authentication="name"></span>,您好,您的角色有:
    <span sec:authentication="principal.authorities"></span>
  </h2>
  <form th:action="@{/logout}">
    <input type="submit" value="注销" />
  </form>
</div>
代码语言:javascript
复制
<div sec:authorize="hasRole('VIP1')">
  <h3>普通武功秘籍</h3>
  <ul>
    <li><a th:href="@{/level1/1}">罗汉拳</a></li>
    <li><a th:href="@{/level1/2}">武当长拳</a></li>
    <li><a th:href="@{/level1/3}">全真剑法</a></li>
  </ul>
</div>

四、官方文档

https://www.thymeleaf.org/doc/articles/springsecurity.html https://github.com/thymeleaf/thymeleaf-extras-springsecurity 该文档介绍了不同版本的 thymeleaf、 springsecurity 、thymeleaf-extras-springsecurity 对应使用以及一些使用示例

源码下载: 链接:https://pan.baidu.com/s/1oT_Dro3yi4xvSJqccU8D2g 提取码:ljj7

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-10-04,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、简介
  • 二、功能演示
    • ① 引入 SpringSecurity
      • ② 编写 SpringSecurity 的配置类
        • ③ 登入
          • ④ 注销
            • ⑤ 记住我
            • 三、SpringSecurity 标签
            • 四、官方文档
            领券
            问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档