前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring Boot 整合SpringSecurity

Spring Boot 整合SpringSecurity

作者头像
LCyee
发布2020-08-05 17:43:59
1.3K0
发布2020-08-05 17:43:59
举报

Spring Security 简介

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

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

在我们日常的应用开发当中,安全是在设计之初就需要考虑的问题,否则架构一旦确定,就需要改动大量的代码;Spring Security 提供了身份认证和权限控制的一系列功能。

  • 功能权限
  • 访问权限
  • 菜单权限

以前实现这些功能,我们需要使用大量的原生代码来实现拦截器、过滤器,使代码变得冗余且安全性也难以控制。

市面上知名的安全框架:shiroSpringSecurity,两者实现的功能都很相同。

常见的几个类:

  • WebSecurityConfigurerAdapter:自定义 Security 策略
  • AuthenticationManagerBuilder:自定义认证策略
  • @EnableWebSecurity:开启 WebSecurity 模式, @EnableXXX 通常表示开启某个功能

更多信息参考官网:https://spring.io/projects/spring-security

下面我们来进行详细的搭建过程

一、环境搭建

新建IDEA项目

选择 webthymeleaf依赖

导入静态资源

静态资源素材地址:https://www.lanzous.com/i8orrja

关闭thymeleaf缓存

application.properties

spring.thymeleaf.cache=false

建立RouterController

controller/RouterController.java

@Controller
public class RouterController {

    @RequestMapping({"/", "index","index.html"})
    private String index(){return "index";}

    @RequestMapping("tologin")
    private String toLogin() { return "views/login"; }

    @RequestMapping("/level1/{id}")
    private String level1(@PathVariable("id") int id) {return "views/level1/" + id;}

    @RequestMapping("/level2/{id}")
    private String level2(@PathVariable("id") int id) {return "views/level2/" + id;}

    @RequestMapping("/level3/{id}")
    private String level3(@PathVariable("id") int id) {return "views/level3/" + id;}
}

启动项目,测试访问 http://localhost:8080/

二、用户认证和授权

0x01 授权

导入Spring Security依赖

<!--Spring Security-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

自定义config

config/SecurityConfig.java

继承 WebSecurityConfigurerAdapter 类,并使用 @EnableWebSecurity 注解声明

import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@EnableWebSecurity
public class SecurityConfig  extends WebSecurityConfigurerAdapter {

}

Alt + Insert 键 查看可以重载的一些函数

这里我们重载 configure(HttpSecurity)

@EnableWebSecurity
public class SecurityConfig  extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
    }
}

根据需求进行配置

需求:首页所有人可以访问,功能页只有对应有权限的人才能访问

  • 任何人都能访问根路径 /
  • /level1 下的所有页面只能等级为 vip1 的才能访问
  • /level2 下的所有页面只能等级为 vip2 的才能访问
  • /level3 下的所有页面只能等级为 vip3 的才能访问
  • 没有权限默认跳转到登录页面

用到的模块

  • http.authorizeRequests()
    • .antMatchers() 设置需要认证的路径
      • .permitAll() 允许任何角色
      • .hasRole() 允许指定角色
  • http.formLogin() 无权限的角色跳转至 /login,默认为SpringSecurity自带的登录页面

config/SecurityConfig.java

@EnableWebSecurity
public class SecurityConfig  extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                //设置需要控制权限的url
                .antMatchers("/").permitAll()   //不需要身份认证的请求
                .antMatchers("/level1/**").hasRole("vip1")  //指定角色访问特定的请求
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");

        //没有权限汇默认到登录页面 "/login",/login是spring security自带的一个页面
        //登录成功后默认跳转到 / 路径
        http.formLogin().loginPage("/login").defaultSuccessUrl("/",true);
    }
}

启动项目,访问测试

0x02 认证

重写 configure(AuthenticationManagerBuilder)

认证信息储存在内存

需求

  • 用户xiaoming的等级为 vip1,只能访问vip1的页面
  • 用户laowang的等级为vip2,只能访问vip2的页面
  • 用户root的等级为admin,可以访问任何页面

模块

  • auth.inMemoryAuthentication().withUser() 添加认证角色信息
  • BcryptPasswordEncoder() 加密模块
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
            .withUser("xiaoming").password(new BCryptPasswordEncoder().encode("123123"))
                .roles("vip1")
            .and()
            .withUser("laowang").password(new BCryptPasswordEncoder().encode("123123"))
                .roles("vip2")
            .and()
            .withUser("root").password(new BCryptPasswordEncoder().encode("123123"))
                .roles("vip1", "vip2", "vip3");
}

使用.and()拼接多个配置, BCryptPasswordEncoder() 为密码加密模块

测试账户 xiaoming
测试测试 root

认证信息储存在数据库

结合之前整合Mybatis的笔记,配置好数据库信息。

看文档实现

三、其他功能实现

0x01 注销

在授权部分代码中添加

//注销
http.logout().logoutSuccessUrl("/"); //指定注销成功后跳转的页面

调用logout()模块后,会自动生成一个/logout 的URL

我们在前端添加一个注销按钮,访问该URL

<a class="item" th:href="@{/logout}">
    <i class="arrow circle right icon"></i>注销
</a>

点击按钮后会调转到默认的logout页面,点击确认后跳转到主页

0x02 整合Thymeleaf

需求如下:

  • 实现用户登录时显示注销按钮,未登录时显示登录按钮
  • 登录后显示用户的用户名和权限信息
  • 实现根据用户的权限信息显示指定的HTML模块

maven官网 找到 Spring SecurityThymeleaf 的整合包

<!-- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf-extras-springsecurity5 -->
<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity5</artifactId>
    <version>3.0.4.RELEASE</version>
</dependency>

pom.xmlproperties 标签中加入,否则在 html 模板中的 sec 标签不生效,原因未知。

<thymeleaf-extras-springsecurity5.version>3.0.4.RELEASE</thymeleaf-extras-springsecurity5.version>

index.html 文件中引用命名空间 xmlns:sec="http://www.thymeleaf.org/extras/spring-security"

<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">

登录状态及权限信息

通过以下配置,实现两点需求:

  • 实现用户登录时显示注销按钮,未登录时显示登录按钮
  • 登录后显示用户的用户名和权限信息

定位到<div class="right menu">标签,修改子标签内容如下

<!--未登录-->
<a sec:authorize="!isAuthenticated()" class="item" th:href="@{/login}">
    <i class="address card icon"></i>登录
</a>

<a sec:authorize="isAuthenticated()" class="item">
    <i class="address card icon"></i>
    用户名:<span sec:authentication="name"></span>
</a>

<a sec:authorize="isAuthenticated()" class="item">
    <i class="address card icon"></i>
    角色:<span sec:authentication="principal.authorities"></span>
</a>

<!--已登录 -->
<a sec:authorize="isAuthenticated()" class="item" th:href="@{/logout}">
    <i class="arrow circle right icon"></i>注销
</a>

附加:添加登录状态提示语

<div class="ui segment" style="text-align: center">
    <h3 sec:authorize="!authenticated">Please Sign in</h3>
    <h3 sec:authorize="authenticated">Welcome Sign in the system</h3>
</div>

在上面的代码当中我们使用以下几个拓展spring security的属性和方法

  • sec:authorize="!isAuthenticated()" 判断用户是否已认证,在前面加上!表示取反,
  • sec:authentication="name" 获取用户名
  • sec:authentication="principal.authorities" 获取用户的权限信息
实现效果

未登录

登录

根据用户身份显示指定模块

定位到index.html 中的 <div class="ui three column stackable grid"> 标签

使用 sec:authorize="hasRole('ROLE_vip1')中的 hasRole() 对用户身份进行判断

例如:

<!--lever 1-->
<div sec:authorize="hasRole('ROLE_vip1')" class="column">
    <div class="ui raised segment">
        <div class="ui">
            <div class="content">
                <h5 class="content">Level 1</h5>
                <hr>
                <div><a th:href="@{/level1/1}"><i class="bullhorn icon"></i> Level-1-1</a></div>
                <div><a th:href="@{/level1/2}"><i class="bullhorn icon"></i> Level-1-2</a></div>
                <div><a th:href="@{/level1/3}"><i class="bullhorn icon"></i> Level-1-3</a></div>
            </div>
        </div>
    </div>
</div>
实现效果

0x03 记住我和登录页定制

remember me

我们可以直接在configure(HttpSecurity http)中添加 http.rememberMe();

再重新登录,访问login页面,就能看到 remember me的选项

我们勾选上并尝试登录

登录成功后我们可以看到 spring security会自动返回一个cookie值到我们的浏览器当中,实现用户会话信息的保存。

登录页定制

在这之前的操作一直以来登录页面都是使用 spring security自带的登录页面,通常我们都是需要替换成自己设计的登录页面

这里我们原来配置的登录页面的路由为 /tologin

@RequestMapping("/tologin")
private String toLogin() { return "views/login"; }

我们修改 config 中的 http.formLogin()

http.formLogin()
    .loginPage("/tologin")        //自己设计的登录页面url
    .usernameParameter("userName")  //修改为自己表单中的name值:默认为 username和password
    .passwordParameter("passWord")
    .defaultSuccessUrl("/",true)
    .loginProcessingUrl("/login"); //提交登录请求的url

rememberme的name值也可以用.rememberMeParameter()自定义,默认为remember-me

在自己的login页面中添加 rememberme 标签

<div class="field">
    <input th:text="保存会话信息" type="checkbox" name="remember-me"/>
</div>

修改表单提交的 url 为 /login

<form th:action="@{/login}" method="post">

页面效果

测试登录,登录成功,如下图所示。

0x04 一些问题

  • 如果登陆后注销出现403错误,在spring security配置中添加 http.csrf().disable() 来关闭csrf验证即可解决
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-02-14,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Spring Security 简介
  • 一、环境搭建
    • 新建IDEA项目
      • 导入静态资源
        • 建立RouterController
        • 二、用户认证和授权
          • 0x01 授权
            • 导入Spring Security依赖
            • 自定义config
            • 根据需求进行配置
            • 用到的模块
          • 0x02 认证
            • 认证信息储存在内存
            • 认证信息储存在数据库
        • 三、其他功能实现
          • 0x01 注销
            • 0x02 整合Thymeleaf
              • 登录状态及权限信息
              • 根据用户身份显示指定模块
            • 0x03 记住我和登录页定制
              • remember me
              • 登录页定制
            • 0x04 一些问题
            领券
            问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档