当使用角色的权限过滤时,碰到了一点小问题.
@Component
public class MyUserDetailService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
//模拟数据库查询用户
Map map = Constant.getMap.get();
UserInfo user = (UserInfo) map.get(name);
if (user == null) {
throw new UsernameNotFoundException("用户名不存在");
}
return user;
}
}
public class Constant {
public static class getMap {
private static Map map;
public static Map get() {
if (map == null) {
map = new HashMap();
}
map.put("gao", new UserInfo() {{
setId(1L);
setPassword(new BCryptPasswordEncoder().encode("123"));
setUserName("gao");
List list = new ArrayList<>();
list.add("admin");
setRoles(list);
}});
map.put("yang", new UserInfo() {
{
setId(2L);
setPassword(new BCryptPasswordEncoder().encode("321"));
setUserName("yang");
List list = new ArrayList<>();
list.add("guest");
setRoles(list);
}
});
return map;
}
}
}
上面是我写死的数据,根据用户名得到了用户角色,gao这个用户是admin这个角色,我将一个接口也设置为了只能admin这个角色用户可以访问,但是一直报权限不足;遂各种找原因,然后再网上看到了解决办法...
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.httpBasic().authenticationEntryPoint(notLogin)
.and()
.formLogin()
.successHandler(loginSuccesssHandler)
.failureHandler(loginFailHandler)
.permitAll()
.and()
.authorizeRequests()
.antMatchers("/open")
.permitAll()
.antMatchers("/index")
.access("hasRole('admin')")
.and()
.authorizeRequests()
.anyRequest()
.authenticated();
http.exceptionHandling().accessDeniedHandler(deniedHandler);
http.addFilterBefore(myFilter, UsernamePasswordAuthenticationFilter.class);
}
这里权限设置中心里的hasRole这里依然不用动,就是保持admin,但是我们需要在数据库存储用户角色时,要存为以ROLE_为开通u的数据,这样就可以了.这个是springboot继承springsecutity默认的设置.
list.add("ROLE_admin");
当然如果使用的是hasAuthority(),那么就没有这个问题;