在使用配置类时,当使用@PreAuthorize或@Secured时,如何在Jersey中使用?

5

我遇到了一个类似于PreAuthorize批注在jersey中不起作用的问题。我为Spring Security创建了一个配置类,身份验证有效,但授权无效。

这是我的代码:

SpringSecurityConfig.java

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
@Order(1)
@ComponentScan({"com.foo.rest.resources.Template"})
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    private final UserService userService;
    private final TokenAuthenticationService tokenAuthenticationService;

    public SpringSecurityConfig() {
        super(true);
        this.userService = new UserService();
        tokenAuthenticationService = new TokenAuthenticationService("tooManySecrets", userService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
            http
                .exceptionHandling().and()
                .anonymous().and()
                .servletApi().and()
                .headers().cacheControl().and()
                .authorizeRequests()
                // Allow anonymous logins
                .antMatchers("/auth/**").permitAll()
                // All other request need to be authenticated
                .anyRequest().authenticated().and()

                // Custom Token based authentication based on the header previously given to the client
                .addFilterBefore(new StatelessAuthenticationFilter(tokenAuthenticationService),
                        UsernamePasswordAuthenticationFilter.class);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService()).passwordEncoder(new BCryptPasswordEncoder());
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    @Override
    public UserService userDetailsService() {
        return userService;
    }

    @Bean
    public TokenAuthenticationService tokenAuthenticationService() {
        return tokenAuthenticationService;
    }
}

以及Template.java

@Component
@Path("/template")
@Produces(MediaType.APPLICATION_JSON)
public class Template {

    @GET
    @Secured("ROLE_EDITOR")
    public User getTemplate() {
        return new Template();
    }
}

我的猜测是认证由过滤器链处理,但在到达授权标记后,它从未回来。您有什么想法可以使其正常工作吗?


访问REST服务的用户在您的用户服务中配置了“ROLE_EDITOR”角色吗? - Shiraaz.M
这只是原始代码中的一个拼写错误,已经被修复了。问题仍然存在。 - user3170736
1个回答

1
我认为您的@ComponentScan配置错误,并且无法正确选择Template资源。
根据@ComponentScan文档,该值是basePackages的别名,但您提供的是类而不是包。尝试更改它,使其看起来像以下内容并查看结果。
@ComponentScan({"com.foo.rest.resources.*"})

请确保您按照文档中的步骤正确集成Jersey Spring,不要遗漏任何步骤。


有一些事情我需要做,但是文档和你的回答让我大致上完成了90%的工作。 - user3170736
user3170736 - 你还记得你最终做了什么吗?我也遇到了同样的问题!干杯 - ChambreNoire

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接