最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

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}`);

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论