【问题标题】:Problem with integrating Spring Boot backend + oauth with frontend app将 Spring Boot 后端 + oauth 与前端应用程序集成的问题
【发布时间】:2020-07-19 01:00:02
【问题描述】:

我有后端 Spring Boot 应用程序,它使用来自 Spotify api 的数据,它需要用户登录才能为我的应用程序提供身份验证令牌。它工作正常,但我不知道如何将它与前端应用程序集成。从服务器应用程序(localhost:8080)外部发送请求时,我总是得到 403 代码。

问题可能是我应该在前端请求 Spotify 令牌,然后以某种方式将其传递给后端,但老实说,我什至不知道我应该用谷歌搜索什么来实现这一点。

以下是一些关键类:

@Configuration
@EnableOAuth2Sso
public class SpotifyConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception{
        http.authorizeRequests().antMatchers("/login").authenticated();
    }

}
And inside @RestController:
@GetMapping("/user")
    public Principal user(Principal principal){
        return principal;
    }

@GetMapping("/")
    public Principal home(Principal principal){
        return principal;
    }

@GetMapping("/login")
    public Principal login(Principal principal){
        return principal;
    }

这是我第一次接触与 Spring Security 相关的东西,我不知道这里发生了什么 xd

【问题讨论】:

    标签: java spring spring-boot oauth


    【解决方案1】:

    首先,Spring Security 禁止的所有请求都会导致这行代码。

    http.authorizeRequests().antMatchers("/login").authenticated();
    

    您必须授予对某些请求或任何请求的访问权限,但在您的情况下,您已被禁止每个请求。这就是为什么当您尝试通过 rest 访问 spring boot 应用程序时收到 403 状态(禁止)的原因

    因此,您有多种选择来解决此问题。我给你两次。

    1. 如果您希望从每个请求中获得访问权限,请将 Spring Security 中的代码行从上面更改为:
    http.authorizeRequests().antMatchers("/**").permitAll();
    
    • “/**”表示所有文件夹和子文件夹
    • permitAll() 表示 Spring Security 授予所有与 antMatchers 函数匹配的请求的访问权限。
    1. 如果您想授予对某些请求的访问权限,通过登录名和其他安全措施来验证用户身份,您可以这样开始:
    http.authorizeRequests()
    .antMatchers("/somePath").authenticated();
    .antMatchers("/somePath2").authenticated();
    .antMatchers("/somePath3").permitAll();
    

    但是 Spring Security 比这更深入,所以如果你想更深入地了解可用的多重配置,你需要阅读官方文档。 https://docs.spring.io/spring-security/site/docs/current/reference/html5/#preface,还有很多简单的配置例子让大家玩的开心。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-01
      • 2020-07-20
      • 2021-05-04
      • 1970-01-01
      • 2020-09-30
      • 2021-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多