package com.rzyc.config; import com.rzyc.filter.JwtAuthenticationTokenFiler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; 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.config.http.SessionCreationPolicy; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; /** * spring security config * @author Xuwanxin * @date 2022/9/26 * */ @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter { /** * 数据库用户连接 */ private UserDetailsService userService; /** * token jwt 验证拦截器 * */ private JwtAuthenticationTokenFiler jwtAuthenticationTokenFiler; @Autowired public void setSecurityConfigFinder(UserDetailsService userService,JwtAuthenticationTokenFiler jwtAuthenticationTokenFiler) { this.userService = userService; this.jwtAuthenticationTokenFiler = jwtAuthenticationTokenFiler; } @Bean public PasswordEncoder getPasswordEncoder() { return new BCryptPasswordEncoder(); } /** * 暴露AuthenticationManager,存上下文 * */ @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() // 对于登录接口 允许匿名访问 .antMatchers("pcPersonal/pclogin","pcPersonal/pcManageLogin","generateCode").anonymous() //放行swagger .antMatchers("/swagger-ui.html","/swagger-resources/**","/webjars/**","/v2/**","/api/**").permitAll() // 除上面外的所有请求全部需要鉴权认证,配置退出路径 .anyRequest().authenticated() .and() .logout().logoutUrl("/logout") .and() //关闭security默认登陆框 .formLogin().disable() //关闭csrf .csrf().disable() //不通过Session获取SecurityContext .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and().addFilterBefore(jwtAuthenticationTokenFiler, UsernamePasswordAuthenticationFilter.class) ; } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { // 配置数据库访问,认证步骤 auth.userDetailsService(userService); } }