Document

@preauthorize使用

在Spring Security中使用PreAuthorize调用自己的方法

如果您想在Spring Security方法授权中使用一些复杂的逻辑进行授权,则可以调用任何bean的方法。

顺便说一句,如果您想正确添加自定义身份验证,则实现PermissionEvaluator可能是合法的方法。
本文很容易理解,并详细介绍了PermissionEvaluator的实现。

  • 在控制器端上进行预授权定义

Controller.java

// An highlighted block
@PreAuthorize(“@customPreAuthorizer.belongGroup(#groupId, authentication.principal)”)
@RequestMapping(“/group/{groupId}/list”)
   public String list(Model model, @PathVariable(“groupId”) Long groupId) {
}
  • Bean定义

CustomPreAuthorizer.java

@Component
public class CustomPreAuthorizer {
    public boolean belongGroup(Long groupId, UserDetails userDetails) {
         // 自定义逻辑
        return true;
    }
}

您可以通过在PreAuthorize表达式的Bean名称开头添加@来引用注册为组件的Bean。
@customPreAuthorizer 可以将认证用户的用户信息作为参数传递给authentication.principal。

如果传递给PreAuthorize中的参数的描述是多余的,则可以通过在方法中调用SecurityContext获得相同的内容,因此可以在方法中对其进行检索。

CustomPreAuthorizer.java

// An highlighted block
@Component
public class CustomPreAuthorizer {
    public boolean belongGroup(Long groupId) {
        var userDetails = (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return true;
    }
}

 

之后,如果扩展UserDetails并在登录时拥有必要的信息,则可以实现并提供扩展的原始授权。

 

posted @ 2022-09-27 18:12  从未被超越  阅读(707)  评论(0)    收藏  举报