Spring Security 角色不起作用

Posted

技术标签:

【中文标题】Spring Security 角色不起作用【英文标题】:Spring Security roles are not working 【发布时间】:2015-07-29 14:31:41 【问题描述】:

我已经在我的应用程序中配置了 Spring Security,身份验证运行良好,但授权不起作用意味着 @secured() 注释不起作用。当我访问 url 时出现错误“出现意外错误 (type=Forbidden, status=403)。 访问被拒绝”。

我的弹簧配置是

@Autowired
    private MongoDBAuthenticationProvider authenticationProvider;

    @Override
    public void configure(WebSecurity web) throws Exception 
        web.ignoring().antMatchers("/js/**", "/css/**");
    

    @Override
    protected void configure(HttpSecurity http) throws Exception 

        http.formLogin().defaultSuccessUrl("/resource")
                .and().logout().and().authorizeRequests()
                .antMatchers("/logout").permitAll()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .anyRequest()
                .authenticated()
                .and().csrf().disable();
    

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception 
        auth.authenticationProvider(authenticationProvider);
    

我的控制器是

@RestController
@RequestMapping("/user")
public class UserController 

    @Autowired
    UserService userService;

    @Secured(value="ROLE_ADMIN")
    @RequestMapping(value = "/id", method = RequestMethod.GET)
    public void getUser() 
        System.out.println("working");
    

数据库用户是

 "_id" : ObjectId("555982a5360403572551660c"), "username" : "user", "password" : "pass", "role" : "ADMIN" 

我的 mongodb 身份验证提供程序

@Service
public class MongoDBAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider


    @Autowired
    MongoUserDetailsService mongoUserDetailsService;

    @Autowired MongoTemplate mongoTemplate;

    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException 

    

    @Override
    protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException 

        UserDetails loadedUser;

        try 
            loadedUser = mongoUserDetailsService.loadUserByUsername(username);
         catch (Exception repositoryProblem) 
            throw new InternalAuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem);
        

        if (loadedUser == null) 
            throw new InternalAuthenticationServiceException(
                    "UserDetailsService returned null, which is an interface contract violation");
        
        return loadedUser;
    

用户域

public class User 

    @Id
    private String id;
    @NotNull
    private String name;
    private int age;
    private String username;
    private String password;
    private String role;




    public User() 
        super();        
    



    public User(String name,String username,
            String password, String role) 
        super();
        this.name = name;
        this.username = username;
        this.password = password;
        this.role = role;
    



    public String getId() 
        return id;
    



    public void setId(String id) 
        this.id = id;
    



    public String getName() 
        return name;
    


    public void setName(String name) 
        this.name = name;
    

    public int getAge() 
        return age;
    


    public void setAge(int age) 
        this.age = age;
    


    public String getUsername() 
        return username;
    


    public void setUsername(String username) 
        this.username = username;
    


    public String getPassword() 
        return password;
    


    public void setPassword(String password) 
        this.password = password;
    



    public String getRole() 
        return role;
    



    public void setRole(String role) 
        this.role = role;
    


【问题讨论】:

您的角色是 ADMIN 而不是 ROLE_ADMIN。修复您的 @Secured 表达式或更改数据库中的用户。还有hasRole前缀ROLE_ 你的意思是我应该写 @Secured(value="ADMIN") ? 请发布完整的堆栈跟踪 【参考方案1】:
@Secured(value="ADMIN")

而不是

@Secured(value="ROLE_ADMIN")

你也可以试试

@PreAuthorize("hasRole('ADMIN')")

如果@Secured注解仍然不起作用

【讨论】:

【参考方案2】:

在 Spring Security 配置文件中添加这个 bean

    @Bean
    public RoleVoter roleVoter() 
        RoleVoter roleVoter = new RoleVoter();
        roleVoter.setRolePrefix("");
        return roleVoter;
    

并像这样编写安全注释

       @Secured(value="ADMIN")

【讨论】:

我将此添加到 spring 配置文件中,例如 roleVoter.setRolePrefix("ROLE_"); .但它不起作用 默认前缀是“ROLE_”所以你必须在数据库中更改或将前缀设置为“” 嘿,我觉得我做错了,你能告诉我怎么做吗? @PrabjotSingh 请分享您的 mongoDb 身份验证提供程序以及用户类(如果有)

以上是关于Spring Security 角色不起作用的主要内容,如果未能解决你的问题,请参考以下文章

Spring Security 登录不起作用

Spring Security:hasAuthority、hasRole 和 PreAuthorize 不起作用

调用 j_spring_security_logout 不起作用

Spring Security,注释@Secured 不起作用

Spring security jsp授权标签不起作用

Spring-security-cas 插件单点注销不起作用