使用配置类时,使用@PreAuthorize或@Secured与Jersey

时间:2016-09-02 04:56:57

标签: java spring rest spring-security jersey

我遇到类似PreAuthorize annotation doesn't work with 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();
    }
}

我的猜测是,身份验证是在过滤器链中处理的,但在达到授权标记后它永远不会再出现。知道如何使这项工作?

1 个答案:

答案 0 :(得分:1)

我认为您的@ComponentScan配置错误,并未正确选择Template资源。

根据@ComponentScan documentation,该值是basePackages的别名,但您已经提供了Class而不是Package。尝试将其更改为以下内容并查看。

@ComponentScan({"com.foo.rest.resources.*"})

确保您没有错过documentation

中Jersey Spring Integration的任何步骤