package com.shkpr.service.alambizplugin.configuration; import com.shkpr.service.alambizplugin.controllerfilter.CustomAuthenticationProvider; import com.shkpr.service.alambizplugin.controllerfilter.third.ApiJWTBizFilterMgr; import com.shkpr.service.alambizplugin.constants.ApiURI; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; 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.builders.WebSecurity; 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; /** * 该类主要用来做权限控制的配置、以及注册各种过滤器 * 执行顺序 * (1) 注册验证组件 - configure(AuthenticationManagerBuilder auth)方法中注册自定义验证组件 * (2) 设置验证规则 - configure(HttpSecurity http)方法中设置了各种路由访问规则 * (3) 初始化过滤组件 - JWTLoginFilter 和 JWTAuthenticationFilter 类会初始化 */ @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) //@PreAuthorize对权限的注解需要设置prePostEnabled = true public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter { @Value("${global.test.pressure:false}") private boolean mBForPressureTest; @Value("${global.ops.lan.ip:127.0.0.1}") private String mStrOpsServerLanIP; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { //使用自定义身份验证组件 auth.authenticationProvider(new CustomAuthenticationProvider()); } // 设置 HTTP 验证规则 @Override protected void configure(HttpSecurity http) throws Exception { String[] arrOpsServerLanIPs = mStrOpsServerLanIP.split(";"); String strAccessFilterForOps = "hasIpAddress('127.0.0.1')"; for (String strTmp:arrOpsServerLanIPs){ strAccessFilterForOps += " or hasIpAddress('"+ strTmp +"')"; } http.csrf().disable() // 关闭csrf验证 .authorizeRequests() // 对请求进行认证 .antMatchers(ApiURI.URI_ACCESS_TOKEN_CHECK).permitAll() .antMatchers(ApiURI.URI_FILE_BUSI_XXX).permitAll() .antMatchers("/").permitAll() .anyRequest().authenticated() //所有其他请求需要身份认证 .and() .addFilterBefore(new ApiJWTBizFilterMgr(ApiURI.URI_ALL_BUSI_XXX, authenticationManager()), UsernamePasswordAuthenticationFilter.class); /*.addFilterBefore(new ServerStatusMonitorFilter(ThirdApiURI.URI_HGAS_MONITOR_XXX, authenticationManager()), UsernamePasswordAuthenticationFilter.class);*/ } @Override public void configure(WebSecurity web) throws Exception { /*web.ignoring() .antMatchers("/error") .antMatchers("/static") .antMatchers("/static/**"); // 所有/static下的静态资源请求时都忽略访问规则 */ } }