2017-12-15 1 views
0

인증 토큰을 보내려고하는데 내 서버가 어떻게 든 그것을받지 못합니다.엔드 포인트에 사용자 정의 HTTP 헤더를 보내는 방법은 무엇입니까?

//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") 
}); 

}

// 엔드 포인트

@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"); 
} 

하지만 POSTMAN을 사용하면 작동합니다. 내가 무엇이 누락 되었습니까?

enter image description here

편집 : 사용 HttpClient를

편집 : IMG가

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 

편집 텍스트 : 답변, 백엔드

@Override 보호 무효 구성 (HttpSecurity에 CORS를 활성화 http) 예외를 throw합니다 {

HttpClient for which you can find the documentation here

을 시도하는

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(); 

}

답변

1

이 단순히 새로운 클라이언트와

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

를 대체 할 좋은 기회가 될 수도, 헤더는이

처럼 제공
http 
    .post('/api/items/add', body, { 
    headers: new HttpHeaders().set('Authorization', 'my-auth-token'), 
    }) 
+0

답장을 보내 주셔서 감사합니다.하지만 동일한 결과가 있습니다. 당신이 크롬 dev 도구에서 이미지에서 볼 수 있듯이 :/ – Frank

+0

글쎄, 사실 (프록시, 직장에서 프록시, imgur 차단). 그러나 나는이 문제에 대해 좋은 생각을 갖고 있습니다. 걱정하지 마십시오.) 내 사진 실명에 대한 질문 : 서버가 토큰을 찾지 못 했나요? 아니면 토큰이 Angular로 보내지지 않았습니까? (브라우저의 dev 도구의'Network' 탭을 확인하고 요청에 헤더가 있는지 확인하십시오.) – trichetriche

+0

Angular에서 전송하지 않았으므로 이미지로 표시된 텍스트를 썼습니다. – Frank

관련 문제