【问题标题】:cors for jwt springboot security and react用于 jwt springboot 安全和反应的 cors
【发布时间】:2022-11-19 01:43:22
【问题描述】:

我可以使用基本身份验证在邮递员中生成令牌进行登录,但是在反应中使用交叉源时它不能,我只是想知道为什么。 错误:

Failed to load resource: the server responded with a status of 401 ()

我的反应代码:

const getPassword = async (e) => {
   
    const res = await Axios.post("http://localhost:5000/token",{},{
        auth:{
            Username:nameRef.current.value,
            Password:passwordRef.current.value
        }
    });
    console.log('res.data'+res.data)
    console.log(res)

我的春季启动代码(安全配置):

@Bean
    public SecurityFilterChain securityfilterchain(HttpSecurity http) throws Exception {
        return http
                //if used csrf.ignoringAntMatchers -->prevent the attack from cross-origin
                //.csrf(csrf -> csrf.disable())
                .cors().and()
                .csrf(csrf -> csrf.ignoringAntMatchers("/shownews/**","/getnews/**","/token","/signup"))

                .authorizeRequests(auth-> auth
                        .antMatchers("/shownews/**").permitAll()
                        .antMatchers("/getnews/**").permitAll()
                        .anyRequest().authenticated())

                .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt)
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                //Link to the jpauserservice to check whether the authentication valid (similar to authentication manager)
                .userDetailsService(myUserDetailsService)
                .headers(headers -> headers.frameOptions().sameOrigin())
                .httpBasic(Customizer.withDefaults())
                //.formLogin().and()
                .build();
    }

控制器:

 @PostMapping("/token")
    public String token(Authentication authentication){
        LOG.debug("Token requested for user: '{}",authentication.getName());
        String token=tokenService.generateToken(authentication);
        LOG.debug("Token granted {}",token);
        return token;
    }

【问题讨论】:

  • 为什么你的 cors 白名单了一些端点

标签: reactjs spring-boot cors


【解决方案1】:

这是我去年修车的方法希望对你有帮助 您可能想找到一种匹配语法的方法

http.cors().and().csrf()
                .disable()
                .authorizeRequests(). your ant matches here

【讨论】:

    猜你喜欢
    • 2018-01-30
    • 2018-11-20
    • 2020-11-30
    • 1970-01-01
    • 2018-06-07
    • 2019-01-10
    • 2021-11-23
    • 2016-09-29
    • 2022-10-05
    相关资源
    最近更新 更多