package com.xkrs.common.config; import com.xkrs.common.account.CustomAuthenticationProvider; import com.xkrs.common.account.JwtAuthenticationFilter; import com.xkrs.common.account.JwtLoginFilter; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled=true) class WebSecurityConfig extends WebSecurityConfigurerAdapter { /** * 设置 HTTP 验证规则 * @param http * @throws Exception */ @Override protected void configure(HttpSecurity http) throws Exception { // 关闭csrf验证 http.csrf().disable() // 对请求进行认证 .authorizeRequests() // 所有 / 的所有请求 都放行 //.antMatchers("/").permitAll() // 所有OPTIONS请求都放行 .antMatchers(HttpMethod.OPTIONS).permitAll() // 所有 /user/add 用户注册 的POST请求 都放行 .antMatchers(HttpMethod.POST, "/api/user/add").permitAll() // 所有 /user/check/duplicate 检查用户名是否重复 的POST请求 都放行 .antMatchers(HttpMethod.POST, "/api/user/check/duplicate").permitAll() // 所有 /login 用户登录 的POST请求 都放行 .antMatchers(HttpMethod.POST, "/api/login").permitAll() // 所有 app 用户注册 的POST请求 都放行 .antMatchers(HttpMethod.POST, "/api/person-investigator/add").permitAll() .antMatchers("/ws/asset").permitAll() .antMatchers(HttpMethod.GET,"/api/user/booleanUserName").permitAll() .antMatchers(HttpMethod.POST,"/insertFirePoint").permitAll() .antMatchers(HttpMethod.POST,"/insertAppTask").permitAll() .antMatchers(HttpMethod.GET,"/selectAppTask").permitAll() .antMatchers(HttpMethod.GET,"/selectFirePointBetweenSeven").permitAll() .antMatchers(HttpMethod.GET,"/selectFirePointNum").permitAll() // 所有其它请求需要身份认证 .anyRequest().authenticated() .and() // 添加一个过滤器 所有访问 /login 的请求交给 JWTLoginFilter 来处理 这个类处理所有的JWT相关内容 .addFilterBefore(new JwtLoginFilter("/api/login", authenticationManager()), UsernamePasswordAuthenticationFilter.class) // 添加一个过滤器验证其他请求的Token是否合法 .addFilterBefore(new JwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); ;} @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { // 使用自定义身份验证组件 auth.authenticationProvider(new CustomAuthenticationProvider()); } }