文章目录

  •     基于表达式的访问控制
    •       1 access()方法使用
        •       1.1 以 hasRole 和 permitAll 举例
    •        2 使用自定义方法
    •    接口
    •      实现类
    •   修改配置项

    基于表达式的访问控制

      1 access()方法使用

      之前的登录用户权限判断实际上底层实现都是调用 access(表达式)
      可以通过 access()实现和之前学习的权限控制完成相同的功能。

      1.1 以 hasRole 和 permitAll 举例

      下面代码和直接使用 permitAll()和 hasRole()是等效的。

       2 使用自定义方法

      虽然这里面已经包含了很多的表达式(方法)但是在实际项目中很 有可能出现需要自己自定义逻辑的情况。
      判断登录用户是否具有访问当前 URL 权限

   接口

public interface MyAccess {
    boolean hasPermit(HttpServletRequest request, Authentication authentication);
}

     实现类

@Component
public class MyAccessImpl implements  MyAccess {
    @Override
    public boolean hasPermit(HttpServletRequest request, Authentication authentication) {
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        return authorities.contains(new SimpleGrantedAuthority(request.getRequestURI()));
    }
}

  修改配置项

      最后一项 ==.anyRequest().authenticated(); ==需要被注释,因为所有配置项取得是交集,如果这一项在的话就表示只要认证就可以访问了

 //授权:权限控制
        http.authorizeRequests()
                .antMatchers("/login.html").permitAll() // login.html 这个请求不需要认证
                .antMatchers("/fail.html").permitAll()  // fail.html 这个请求不需要认证
             .anyRequest().access("@myAccessImpl.hasPermit(request,authentication)");
//                .anyRequest().authenticated(); // 所有的请求都必须被认证

更多推荐

Spring Security--基于表达式的访问控制 access的使用