gpt4 book ai didi

java - Spring Security @Secured 注解和用户权限

转载 作者:行者123 更新时间:2023-12-02 08:03:12 29 4
gpt4 key购买 nike

这是关于 Spring v.4(MVC + 安全性)的内容。我已经实现了 UserDetailsS​​erviceImpl,其中在 loadUserByUsername 方法中向用户授予了权限。假设它很简单:

public UserDetails loadUserByUsername(String username) {
...
Collection<GrantedAuthority> authorities = new ArrayList<>();

authorities.add(new SimpleGrantedAuthority("ADMIN"));

return new org.springframework.security.core.userdetails.User(username, password, enabled, true, true, true, authorities);
...
}

并且有一个安全 Controller ,其中有一个带有 @Secured 注释的注释方法:

@Secured("ADMIN")
@RequestMapping(value = "/users", method = RequestMethod.GET)
public String users(Model model ...) { ... }

正如您在 loadUserByUsername 方法中看到的,我显式向用户授予了 ADMIN 角色。但是当我尝试访问 /users 时,我收到 访问被拒绝 异常:

2016-04-19 10:25:16,899 DEBUG (http-nio-8080-exec-9)[org.springframework.security.web.access.ExceptionTranslationFilter] -Access is denied (user is not anonymous); delegating toAccessDeniedHandlerorg.springframework.security.access.AccessDeniedException: Access isdenied atorg.springframework.security.access.vote.AbstractAccessDecisionManager.checkAllowIfAllAbstainDecisions(AbstractAccessDecisionManager.java:70)atorg.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:88)atorg.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:232)atorg.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:64)atorg.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)atorg.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655)...

(没有@Secured注释一切正常)。

我在这里错过了什么?

最佳答案

令人惊讶的是,问题出在角色名称上。由于 defaultRolePrefix 设置为 ROLE_ (请参阅 org.springframework.security.access.vote.RoleVoter 类),所有角色的名称都应以带有 ROLE_ 前缀。换句话说,当我改变了

authorities.add(new SimpleGrantedAuthority("ADMIN"));

authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));

@Secured("ADMIN")@Secured("ROLE_ADMIN") - 一切都变得很好。

关于java - Spring Security @Secured 注解和用户权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36711538/

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