java - 如何将自定义 HTTP header 发送到端点?

标签 java spring angular security typescript

我正在尝试发送授权 token ,但我的服务器不知何故没有收到它。

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

// token 过滤器

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

//Cors配置

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

但是当我使用 POSTMAN 执行此操作时,它确实有效。 我错过了什么?

enter image description here

编辑:使用 HttpClient

编辑:图像到文本

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

}

最佳答案

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

简单地替换

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

对于新客户端, header 是这样提供的

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

关于java - 如何将自定义 HTTP header 发送到端点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47828746/

相关文章:

javascript - 如何在 Angular 中获取结构指令的 ElementRef

java - Hibernate 5.2.9 :@Basic(fetch = FetchType. LAZY) 不起作用

java - 使用 lambda 表达式打印 boolean 值

java - 请求方法 'GET' 不支持 Spring MVC

java - 了解 Spring 事务边界

html - 如何将 [ngClass] 用于多个类条件 Angular4

java - 在 Wildfly 10 应用程序中使用 jboss-client.jar 的最佳方法是什么?

java - 如何用 Java 缩写 HTML?

java - HttpURLConnection 将响应返回为 FileNotFoundException (404) 而不是 401

html - 如何在同一个组件中定义两个管道