gpt4 book ai didi

java - 使用Java jersey和Spring Security进行的Pdf下载在初始化 postman 的请求时给出错误

转载 作者:搜寻专家 更新时间:2023-11-01 00:54:07 24 4
gpt4 key购买 nike

我正在使用以下邮递员的“发送和下载按钮”来点击jersy API,但我无法下载pdf,而不是仅下载了普通文件。如果我评论 @RolesAllowed(“ROLE_USER”)并直接从浏览器中命中API,则它似乎可以正常工作,但我希望使用spring security。请建议解决此问题

enter image description here

JAVA代码

  @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传递给响应。

希望对您有所帮助。

关于java - 使用Java jersey和Spring Security进行的Pdf下载在初始化 postman 的请求时给出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54289056/

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