private static final String KEY = "yangmd.com";
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private PasswordEncoder passwordEncoder;
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(); // 使用 BCrypt 加密
}
@Bean
public AuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(userDetailsService);
authenticationProvider.setPasswordEncoder(passwordEncoder); // 设置密码加密方式
return authenticationProvider;
}
/**
* 自定义配置
* @param
* @param
* @return
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
// http.headers().frameOptions().disable();
// http.authorizeRequests()
// .antMatchers("/css/**","js/**","fonts/**","index").permitAll() //这些都可以访问
// .antMatchers("/users/**").hasRole("ADMIN") //需要对应角色才能访问
// .and()
// .formLogin() //基于form表单登录验证
// .loginPage("/login").failureUrl("/login-error"); //自定义登录界面
http.headers().frameOptions().disable();
http.authorizeRequests().antMatchers("/css/**", "/js/**", "/fonts/**", "/index").permitAll() // 都可以访问
.antMatchers("/h2-console/**").permitAll() // 都可以访问
.antMatchers("/admins/**").hasRole("ADMIN") // 需要相应的角色才能访问
.and()
.formLogin() //基于 Form 表单登录验证
.loginPage("/login").failureUrl("/login-error") // 自定义登录界面
.and().rememberMe().key(KEY) // 启用 remember me
.and().exceptionHandling().accessDeniedPage("/403"); // 处理异常,拒绝访问就重定向到 403 页面
http.csrf().ignoringAntMatchers("/h2-console/**"); // 禁用 H2 控制台的 CSRF 防护
http.headers().frameOptions().sameOrigin(); // 允许来自同一来源的H2 控制台的请求
}
/**
* 认证信息管理
* @param auth
* @param
* @return Exception
*/
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)throws Exception{
// auth.inMemoryAuthentication() //认证信息存储于内存中
// .withUser("admin").password("111111").roles("ADMIN"); //先初始化了信息
auth.userDetailsService(userDetailsService);
auth.authenticationProvider(authenticationProvider());
}
毕设 Elasticsearch搜索+Thymeleaf模板+JPA+Security+BootStrap
了解课程