老唐手把手教你配置security,并增加JWT校验(copy就用)。
1.首先配置security
1.1导入security的jar包
<!--security 框架-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
1.2配置security配置文件(直接上代码)
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private final JwtAccessDeniedHandler jwtAccessDeniedHandler;
private final JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
private final JwtTokenUtils jwtTokenUtils;
@Autowired
private YxsPubOrderMaintenanceService yxsPubOrderMaintenanceService;
public WebSecurityConfig(JwtAccessDeniedHandler jwtAccessDeniedHandler, JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint, JwtTokenUtils jwtTokenUtils,YxsPubOrderMaintenanceService yxsPubOrderMaintenanceService) {
this.jwtAccessDeniedHandler = jwtAccessDeniedHandler;
this.jwtAuthenticationEntryPoint = jwtAuthenticationEntryPoint;
this.jwtTokenUtils = jwtTokenUtils;
this. yxsPubOrderMaintenanceService=yxsPubOrderMaintenanceService;
}
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.csrf().disable()
.exceptionHandling()
.authenticationEntryPoint(jwtAuthenticationEntryPoint)
.accessDeniedHandler(jwtAccessDeniedHandler)
.and()
.headers()
.frameOptions()
.disable()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(
HttpMethod.GET,
"/*.html",
"/**/*.html",
"/**/*.css",
"/**/*.js",
"/**/*.jpeg",
"/**/*.png",
"/**/*.svg",
"/**/*.jpg",
"/webSocket/**",
"/yxs/**"
).permitAll()
.antMatchers("/swagger-ui.html").permitAll()
.antMatchers("/swagger-resources/**").permitAll()
.antMatchers("/webjars/**").permitAll()
.antMatchers("/*/api-docs").permitAll()
.antMatchers("/file/**").permitAll()
.antMatchers("/pub/**").permitAll()
.antMatchers("/gft/**").permitAll()
.antMatchers("/druid/**").permitAll()
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.antMatchers("/api/auth/**", "/error/**").permitAll()
.antMatchers("/**").permitAll()
.anyRequest().authenticated();
httpSecurity.headers().cacheControl();
httpSecurity
.apply(new TokenConfigurer(jwtTokenUtils));
}
public class TokenConfigurer extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
private final JwtTokenUtils jwtTokenUtils;
public TokenConfigurer(JwtTokenUtils jwtTokenUtils) {
this.jwtTokenUtils = jwtTokenUtils;
}
@Override
public void configure(HttpSecurity http) throws Exception {
JwtAuthenticationTokenFilter customFilter = new JwtAuthenticationTokenFilter(jwtTokenUtils,yxsPubOrderMaintenanceService);
http.addFilterBefore(customFilter, UsernamePasswordAuthenticationFilter.class);
}
}
}
2.JWT配置
2.1导入JWT包
<dependency>
<groupId>io.jsonwebtoken</groupId