1.access()方法使用
1)使用理由
之前学习的登录用户权限判断实际上底层实现都是调用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 + "')";
}
2.使用自定义方法
虽然这里面已经包含了很多的表达式(方法)但是在实际项目中很有可能出现需要自己自定义逻辑的情况。
例如:实现判断登录用户是否具有访问当前URL权限
1)自定义service接口和实现类,在实现类实现判断逻辑
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;
}
}
2)修改配置类
http.authorizeRequests()
.antMatchers("/testaccess").access("@myServiceImpl.hasPermission(request,authentication)")
3)编写控制器
@RequestMapping("/testaccess")
@ResponseBody
public String toaccess(){
return "testaccess";
}
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/2352.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...