81,122
社区成员




@Configuration
public class LibvanMvcConfig implements WebMvcConfigurer {
/**
* 跨域访问
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedHeaders("Content-Type", "X-Requested-With", "accept,Origin", "Access-Control-Request-Method",
"Access-Control-Request-Headers", "token")
.allowedMethods("*").allowedOrigins("*").allowCredentials(true);
}
}
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class LibvanSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserDetailsService userDetailsService;
@Autowired
LibvanJwtException libvanJwtException;
@Autowired
LibvanAccessException libvanAccessException;
@Override
public void configure(WebSecurity web) throws Exception {
// druid管理控制台,用户注册,用户登录功能和swagger文档放行
web.ignoring().antMatchers( ///////////////////// swagger权限///////////////////
"/swagger-ui.html", "/swagger-resources/**", "/images/**", "/webjars/**", "/v2/api-docs",
///////////////////// druid权限///////////////////
"/configuration/ui", "/configuration/security", "/druid/**",
/////////// 账号注册的权限/////////账号登录的权限////////
"/api/user/register", "/api/user/login");
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// 校验用户账号密码
auth.userDetailsService(userDetailsService).passwordEncoder(new PasswordEncoder() {
// 对密码进行加密
@Override
public String encode(CharSequence charSequence) {
StaticLog.info(LibvanSecurityConfig.class.getSimpleName(), charSequence.toString());
return DigestUtils.md5DigestAsHex(charSequence.toString().getBytes());
}
// 对密码进行判断匹配
@Override
public boolean matches(CharSequence charSequence, String s) {
String encode = DigestUtils.md5DigestAsHex(charSequence.toString().getBytes());
boolean res = s.equals(encode);
return res;
}
});
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// 错误处理和异常捕获
.exceptionHandling().accessDeniedHandler(libvanAccessException).and().exceptionHandling()
.authenticationEntryPoint(libvanJwtException).and()
// 因为使用JWT,所以不需要HttpSession
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()
// 跨域预检
.requestMatchers(CorsUtils::isPreFlightRequest).permitAll().anyRequest().authenticated().and().cors()
.and().csrf().disable();
// 使用自定义的 Token过滤器 验证请求的Token是否合法
http.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
http.headers().cacheControl();
}
@Bean
public JwtTokenFilter authenticationTokenFilterBean() throws Exception {
return new JwtTokenFilter();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
@Component
public class LibvanAccessException implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
AccessDeniedException accessDeniedException) throws IOException, ServletException {
String message =accessDeniedException.getMessage();
LibvanResponse libvanResponse = new LibvanResponse();
ApiUtils.apiFial(libvanResponse, message);
response.setStatus(200);
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
response.getWriter().println(JSONUtil.parse(libvanResponse));
}
}