認証トークンを送信しようとしていますが、サーバーがそれを受信していません。
//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を使用して実行すると、機能します。何が足りないのですか?
編集: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
編集:回答、バックエンドでCORSをアクティブ化
@Override 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
単に交換する
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'),
})
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加