之前学习的登录用户权限判断实际上底层实现都是调用access(表达式),我们可以通过access()实现和hasAuthority,hasRole等的权限控制完成相同的功能。
public ExpressionUrlAuthorizationConfigurer<H>.ExpressionInterceptUrlRegistry hasAuthority(String authority) {
return this.access(ExpressionUrlAuthorizationConfigurer.hasAuthority(authority));
}
private static String hasAuthority(String authority) {
return "hasAuthority('" + authority + "')";
}
Expression表达式如下
也可以在源码中查找
private static String hasAnyRole(String... authorities) {
String anyAuthorities = StringUtils.arrayToDelimitedString(authorities, "','ROLE_");
return "hasAnyRole('ROLE_" + anyAuthorities + "')";
}
private static String hasRole(String role) {
Assert.notNull(role, "role cannot be null");
if (role.startsWith("ROLE_")) {
throw new IllegalArgumentException("role should not start with 'ROLE_' since it is automatically inserted. Got '" + role + "'");
} else {
return "hasRole('ROLE_" + role + "')";
}
}
private static String hasAuthority(String authority) {
return "hasAuthority('" + authority + "')";
}
private static String hasAnyAuthority(String... authorities) {
String anyAuthorities = StringUtils.arrayToDelimitedString(authorities, "','");
return "hasAnyAuthority('" + anyAuthorities + "')";
}
private static String hasIpAddress(String ipAddressExpression) {
return "hasIpAddress('" + ipAddressExpression + "')";
}
虽然这里面已经包含了很多的表达式(方法)但是在实际项目中很有可能出现需要自己自定义逻辑的情况。 例如:实现判断登录用户是否具有访问当前URL权限
public interface MyService {
boolean hasPermission(HttpServletRequest request, Authentication authentication);
}
@Service
public class MyServiceImpl implements MyService {
@Override
public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
Object principal = authentication.getPrincipal();
String requestURI = request.getRequestURI();
System.out.println(requestURI);
if(principal instanceof User){
User user=(User)principal;
Collection<GrantedAuthority> authorities = user.getAuthorities();
boolean contains = authorities.contains(new SimpleGrantedAuthority(requestURI));
System.out.println(contains);
return authorities.contains(new SimpleGrantedAuthority(requestURI));
}
return false;
}
}
http.authorizeRequests()
.antMatchers("/testaccess").access("@myServiceImpl.hasPermission(request,authentication)")
@RequestMapping("/testaccess")
@ResponseBody
public String toaccess(){
return "testaccess";
}