【问题标题】:Authenticate and access spring security protected API from a react js application从 React js 应用程序验证和访问受 Spring Security 保护的 API
【发布时间】:2021-11-09 13:21:13
【问题描述】:

我的目标是在身份验证后从 React js 应用程序访问受 Spring Security 保护的 API。

  • Spring Boot 应用程序托管在 http://myserver:8080
  • React JS 应用程序托管在 http://myserver:3000

我能够使用 curl 进行身份验证和访问 API,如下所示:

  1. 使用凭据访问登录 URL。从响应头中提取 jsessionid 令牌。
  2. 使用 jsessionid 令牌访问结束 url。
$ curl -i -X POST login_url --data 'username=myusername&password=mypassword'
$ curl end_url -H 'Cookie: JSESSIONID=session_token'

我正在尝试通过 React JS 应用程序复制相同的内容。

  • 即使响应头中存在 JSESSIONID Cookie(通过 curl 和浏览器开发工具验证),但 axios 响应头无法捕获它。

  • 我了解 JavaScript 代码中的“Set-Cookie”标头在默认情况下不起作用。正如这个问题所讨论的React Axios, Can't read the Set-Cookie header on axios response

  • 请帮助修改代码以实现相同的目的。或建议实现目标的替代方法。 谢谢。

客户端代码如下:

const onSubmitAuthenticateButton = (e) => {
 e.preventDefault();
 const loginUrl = 'http://myserver:8080/login';
 axios.defaults.withCredentials = true;
 axios.post(loginUrl, { username, password})
      .then(res => console.log(res.headers))
      .catch(err => console.log(err.message));
}

在 Spring Secuirty 配置中,csrf 被禁用,并且 cors 允许“http://myserver:3000”的来源。

WebSecurityConfig 类

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{

    private CustomAuthenticationProvider customAuthProvider;

    public WebSecurityConfig(CustomAuthenticationProvider customAuthProvider) {
        super();
        this.customAuthProvider = customAuthProvider;
    }
        
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .cors()
            .and()
            .csrf().disable()
            .authorizeRequests()
            .anyRequest().fullyAuthenticated()
            .and()
            .formLogin();           
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.authenticationProvider(customAuthProvider);
        }
}

WebMvcConfig 类

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    private final long MAX_AGE_SECS = 3600;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://myserver:3000")
                .allowedMethods("GET", "POST")
                .exposedHeaders("Set-Cookie")
                .maxAge(MAX_AGE_SECS)
                .allowCredentials(true);       
      }
}

【问题讨论】:

    标签: reactjs cookies spring-security axios


    【解决方案1】:

    我已经通过其他方式实现了目标。 我现在使用的是无状态身份验证,而不是基于会话的身份验证。成功验证后,将返回一个 jwt 令牌作为响应。随后的 API 调用,jwt 令牌作为有效负载附加。应用程序在处理 API 调用请求之前检查令牌的有效性。

    【讨论】:

      猜你喜欢
      • 2015-03-21
      • 2017-04-14
      • 2020-04-25
      • 1970-01-01
      • 2018-07-17
      • 2020-04-06
      • 2020-04-03
      • 1970-01-01
      • 2019-09-08
      相关资源
      最近更新 更多