gpt4 book ai didi

java - 在 Spring 应用程序中使用 SecurityContextHolder 的安全实用程序

转载 作者:行者123 更新时间:2023-12-01 12:25:27 25 4
gpt4 key购买 nike

在我的 spring 应用程序中,我对 Controller 方法有一些方面,我在其中进行一些安全检查。因为我需要更频繁地进行多次检查,所以我将它们包装到“sercurityUtil”类的静态辅助方法中。:

public abstract class SecurityUtils {

public static Authentication getCurrentAuthentication(){
return SecurityContextHolder.getContext().getAuthentication();
}

public static ChroniosUser getAuthenticatedUser(){
return (ChroniosUser) getCurrentAuthentication().getPrincipal();
}

public static boolean authenticationHasRole(Authentication authentication, Role role){
SimpleGrantedAuthority grantedAuthority = new SimpleGrantedAuthority(role.getRoleIdentifier());
return authentication.getAuthorities().contains(grantedAuthority);
}

public static boolean authenticatedUserIsAdmin(){
Authentication authentication = getCurrentAuthentication();
return authenticationHasRole(authentication, ADMIN);
}

...
}

这是一个有效且好的方法吗?或者关闭我将这些辅助函数包装到 Spring 服务中?

谢谢。

PS:我知道我可以使用@PreAuthorize ...但我的方面更复杂。

最佳答案

简短的答案是:

是的这似乎是一个有效且好的方法。

长答案是:

这取决于你。

Spring Security 文档指出,其基础架构完全基于标准 servlet 过滤器,并且与任何特定 Web 技术(包括 Spring MVC)没有强链接

Spring Security’s web infrastructure is based entirely on standard servlet filters. It doesn’t use servlets or any other servlet-based frameworks (such as Spring MVC) internally, so it has no strong links to any particular web technology. It deals in HttpServletRequest s and HttpServletResponse s and doesn’t care whether the requests come from a browser, a web service client, an HttpInvoker or an AJAX application

[Spring Security Reference - 1. The Security Filter Chain]

它的使用几乎完全基于SecurityContextHolder 。提供的示例是通过静态方法:

Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

如您所见,它不是 Spring Bean/服务/组件。 SecurityContextHolder 本身看起来像一个实用程序类。

现在您可以创建一个 Spring 服务来公开它,或者您可以通过经典的 Util class 使用它取决于什么对您和您的应用更实用。

关于java - 在 Spring 应用程序中使用 SecurityContextHolder 的安全实用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26379290/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com