Spring Security是一个功能强大且高度可定制的身份验证和访问控制框架。提供了完善的认证机制和方法级的授权功能。是一款非常优秀的权限管理框架。它的核心是一组过滤器链,不同的功能经由不同的过滤器。

1. SpringSecurity 快速入门

① 引入依赖

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

② 在项目中提供一个用于测试的/hello接口:

@RestController
public class UserResource {

    @RequestMapping("/hello")
    public String test(){
        return "hello";
    }
}

③ 启动项目,/hello接口 就已经被保护起来了,当用户访问 /hello 接口时,会自动跳转到登录页面,用户登录成功后才能访问到 /hello 接口。

springsecurity放行固定请求 springsecurity放行静态资源_静态资源

默认的登录用户名是user,登录密码是一个随机生成的UUID字符串,在项目启动日志中可以看到登录密码(这意味着每次项目启动时,密码都会发生变化):

New HTTP session created: 4D9A358D69838EEF8B8961DAC5B3093F

输入默认的用户名和密码,就可以成功登录了。

上面的用户名是默认的,密码是随机生成的,实在是不方便,那么怎么自定义用户名和密码呢,只需要在配置文件application.properties 文件中添加如下配置:

spring.security.user.name = admin
spring.security.user.password = 123456

这就是SpringSecurity 的强大之处,只需要引入一个依赖,所有的接口就会别自动保护起来。

2. SpringSecurity 配置需要放行的请求

有些请求不需要经过 SpringSecurity过滤器,毕竟启动SpringSecurity过滤器是消耗性能的,这时就可以重写configure(WebSecurity web)方法,并配置需要放行的请求,这些请求不需要经过认证就能访问。

1、访问html、css、jss、image等静态资源的请求放行,不启用SpringSecurity过滤器

SpringBoot默认存放静态资源的四个静态资源文件夹:

classpath:/META-INF/resources/
classpath:/resources/
classpath:/static/
classpath:/public/

springsecurity放行固定请求 springsecurity放行静态资源_spring_02

配置静态资源的路径时不要加静态资源文件夹的名称:

@EnableWebSecurity(debug = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(WebSecurity web) throws Exception {
       web.ignoring()
               .antMatchers("/login.html")
               .antMatchers("/images/**");
       // web.ignoring().antMatchers("/login.html","images/**");
    }
}

访问静态资源时也不要加静态资源文件夹的名称:

浏览器访问 http://localhost:8080/images/big.png 和 http://localhost:8080/login.html , 经测试不需要经过认证登录即可访问成功。

2、SpringMvc的接口请求放行,不启用SpringSecurity过滤器

@RestController
public class UserResource {
    @RequestMapping("/test/hello")
    public String test1(){
        return "public hello";
    }

    @RequestMapping("/api/hello")
    public String api(){
        return "public hello";
    }
}

配置放行路径以 /test/api/开头的请求:

@EnableWebSecurity(debug = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(WebSecurity web) throws Exception {
       web.ignoring()
               .mvcMatchers("/test/**")
               .mvcMatchers("/api/**");
       // web.ignoring().mvcMatchers("/test/**","/api/**");       
    }
}

访问请求:http://localhost:8080/api/hello 和 http://localhost:8080/test/hello。经测试不需要经过认证登录即可访问成功。