如何将自定义HTTP标头发送到端点?

时间:2017-12-15 08:50:38

标签: java spring angular security typescript

我试图发送一个授权令牌,而我的服务器却没有收到它。

// 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 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

编辑:回答,在后端激活CORS

@覆盖 protected void configure(HttpSecurity http)抛出异常{

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 个答案:

答案 0 :(得分:1)

这可能是您尝试新HttpClient for which you can find the documentation here

的好机会

简单地替换

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'),
  })