SpringSecurity学习笔记

博主 979 2020-08-15

参考视频
狂神的SpringSecurity

一、简介

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

SpringSecurity的特点:

  • 对身份验证和授权提供全面和可扩展的支持

  • 防止会话固定、点击劫持、跨站点请求伪造等攻击

  • Servlet API的集成

  • 与Spring Web MVC的可选集成

二、入门

  1. 首先写一些简单的页面,首页,登录页,不同用户可访问的页面
    image.png
    参考B站狂神的SpringSecurity视频

  2. 添加依赖

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

		<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-security -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
<!--			<version>2.2.5.RELEASE</version>-->
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
			<version>2.2.5.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
  1. 控制器
    实现首页,登录页,访问页面的跳转
@Controller
public class RouterController {

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

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

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

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

    @RequestMapping("/level3/{id}")
    public String toLevel3(@PathVariable("id") Integer id){
        return "views/level3/" + id;
    }
}
  1. 配置SpringSecurity
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 认证
     * password 不能使用明文,需要加密 (There is no PasswordEncoder mapped for the id "null")
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        super.configure(auth);
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("wuminggao").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2", "vip3")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2", "vip3", "vip1")
        .and()
        .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1")
        ;

    }

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

        //没有权限时跳转到登录页面
        http.formLogin().loginPage("/toLogin");

        //注销
        http.logout().logoutSuccessUrl("/");

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

        http.rememberMe().rememberMeParameter("remember"); // 开启记住我功能
    }
}
  1. 功能测试
    首页
    image.png
    点击登录
    image.png
    登录root用户
    image.png
    注销,登录访客用户
    image.png