简体   繁体   English

如何从我的 react.js 前端的后端(Java Spring Boot)检索 JWT 令牌?

[英]How to retrieve JWT token from back-end (Java Spring Boot) in my react.js front-end?

i'm trying to retrieve my two JWT tokens from my back-end while logging in with my react.js in the front end but it is not responding with anything.我正在尝试从后端检索我的两个 JWT 令牌,同时在前端使用我的 react.js 登录,但它没有任何响应。 I am sure my backend works because it is responding with two tokens.我确信我的后端可以正常工作,因为它使用两个令牌进行响应。 When I try to login I've tried printing the data to the console, but it returns 'Undefined' and the request happens so fast it just disappears in the console.当我尝试登录时,我尝试将数据打印到控制台,但它返回“未定义”,并且请求发生得如此之快,它就在控制台中消失了。 Postman POST response with two tokens.带有两个令牌的邮递员 POST 响应。

Here is my front-end post request code:这是我的前端发布请求代码:

    login(username, password) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('Accept', 'application/json');
    headers.append('Origin', 'http://localhost:3000');

    return fetch("/api/public/signin", {

        method: 'POST',
        body: JSON.stringify({
            username: username,
            password: password

        }),
        headers: headers
    })

        .then(response => {
            console.log(response.data);
            if (response.data.accessToken) {
                localStorage.setItem("user", JSON.stringify(response.data.accessToken));
            }
            return response.data;
        });
}

I am not sure if this could be a CORS issue as well?我不确定这是否也可能是 CORS 问题? I was getting the error before but I'm not sure if I handled it correctly.我之前遇到过错误,但我不确定我是否正确处理了它。

This is my SecurityConfig class.这是我的 SecurityConfig 类。

@EnableGlobalMethodSecurity(
        securedEnabled = true,
        jsr250Enabled = true,
        prePostEnabled = true
)
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    private final UserDetailsService userDetailsService;
    private final UserRepository userRepo;
    private final JwtTokenFilter jwtTokenFilter;


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }
    // Used by JwtAuthenticationProvider to generate JWT tokens

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // Enable CORS and disable CSRF
        http = http.cors().and().csrf().disable();

        // Set session management to stateless
        http = http
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and();

        // Set unauthorized requests exception handler
        http = http
                .exceptionHandling()
                .authenticationEntryPoint(
                        (request, response, ex) -> {
                            response.sendError(
                                    HttpServletResponse.SC_UNAUTHORIZED,
                                    ex.getMessage()
                            );
                        }
                )
                .and();

        // Set permissions on endpoints
        http.authorizeRequests()
                // Our public endpoints
                .antMatchers("/api/public/**").permitAll()
                .anyRequest().authenticated();

        // Add JWT token filter
        http.addFilterBefore(
                jwtTokenFilter,
                UsernamePasswordAuthenticationFilter.class
        );
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new 
        UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws 
    Exception {
        return super.authenticationManagerBean();
    }
}

Here is my authController class.这是我的 authController 类。

@RestController
@RequestMapping(path = "api/public")
public class AuthController {

    @Autowired
    AuthenticationManager authenticationManager;
    @Autowired
    UserRepository userRepository;
    @Autowired
    RoleRepo roleRepository;
    @Autowired
    PasswordEncoder encoder;
    @Autowired
    JwtUtil jwtUtil;


    @PostMapping("/signin")
    public ResponseEntity<?> authenticateUser(@Valid @RequestBody User user) {
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword()));
        SecurityContextHolder.getContext().setAuthentication(authentication);
        String jwt = jwtUtil.generateJwtToken(authentication);

        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        List<String> roles = userDetails.getAuthorities().stream()
                .map(GrantedAuthority::getAuthority)
                .collect(Collectors.toList());
        return ResponseEntity.ok(new JwtResponse(jwt,
                userDetails.getId(),
                userDetails.getUsername(),
                userDetails.getEmail(),
                roles));
    }


}

My Debugger log: Debugger log我的调试器日志:调试器日志

This is the error i'm getting in the front end after running the POST request.这是我在运行 POST 请求后在前端遇到的错误。 Error in chrome browser Error in chrome console chrome浏览器中的错误chrome控制台中的错误

I am not sure if this is a problem in my front-end or back-end because I have a registration method that works which is confusing me now.我不确定这是否是我的前端或后端的问题,因为我有一个有效的注册方法现在让我感到困惑。

您必须将“ Access-Control-Expose-Headers ”添加到后端的响应标头中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM