Spring-Security快速体验
1、创建Springboot项目,并简单实现一个接口
package com.zf.springsecurity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloSecurityController {
@RequestMapping("/hello/security")
public String hello(){
return "hello secuity";
}
}
2、浏览器调用接口响应接口数据
3、添加SpringSecurity依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
4、重启springboot后,再次访问接口得到结果如下:
5、输入用户名user,密码(项目启动时生成)即可
可以看到security框架默认保护用户资源,当访问资源时需要进行一层用户认证,认证通过后可继续访问资源,认证不通过则访问被拒绝。
内置认证过滤器
SpringSecurity功能的实现主要由一系列过滤器配合完成,也称为过滤器链。
@EnableWebSecurity(debug = true) 打印过滤器链
自定义认证过滤器
1、自定义过滤器
package com.zf.springsecurity;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class JWTFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
System.out.println("自定义过滤器---------");
}
}
2、将自定义过滤器添加到过滤器链
package com.zf.springsecurity;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@EnableWebSecurity(debug = true)
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().addFilterBefore(new JWTFilter(), UsernamePasswordAuthenticationFilter.class);
return http.build();
}
}
参考文章:
Spring Security 基本介绍及基础项目搭建-CSDN博客
如何使用SpringSecurity_spring security使用-CSDN博客