[英]Not setting headers for request
我有一個Angular 7應用程序和一個帶有JTW的Java Spring API。 應用程序必須在API中的每個請求中發送令牌,但這不會發生,因此所有請求都會返回401錯誤。
應用模塊
...
@NgModule
({
declarations: [
AppComponent,
PatientComponent,
HeaderComponent,
FooterComponent,
AlertComponent,
NotFoundComponent,
UserRegisterComponent,
LoginComponent,
AuthGuardComponent
],
imports: [
BrowserModule,
FormsModule,
NgSelectModule,
ReactiveFormsModule,
HttpClientModule,
AppRoutingModule,
NgbModule,
],
providers: [
{
provide : HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi : true,
},
],
bootstrap: [AppComponent]
})
export class AppModule {
}
AuthInterceptor
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { GeneralService } from '../_service/general.service';
import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private generalService: GeneralService) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
req = req.clone({
setHeaders: {
Authorization: 'Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyIiwic2NvcGVzIjpbeyJhdXRob3JpdHkiOiJTeXN0ZW0gVXNlciJ9XSwiaXNzIjoiaHR0cHM6Ly9hcGkubmVvZ3JpZC5jb20vIiwiaWF0IjoxNTU4OTgwOTAxLCJleHAiOjE1NTg5OTg5MDF9.vZByXryTI-1wGLYY1bU8DurOF15qlxA7QkdMW5UeM8c')
}
});
console.log(req);
return next.handle(req);
}
}
請求
listAll() {
return this.http.get('http://localhost:8080/api/listAll');
}
async get() {
let error = null;
let response = await this.listAll()
.toPromise()
.catch(error => error = error);
console.log(response);
}
console.log(req)的結果;
看起來沒關系,授權和令牌就在那里
請求
不要在這里傳遞令牌:c
誤差修改
選項401'http :// localhost:4200 '對XMLHttpRequest的訪問已被CORS策略阻止:對預檢請求的響應未通過訪問控制檢查:它沒有HTTP ok狀態。
我用insonmia做了同樣的請求(通過授權和令牌)e一切都好,問題在於角度請求。
感謝您的評論,我能夠制定解決方案,我修改了我的WebSecurityConfig.java api文件,問題不在於角度請求。 謝謝大家。
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private ParametersProperties parameters;
@Resource(name = "userService")
private UserDetailsService userDetailsService;
@Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Autowired
public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService)
.passwordEncoder(encoder());
}
@Bean
public JwtAuthenticationFilter authenticationTokenFilterBean() {
return new JwtAuthenticationFilter();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable().
authorizeRequests()
.antMatchers(
"/swagger-resources/**",
"/swagger-ui.html",
"/webjars/**",
"/h2/**",
"/auth/signin",
).permitAll()
/* the saver is the line below*/
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.anyRequest().authenticated()
.and()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http
.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class)
.headers().frameOptions().sameOrigin();
}
@Bean
public BCryptPasswordEncoder encoder(){
return new BCryptPasswordEncoder();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.