Pdf下载使用java jersey和spring security在给出邮递员的请求时给出错误

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Pdf下载使用java jersey和spring security在给出邮递员的请求时给出错误相关的知识,希望对你有一定的参考价值。

我正在使用以下邮递员“发送和下载按钮”来点击jersy API,但我无法下载pdf而不是只有正常文件被下载。如果我评论@RolesAllowed(“ROLE_USER”)和dircetly从浏览器点击API然后它似乎工作正常,但我想要spring security.please建议解决这个问题

enter image description here

JAVA CODE

  @GET
    @Path("/{userId}/resume/downloadpdf")
    @Produces("application/pdf")
    @ApiOperation(value = "Gets user resume pdf",
            response = Response.class)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "UserResume information found"),
            @ApiResponse(code = 401, message = "Unauthorized request"),
            @ApiResponse(code = 404, message = "UserResume information not found"),
            @ApiResponse(code = 400, message = "Bad request"),
            @ApiResponse(code = 500, message = "Unknown internal server error")
    })
   @RolesAllowed("ROLE_USER")
    @Override
    public Response downloadResumePdf(@PathParam("userId") String userId) throws IOException, DocumentException {


        String resumehtmlData ="<h1> hi </h1>";

        StreamingOutput fileStream  = new StreamingOutput() {
            @Override
            public void write(OutputStream output) {
                try {
                    ITextRenderer renderer = new ITextRenderer();
                    renderer.setDocumentFromString(resumeHTMLData);
                    renderer.layout();
                    renderer.createPDF(output);
                    output.flush();
                } catch (Exception ex) {
                    throw new RuntimeException(ex);
                }
            }
        };

         return Response.ok(entity)
            .header("Content-Disposition", "attachment; filename="Resume" + LocalDateTime.now().toLocalDate() + ".pdf"")
     .build();


    }

配置类

    @Configuration
    public class OAuthSecurityConfig {

        private static final String USER_ACCOUNTS_RESOURCE_ID = "useraccounts";

        @Configuration
        @Import(SecurityConfig.class)
        @EnableAuthorizationServer
        @PropertySource("classpath:application.properties")
        protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

            @Value("#{environment}")
            private Environment environment;

            @Autowired
            @Qualifier("authenticationManagerBean")
            private AuthenticationManager authenticationManager;

            @Autowired
            private ResourceLoader resourceLoader;



            @Value("${JWT_SHARED_SECRET:test}")
            private String JWT_SHARED_SECRET;

            @Value("${authorization.server:test}")
            private String authorizationServer;

            @Autowired
            private UserDetailsService userDetailsService;

            @Autowired
            @Qualifier("mongoClientDetailsService")
            private ClientDetailsService mongoClientDetailsService;

            @Override
            public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

                ClientDetailsServiceBuilder clientDetailsServiceBuilder =
                        clients.withClientDetails(mongoClientDetailsService);

            }

            @Override
            public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
                endpoints
                        .tokenStore(tokenStore())
                        .tokenEnhancer(tokenEnhancer())
                        .authenticationManager(authenticationManager)
                        .userDetailsService(userDetailsService);
            }

            @Override
            public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
                oauthServer.realm( authorizationServer + "/client")
                        .allowFormAuthenticationForClients();
            }

            @Bean
            public TokenStore tokenStore(){
                return new JwtTokenStore(tokenEnhancer());
            }

            @Bean
            public JwtAccessTokenConverter tokenEnhancer(){
                JwtAccessTokenConverter tokenConverter = new JwtAccessTokenConverter();
                tokenConverter.setSigningKey(JWT_SHARED_SECRET);

                return tokenConverter;
            }

        }

        @Configuration
        @EnableResourceServer
        protected static class ResourceServerConfig extends ResourceServerConfigurerAdapter {

            @Autowired
            private TokenStore tokenStore;

            @Override
            public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
                resources.resourceId(USER_ACCOUNTS_RESOURCE_ID).stateless(true);
                resources.tokenStore(tokenStore);
            }

            @Override
            public void configure(HttpSecurity http) throws Exception {
                http
                        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
                        .and()
                        .requestMatchers().antMatchers("/oauth/admin/**", "/oauth/users/**", "/oauth/clients/**", API_REQUEST_ANT_MATCHER)
                        .and()
                        .authorizeRequests()
                        .antMatchers(API_REQUEST_ANT_MATCHER).permitAll()
                        .antMatchers(API_DOCS_REQUEST_ANT_MATCHER).permitAll()
                        .antMatchers(API_FILTER_CONTEXT + "/swagger.json").permitAll() //Allowing swagger.json for now
                        .regexMatchers(HttpMethod.DELETE, "/oauth/users/([^/].*?)/tokens/.*")
                            .access("#oauth2.clientHasRole('ROLE_CLIENT') and (hasRole('ROLE_USER') " +
                                    "or #oauth2.isClient()) and #oauth2.hasScope('write')")
                        .regexMatchers(HttpMethod.GET, "/oauth/clients/([^/].*?)/users/.*")
                            .access("#oauth2.clientHasRole('ROLE_CLIENT') and (hasRole('ROLE_USER') " +
                                    "or #oauth2.isClient()) and #oauth2.hasScope('read')")
                        .regexMatchers(HttpMethod.GET, "/oauth/clients/.*")
                            .access("#oauth2.clientHasRole('ROLE_CLIENT') " +
                                    "and #oauth2.isClient() and #oauth2.hasScope('read')");
            }
        }

    }

> SecurityConfig class

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(daoAuthenticationProvider());
    }

    @Autowired
    @Qualifier("bCryptEncoder")
    PasswordEncoder passwordEncoder;

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
                .regexMatchers("/swagger/((css|images|fonts|lang|lib)/)?(w|.|-)*")
                .regexMatchers("/app/((css|images|fonts|lang|lib)/)?(w|.|-)*")
                .antMatchers("/oauth/uncache_approvals", "/oauth/cache_approvals");
    }

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

    @Bean
    @Override
    protected UserDetailsService userDetailsService() {
        return new MongoDBUserDetailsService();
    }

    @Bean
    public ClientDetailsService mongoClientDetailsService() {
        return new MongoDBClientDetailsService();
    }

    @Bean
    public AuthenticationProvider daoAuthenticationProvider() {

        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setUserDetailsService(userDetailsService());
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder);

        return daoAuthenticationProvider;
    }

    /**
     * TODO: Using default spring pages for login/logout processing
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/login").permitAll()
                .anyRequest().hasRole("USER")
                .and()
                // TODO: put CSRF protection back into this endpoint
                .csrf()
                .requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize"))
                .disable()
                .logout()
                .and()
                .formLogin();
    }
}
答案

解决方案1:将物理文件保存到磁盘并在Response中传递文件对象。

解决方案2:将InputStream传递给Response。

我希望它有所帮助。

另一答案

您必须使用以下注释来启用方法级安全性。这是在SecurityConfig内部配置的Web安全性之上的额外级别安全性。

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(jsr250Enabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter

启用后,您可以使用@RolesAllowed注释

@RolesAllowed("ROLE_USER")
@Override
public Response downloadResumePdf(@PathParam("userId") String userId) 

以上是关于Pdf下载使用java jersey和spring security在给出邮递员的请求时给出错误的主要内容,如果未能解决你的问题,请参考以下文章

Java:使用带有 Spring Security 的 Jersey Jax-RS 进行用户身份验证

Spring Boot + Jersey

Java 上传和下载文件(附加密和解密)

Java 上传和下载文件(附加密和解密)

Java 上传和下载文件(附加密和解密)

使用 Spring Security 和 Jersey Restful Web 服务进行登录身份验证