RbacServiceImpl

来源:8-1 课程总结

Ferris_Yang

2018-04-12

@Component("rbacService")

public class RbacServiceImpl implements RbacService {


private AntPathMatcher antPathMatcher = new AntPathMatcher();


@Override

public boolean hasPermission(HttpServletRequest request, Authentication authentication) {

Object principal = authentication.getPrincipal();


boolean hasPermission = false;


if (principal instanceof Admin) {

//如果用户名是admin,就永远返回true

if (StringUtils.equals(((Admin) principal).getUsername(), "admin")) {

hasPermission = true;

} else {

// 读取用户所拥有权限的所有URL

Set<String> urls = ((Admin) principal).getUrls();

for (String url : urls) {

if (antPathMatcher.match(url, request.getRequestURI())) {

hasPermission = true;

break;

}

}

}

}


return hasPermission;

}


}


这里有个问题,Object principal = authentication.getPrincipal(); 这个 principal 应该是 username 或者 mobile,不是 UserDetail 的一个实现啊,怎么能用 if (principal instanceof Admin) 来做呢?

在 SmsCodeAuthenticationToken 里:

public SmsCodeAuthenticationToken(String mobile) {
   super(null);
   this.principal = mobile;
   setAuthenticated(false);
}

在 UsernamePasswordAuthenticationFilter 里

UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
     username, password);

在 UsernamePasswordAuthenticationToken 里:

public UsernamePasswordAuthenticationToken(Object principal, Object credentials) {
  super(null);
  this.principal = principal;
  this.credentials = credentials;
  setAuthenticated(false);
}

都能表明,principal 不是 UserDetail 的一个实例。

所以,麻烦老师给解释一下 RbacServiceImpl 里面的代码为什么判断 principal 是 UserDetail 的一个实例的写法。

写回答

1回答

JoJo

2018-04-16

根据登录方式和登录结果的不同,principal可能是各种类型的数据。但是当用表单登录成功时,principal肯定是个UserDetails的实例。一般内管都表单登录的,所以做了这样一个判断。

0
0

Spring Security技术栈开发企业级认证与授权

Spring Security技术栈,REST风格开发常见接口,独立开发认证授权模块保证REST服务安全

2662 学习 · 1561 问题

查看课程