我正在尝试公开一个 REST GET 端点,该端点允许下载文件,如下所示。
@RequestMapping(value="/downloadFile", method = RequestMethod.GET)
@ResponseBody
public void downloadResource(HttpServletResponse response, @RequestParam("fileName") String name) {
downloadService.flushFile(response, name);
}
当前安全配置如下所示:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests().antMatchers("/", "/v1/**").permitAll()
.anyRequest().rememberMe();
http.httpBasic();
}
问题::如何启用硬编码 token ,以便客户端 JavaScript 可以将其包含在其发送的每个请求中?
当前调用 GET 服务时没有传递安全 token 。
window.open("http://localhost:8080/DownloadMS/v1/downloadFile?fileName=abc_test");
尝试的解决方案:我尝试在调用 GET 服务时使用用户名和密码,如下所示。这可能很糟糕,因为在页面检查时(在所有浏览器中)可以清楚地看到密码。
window.open("http://username:password@localhost:8080/DownloadMS/v1/downloadFile?fileName=abc_test");
谢谢
最佳答案
根据您的用例,有多种方法可以实现基于 token 的身份验证。最常见的是 OAuth2
。 spring-security-oauth2
与 spring-security-oauth2-autoconfigure
一起使您能够轻松设置 OAuth2
合适的应用程序。例如,它带来了 ResourceServer
和 AuthorizationServer
。可以找到Spring官方文档here .
另一个很好的教程可以找到here 。它大量使用了 spring-security-jwt 包。尽管您正在寻找一个小型解决方案并且硬编码 token 就足够了,但我强烈建议您的应用程序使用 AuthorizationServer
和 ResourceServer
的实现。否则, token 安全解决方案不会比密码安全解决方案更好。
关于javascript - 使用硬编码 token 访问 spring boot Rest 端点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51844106/