首页 > 解决方案 > 使用硬编码令牌访问spring boot Rest端点?

问题描述

我正在尝试公开一个允许下载文件的 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();
}

问题::如何启用硬编码令牌,以便客​​户端javascript可以将它包含在它发送的每个请求中?

目前调用 GET 服务时没有传递安全令牌。

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");

谢谢

标签: javascriptspringrestspring-bootspring-security

解决方案


根据您的用例,有多种方法可以实现基于令牌的身份验证。最常见的是OAuth2. 与spring-security-oauth2一起spring-security-oauth2-autoconfigure使您能够轻松设置OAuth2合适的应用程序。例如,它带来了一个ResourceServerAuthorizationServer你可以在这里找到官方的 Spring 文档。

另一个很好的教程可以在这里找到。它大量使用了这个spring-security-jwt包。即使您正在寻找一个小型解决方案并且硬编码的令牌就足够了,我强烈建议您为您的应用程序使用AuthorizationServer和实现。ResourceServer否则,令牌安全解决方案不会比密码安全解决方案更好。


推荐阅读