**
**
1.根据百度一些demo,多番尝试以后能够使用。
2.仅做记录,便于以后更好的改进和研究。
//SecurityConfig
import com.guyi.core.security.filter.JwtAuthenticationTokenFilter;
import com.guyi.core.security.handle.AuthenticationEntryPointImpl;
import com.guyi.core.security.handle.LogoutSuccessHandlerImpl;
import com.guyi.core.web.service.ManageUserDetailsServiceImpl;
import com.guyi.core.web.service.WebUserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.BeanIds;
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.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.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.web.filter.CorsFilter;
/**
* @program: displayserve
* @description:
* @author: ZH
* @create: 2022-06-10 14:21
**/
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig {
@Configuration
@Order(1)
public static class ManageConfigurationAdapter extends WebSecurityConfigurerAdapter {
// @Bean("manageAuthenticationManager")
// @Override
// public AuthenticationManager authenticationManagerBean() throws Exception {
// return super.authenticationManagerBean();
// }
// @Autowired
@Qualifier("manageAuthenticationManager")
// private AuthenticationManager authenticationManager;
@Bean("manageAuthenticationManager")
@Override
@Primary
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Autowired
@Qualifier("manageUserDetailsServiceImpl")
private UserDetailsService manageUserService;
/**
* 认证失败处理类
*/
@Autowired
private AuthenticationEntryPointImpl unauthorizedHandler;
/**
* 退出处理类
*/
@Autowired
private LogoutSuccessHandlerImpl logoutSuccessHandler;
/**
* token认证过滤器
*/
@Autowired
private JwtAuthenticationTokenFilter authenticationTokenFilter;
/**
* 跨域过滤器
*/
@Autowired
private CorsFilter corsFilter;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
// daoAuthenticationProvider.setUserDetailsService(manageUserService);
// daoAuthenticationProvider.setPasswordEncoder(new BCryptPasswordEncoder());
// auth.authenticationProvider(daoAuthenticationProvider);
auth.userDetailsService(manageUserService).passwordEncoder(manageBcrypt());
}
@Bean
public BCryptPasswordEncoder manageBcrypt() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
// CSRF禁用,因为不使用session
.csrf().disable()
// 认证失败处理类
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
// 基于token,所以不需要session
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
// 过滤请求
.authorizeRequests()
// 对于登录login 注册register 验证码captchaImage 允许匿名访问
//html用户登录htmlLogin 发送邮箱验证sendCode 更改密码modifyPassword 注册html用户registerHtml
.antMatchers("/login").permitAll()
.antMatchers(
HttpMethod.GET,
"/",
"/*.html",
"/**/*.html",
"/**/*.css",
"/**/*.js",
"/profile/**"
).permitAll()
.antMatchers("/swagger-ui.html").anonymous()
.antMatchers("/swagger-resources/**").anonymous()
.antMatchers("/webjars/**").anonymous()
.antMatchers("/*/api-docs").anonymous()
.antMatchers("/druid/**").anonymous()
// 除上面外的所有请求全部需要鉴权认证
.anyRequest().authenticated()
.and()
.headers().frameOptions().disable();
httpSecurity.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler);
// 添加JWT filter
httpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
// 添加CORS filter
httpSecurity.addFilterBefore(corsFilter, JwtAuthenticationTokenFilter.class);
httpSecurity.addFilterBefore(corsFilter, LogoutFilter.class);
}
}
@Configuration
@Order(2)
public static class WebConfigurationAdapter extends WebSecurityConfigurerAdapter {
@Autowired
@Qualifier(value = "webUserDetailsServiceImpl")
private UserDetailsService webUserService;
@Bean("webAuthenticationManager")
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
/**
* 认证失败处理类
*/
@Autowired
private AuthenticationEntryPointImpl unauthorizedHandler;
/**
* 退出处理类
*/
@Autowired
private LogoutSuccessHandlerImpl logoutSuccessHandler;
/**
* token认证过滤器
*/
@Autowired
private JwtAuthenticationTokenFilter authenticationTokenFilter;
/**
* 跨域过滤器
*/
@Autowired
private CorsFilter corsFilter;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(webUserService).passwordEncoder(webCrypt());
// DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
// daoAuthenticationProvider.setUserDetailsService(webUserService);
// daoAuthenticationProvider.setPasswordEncoder(new BCryptPasswordEncoder());
// auth.authenticationProvider(daoAuthenticationProvider);
}
@Bean
public BCryptPasswordEncoder webCrypt() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
// CSRF禁用,因为不使用session
.csrf().disable()
// 认证失败处理类
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
// 基于token,所以不需要session
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
// 过滤请求
.authorizeRequests()
// 对于登录login 注册register 验证码captchaImage 允许匿名访问
//html用户登录htmlLogin 发送邮箱验证sendCode 更改密码modifyPassword 注册html用户registerHtml
.antMatchers("/login").permitAll()
.antMatchers(
HttpMethod.GET,
"/",
"/*.html",
"/**/*.html",
"/**/*.css",
"/**/*.js",
"/profile/**"
).permitAll()
.antMatchers("/swagger-ui.html").anonymous()
.antMatchers("/swagger-resources/**").anonymous()
.antMatchers("/webjars/**").anonymous()
.antMatchers("/*/api-docs").anonymous()
.antMatchers("/druid/**").anonymous()
// 除上面外的所有请求全部需要鉴权认证
.anyRequest().authenticated()
.and()
.headers().frameOptions().disable();
httpSecurity.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler);
// 添加JWT filter
httpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
// 添加CORS filter
httpSecurity.addFilterBefore(corsFilter, JwtAuthenticationTokenFilter.class);
httpSecurity.addFilterBefore(corsFilter, LogoutFilter.class);
}
}
}
//登录方法层
//这里的6 可能在你的方法中并不是 请根据实际更改
String methodName = Thread.currentThread().getStackTrace()[6].getMethodName();
//
if ("manageAuthenticationManager".equalsIgnoreCase(methodName)) {
boolean captchaOnOff = configService.selectCaptchaOnOff();
// 验证码开关
if (captchaOnOff) {
validateCaptcha(username, uuid);
}
}
// 用户验证
Authentication authentication = null;
try {
AuthenticationManager authenticationManager = SpringUtils.getBean(methodName);
authentication = authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken(username, password));