SpringSecurity 学习笔记

SpringSecurity

Spring Security 是一个功能强大且高度可定制的身份验证和访问控制框架。它是用于保护基于Spring的应用程序的实际标准。

Spring Security 是一个框架,致力于为 Java 应用程序提供身份验证和授权。与所有Spring项目一样,Spring Security 的真正强大之处在于可以轻松扩展以满足自定义要求。

简介

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

  • WebSecurityConfigurerAdapter: 自定义Security策略
  • AuthenticationManagerBuilder: 自定义认证策略
  • @EnableWebSecurity: 开启WebSecurity模式 ( @Enablexxx : 开启某个功能 )

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

“认证”(Authentication)

“授权”(Authorization)

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

1、新建 SpringBoot 项目

素材:https://gitee.com/ENNRIAAA/spring-security-material

搭建项目,路由 controller

@Controller
public class RouterController {

    @RequestMapping({"/", "/index"})
    public String index(){
        return "index";
    }

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

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

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

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

导入依赖 security:

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

官方文档: https://docs.spring.io/spring-security/site/docs/current/reference/html5/#jc

在 config 包下新建 SecurityConfig 类, 以下是固定的框架

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
    }
}
2、用户认证、授权、注销、记住我、定制登录页

点进源码看注释!!!

// Aop : 拦截器
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    // 链式编程
    // 授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 首页所有人可以访问, 功能页只有对应权限的人才能访问
        // 请求授权的规则
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");

        // 没有权限默认会到登录页, 需要开启登录的界面 默认会调到 /login 界面
        // loginPage("/toLogin") : 定制登录页面
        http.formLogin().loginPage("/toLogin")
                .usernameParameter("username")      // 前端表单的 name 属性值
                .passwordParameter("password")      // 前端表单的 name 属性值
                .loginProcessingUrl("/login");      // 提交表单的地址

        http.csrf().disable();  // 关闭 csrf 功能

        // 注销。开启了注销功能
        http.logout().logoutSuccessUrl("/");    // 跳转到首页

        // 记住我, cookie: 默认保存两周
        http.rememberMe().rememberMeParameter("remember");   // 自定义接收前端的参数
    }

    // 认证   SpringBoot 2.1.x 可以直接使用
    // 密码编码错误: PasswordEncoder  在 Spring Security 中新增了许多加密的方式
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // auth.jdbcAuthentication() 从数据库中
        // 正常这些数据是从数据库中读取
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())   // 在内存中读
                .withUser("mianbao").password(new BCryptPasswordEncoder().encode("123")).roles("vip1", "vip2")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123")).roles("vip1", "vip2", "vip3")
                .and()
                .withUser("guest").password(new BCryptPasswordEncoder().encode("123")).roles("vip3");
    }
}
3、权限控制

导入 thymeleaf 和 springsecurity 的整合包:

<!-- 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>

index.html 导入命名空间:

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

编写 HTML

....
<div class="ui secondary menu">
    <a class="item"  th:href="@{/index}">首页</a>

    <!--登录注销-->
    <div class="right menu">
        <!--如果未登录-->
        <div sec:authorize="!isAuthenticated()">	<!-- 判断未登录 -->
            <a class="item" th:href="@{/toLogin}">
                <i class="address card icon"></i> 登录
            </a>
        </div>

        <!--如果登录-->
        <div sec:authorize="isAuthenticated()">
            <!--注销-->
            <a class="item">
                用户名:<span sec:authentication="name"></span>	
                角色:<span sec:authentication="principal.authorities"></span>
            </a>
        </div>
        <div sec:authorize="isAuthenticated()">
            <!--注销-->
            <a class="item" th:href="@{/logout}">
                <i class="sign-out icon"></i> 注销
            </a>
        </div>
    </div>
....

角色权限管理:

<!-- 根据登录的角色,动态的显示 -->
<div class="column" sec:authorize="hasAnyRole('vip1')">
    ...
</div>

记住我的前端:

...
<div class="field">
    <input type="checkbox" name="remember"> 记住我
</div>
...
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值