1、基于數(shù)據(jù)庫的認(rèn)證(Mybstis)
user表
role表
創(chuàng)建User實(shí)現(xiàn)UserDetails接口
public class User implements UserDetails {
.......
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<SimpleGrantedAuthority> authorities = new ArrayList<>();
for (Role role : roles) {
authorities.add(new SimpleGrantedAuthority("ROLE_"+role.getName()));
}
return authorities;
}
}
UserService實(shí)現(xiàn)UserDetailsService
@Service
public class UserService implements UserDetailsService {
@Autowired
UserMapper userMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userMapper.loadUserByUsername(username);
if (user==null){
throw new UsernameNotFoundException("用戶不存在!");
}
user.setRoles(userMapper.getUserRolesById(user.getId()));
return user;
}
}
完善UserMapper
@Mapper
public interface UserMapper {
@ResultType(User.class)
@Select("select * from user where username=#{username}")
User loadUserByUsername(String username);
@ResultType(Role.class)
@Select("select * from role where id in (select rid from user_role where uid=#{id})")
List<Role> getUserRolesById(Integer id);
}
配置SecurityConfig(root有dba自沧、admin權(quán)限,admin具有admin權(quán)限,sang擁有user權(quán)限)
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserService userService;
@Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/abd/**").hasRole("dba")
.antMatchers("/admin/**").hasRole("admin")
.antMatchers("/user/**").hasRole("user")
.anyRequest().authenticated()
.and()
.formLogin()
.permitAll()
.and()
.csrf().disable();
}
}
角色繼承 (dba>admin>user使用‘\n’分隔關(guān)系)
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
RoleHierarchy roleHierarchy(){
RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
String hierarchy="ROLE_dba > ROLE_admin \n ROLE_admin > ROLE_user";
roleHierarchy.setHierarchy(hierarchy);
return roleHierarchy;
}
}