之前都用shiro对用户登录后的权限认证及controller请求地址拦截,现在想通过SpringSecuryConfig实现权限的控制,结果2步可以实现,具体实现如下:
1、创建SpringSecuryConfig类
@Configuration
@EnableWebSecurity
public class SpringSecuryConfig extends WebSecurityConfigurerAdapter{
@Autowired
private CustomUserDetailsService customUserDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/bower_components/**", "/css/**", "/js/**","/img/**","/").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.successForwardUrl("/dashboard")
.and()
.logout()
.logoutSuccessUrl("/login")
.invalidateHttpSession(true);
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder());
auth.eraseCredentials(false);
//auth.inMemoryAuthentication()
// .withUser("user").password("password").roles("USER");
}
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(4);
}
/**
* 登录成功执行的方法
*/
@Bean
public AuthenticationSuccessHandler successHandler() {
return new MyAuthenticationSuccessHandler();
}
}
2、创建CustomUserDetailsService类,该类是用户登录帐号,密码的校验,实现如下:
@Component
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
private UserService userService; //可以替换成自己的用户类
@Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
User user = userService.checkUserByName(userName); //通过登录用户名获得数据库用户类
if (user == null) {throw new UsernameNotFoundException("UserName not found");}
List<SimpleGrantedAuthority> authorities = new ArrayList<>();
return new SafeUser(user, user.getName(), user.getPassword(), authorities);
}
}
网友评论