JWT Token does not begin with Bearer String ,and in axioms when sending it began with Bearer

Total
1
Shares

I’m trying to send a post request sending the token in the header and also as a string. The problem is authenticating the header in the backend gives me the error JWT Token does not begin with Bearer String.

Below is the relevant code.

Frontend

    getUser() {
        if (token != null) {
            const config = {
                headers: { Authorization: `Bearer ${token}` }
            };

            const formData = new FormData();
            formData.set("token", token);
            
            axios.post("http://localhost:8080/user/token", formData,config)
                .then((function (response) {
                    if (response.data.email !== null) {

                        sessionStorage.setItem("role", response.data.role);
                        sessionStorage.setItem("userId", response.data.id);
                        sessionStorage.setItem("name", response.data.name);

                        location.reload(true)
                        document.getElementById('loginResult').innerHTML = response.data.token;
                    }

                }));
        }

    }

Backend

  protected void configure(HttpSecurity httpSecurity) throws Exception {
              // We don't need CSRF for this example
        httpSecurity
                .csrf().disable()
              // dont authenticate this particular request
                .authorizeRequests()
                .antMatchers("/authenticate").permitAll()
                .antMatchers("/events").permitAll()
                .antMatchers("/events/**").hasAnyAuthority("ADMIN","VENDOR")
                .antMatchers("/event-photos/**").permitAll()
                .antMatchers("/user/**").hasAnyAuthority("ADMIN","VENDOR")
                .anyRequest().authenticated()
                .and()
             // make sure we use stateless session; session won't be used to
             // store user's state.
               .exceptionHandling()
                .authenticationEntryPoint(jwtAuthenticationEntryPoint)
                .and().sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

             // Add a filter to validate the tokens with every request
        httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);

    }
    @PostMapping("user/token")
    public @ResponseBody User getUser(@RequestParam("token") String token){
        String email=jwtTokenUtil.getUsernameFromToken(token);
        User user=userRepository.getUserByUsername(email);
        return user ;
    }

Google Inspect picture for the request


Solution

If you want to add Bearer in front of the token in the body you can add it with:

formData.set("token", `Bearer ${token}`);
Leave a Reply

Your email address will not be published. Required fields are marked *