0

I'm trying to send an authorization token and my server somehow is not recieving it.

//service.ts

...
import { HttpClient, HttpHeaders } from '@angular/common/http';
...

 getAllUsers():Observable<User[]>{
 return this.http.get<User[]>(this.backendUrl.getUrl.concat('rest/user/getallusers'),
{headers: new HttpHeaders()
  .set('Authorization', 'Token asdasd')
  .set("Content-Type", "application/json")
});

}

//endpoint

@RequestMapping(value = "/getallusers", method = RequestMethod.GET, consumes = MediaType.APPLICATION_JSON_VALUE)
public List<User> getallusers() {
    return this.userService.getAllUsers();
}

//TokenFilter

@Override
    public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException, ServletException {

        String header = httpServletRequest.getHeader("Authorization");
        //Header is null here when I do a request from the browser
        //but with postman it does has a value.
        if (header == null || !header.startsWith("Token ")) {
            throw new RuntimeException("JWT Token is missing");
        }

        String authenticationToken = header.substring(6);

        JwtAuthenticationToken token = new JwtAuthenticationToken(authenticationToken);
        return getAuthenticationManager().authenticate(token);
    }

//CorsConfiguration

@Override
public void addCorsMappings(CorsRegistry registry) {
   registry.addMapping("/**").allowedOrigins("*")
   .allowedMethods("GET","POST","DELETE");
}

But when I do it using POSTMAN it does work. What am I missing?

enter image description here

EDIT: Using HttpClient

EDIT: Img to text

Request Headers
Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:es-ES,es;q=0.9
Access-Control-Request-Headers:authorization,content-type
Access-Control-Request-Method:GET
Connection:keep-alive
Host:localhost:2030
Origin:http://localhost:4200
User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36

EDIT: Answer, activate CORS in the backend

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

http.csrf().disable()
    .cors()  //<-- This one was missing
    .and()
    .addFilterBefore(authenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class)
    .authorizeRequests().antMatchers("login").permitAll()
    .and()
    .authorizeRequests().antMatchers("rest/**").authenticated()
    .and()
    .exceptionHandling().authenticationEntryPoint(entryPoint)
    .and()
    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
    .and()
    .headers()
    .cacheControl();

}

Fran
  • 521
  • 4
  • 20

1 Answers1

1

This might be a good occasion for you to try the new HttpClient for which you can find the documentation here

Simply replace

import { Http } from '@angular/http'; // old version
import { HttpClient } from '@angular/common/http'; // new version

With the new client, headers are provided like this

http
  .post('/api/items/add', body, {
    headers: new HttpHeaders().set('Authorization', 'my-auth-token'),
  })
  • Thanks for your reply, but I have the same results as you can see at the image from chrome dev tools :/ – Fran Dec 15 '17 at 09:07
  • Well I can't actually (proxy at work, imgur blocked). But I have a good idea of the problem, don't worry ;) just a question for my picture blindness : is your server not finding the token, or is your token not sent by Angular ? (check the `Network` tab of your browser dev tools and see if the request holds the header) –  Dec 15 '17 at 09:10
  • Is not sent by Angular, I wrote the text showed by image. – Fran Dec 15 '17 at 09:13
  • Could you try sending an Authorization header containing the chain `Bearer abcd` Instead of `Token abcd` ? –  Dec 15 '17 at 09:20
  • I did but i've the same results :( – Fran Dec 15 '17 at 09:24
  • I'll try using interceptors following this guide https://medium.com/@milosbejda/adding-authorization-header-to-http-request-in-angular-4-and-5-777b2ce05424 – Fran Dec 15 '17 at 09:25
  • Well that's your only option, because I can't locate the issue ... Maybe provide a real token to test ? –  Dec 15 '17 at 09:30
  • Didn't worked , dont know what to try, also did this https://stackoverflow.com/questions/45286764/angular-4-3-httpclient-doesnt-send-header but didnt worked. Thank you for you time man :) – Fran Dec 15 '17 at 09:40
  • 1
    Last thing, did you authorize the Authorization header in your back-end ? Maybe you forgot, and the back-end is not allowing it to be sent ! And no problem, that's what SOF is for :) –  Dec 15 '17 at 09:43
  • You were right. I had to call ´.cors()´ in the back-end in the WebSecurityConfig file. – Fran Dec 15 '17 at 11:06
  • Haha Thank you mate :D – Fran Dec 15 '17 at 11:57