Reputation: 577
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?
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();
}
Upvotes: 0
Views: 1575
Reputation:
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'),
})
Upvotes: 1