1

当谈到 Spring Security 应用程序中的 GrantedAuthority 对象时,我有一个担忧。我正在寻找一种处理事情的好方法。首先,我试图描述我的担忧,如果有任何事实错误,请毫不犹豫地指出,我将不胜感激。

Spring Security 使用 GrantedAuthority 实例在应用程序的不同部分充当授权令牌。

默认情况下,GrantedAuthority 可以将自身呈现为字符串。当使用@Secured("ROLE_NAME")保护方法,或使用 Spring XML 配置保护 URL或以编程方式检查HttpServletRequest 请求时,如if(request.isUserInRole("ROLE_NAME")) {..}您用于指定要检查的权限的字符串。

我想知道在应用程序的几个地方使用静态字符串的含义。如果更改了角色名称,开发人员必须查找所有旧字符串并更新它们。如果缺少一个字符串,则不会出现编译时错误,只会在运行时出现问题。

在 Spring Security 应用程序中处理 GrantedAuthority 对象时,您认为最好的方法是什么?你的解决方案有什么优点和缺点?

4

3 回答 3

2

First off, if possible, only do your checks at a particular place in the application (e.g. an HTTP interceptor at the beginning of the request), and using only one of the mentioned approaches. This is a good practice since you will be able to know authoritatively when a user becomes authorized.

If this is not possible, use enums for the role names and only compare on the enums. Therefore, if you wanted to locate all usages in the application it's a simple search.

于 2009-05-05T15:47:06.527 回答
0

我认为这里没有什么大问题。GrantedAuthority 不太可能更改密钥。只是不要将您的角色命名为 ROLE_A。

此外,我个人更喜欢 XML 安全配置而不是注解。一般来说,将任何相关配置保存在一个地方看起来是个好主意。

于 2009-05-05T14:00:14.410 回答
-1

在 Spring 和其他框架(尤其是对于动态语言)中,使用“约定优于配置”。如果您可以自己定义角色名称,您很容易发现需要更多的代码行。

所以坚持约定。始终使用以下 3 个角色,ROLE_ANONYMOUS、ROLE_ADMIN 和 ROLE_USER。如果您需要另一个,请相应地命名并在所有场合使用它。文档很重要。

单元测试也被导入。在编译器未捕获错误的情况下,它可以帮助您。

于 2009-05-05T14:01:09.120 回答