在网上看到很多教程,登陆到不同的路径或页面,讲的都很模糊。或者说没有贴代码,只给了部分思路。在做项目的时候踩了不少坑,在此记录一下。
配置Security
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) // 启用方法安全设置
public class SecurityConfig extends WebSecurityConfigurerAdapter {//首先是继承WebSecurityConfigurerAdapter
private static final String KEY="wxj1994";
@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;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/css/**", "/js/**", "/fonts/**","/Playerss","manage/**").permitAll() // 都可以访问
.antMatchers("/h2-console/**").permitAll() // 都可以访问
.antMatchers("/admins/**").hasRole("ADMIN") // 需要相应的角色才能访问
.and()
.formLogin() //基于 Form 表单登录验证
.loginPage("/login").failureUrl("/login-error").defaultSuccessUrl("/admin/adminindex").successHandler(new LoginSuccessHandle()) // 自定义登录界面
.and().rememberMe().key(KEY) // 启用 remember me
.and().exceptionHandling().accessDeniedPage("/403"); // 处理异常,拒绝访问就重定向到 403 页面
http.csrf().ignoringAntMatchers("/h2-console/**"); // 禁用 H2 控制台的 CSRF 防护
http.headers().frameOptions().sameOrigin(); // 允许来自同一来源的H2 控制台的请求
}
@Override
public void configure(WebSecurity web) throws Exception {
//解决静态资源被拦截的问题
web.ignoring().antMatchers("/manage/**","/css/**","/js/**");
}
/***
* 认证信息管理
* **/
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
auth.authenticationProvider(authenticationProvider());
}
}
***这一段主要是配置不同的角色登陆不同的路径或者页面***
接下来创建一个LoginSuccessHandle 实现AuthenticationSuccessHandler接口
public class LoginSuccessHandle implements AuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)throws IOException {
Set<String> roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
//获取到登陆者的权限,然后做跳转
if (roles.contains("ROLE_ADMIN")){
response.sendRedirect("/****");
return;
}else if (roles.contains("ROLE_USER")){
response.sendRedirect("/*****");
System.out.println();
return;
}else {
response.sendRedirect("/403");
}
}
}
在 response.sendRedirect(“/**“);里面写上你不同角色登陆的不同路径
OK 大功告成!