最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

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

matteradmin8PV0评论

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

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

Share Improve this question edited May 23, 2021 at 9:10 Kitswas 1,2052 gold badges16 silver badges34 bronze badges asked May 23, 2021 at 8:53 mohammedmohammed 151 gold badge1 silver badge9 bronze badges 3
  • You're sending the token in the header and the body. In the backend you're reading the token from the body. – Thomas Sablik Commented May 23, 2021 at 9:00
  • @ThomasSablik yes I want also to send it in the body to get the user from the token , but to be able to get access to the getUser() function in the backend it must be authenticated and hire e the header – mohammed Commented May 23, 2021 at 9:04
  • But getUser(@RequestParam("token") String token) doesn't read the token from the header. If you want to add Bearer in front of the token add it: formData.set("token", `Bearer ${token}`); – Thomas Sablik Commented May 23, 2021 at 9:24
Add a ment  | 

1 Answer 1

Reset to default 1

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

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

Articles related to this article

Post a comment

comment list (0)

  1. No comments so far