I would like to call backend (java/springboot) to create a login feature on my app. I invoke a jwtoken from frontend (angular) to backend. There is no problem to generate in backend and the frontend recieve the good jwtoken.
https://www.example.com/api/v1/authenticate
response :
jwtToken: "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJzdG9ja21hbmFnZXIiLCJleHAiOjE2NDMzODc1NjQsImlhdCI6MTY0MzM2OTU2NH0.mYl10_v5Dm3S6K0lM5uBOLs1x2rYwC76ZkJ9w6-QOTw1tE7xjiKxMIOiiU6QgwsKxqtDmz31aCEA4ePY2IzkUQ"
So far, so good
Request URL: https://www.example.com/api/v1/authenticate
Request Method: POST
Status Code: 200 (from service worker)
Referrer Policy: strict-origin-when-cross-origin
But I would like to GET a user with authentification in the header of the call
https://www.example.com/api/v1/users/find
Authorization: Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJzdG9ja21hbmFnZXIiLCJleHAiOjE2NDMzODc1NjQsImlhdCI6MTY0MzM2OTU2NH0.mYl10_v5Dm3S6K0lM5uBOLs1x2rYwC76ZkJ9w6-QOTw1tE7xjiKxMIOiiU6QgwsKxqtDmz31aCEA4ePY2IzkUQ
Payload : {username: "example", password: "password"}
Unfortunately there a CORS Error :
Access to fetch at 'https://www.example.com/api/v1/users/find' from origin 'https://www.example.com/api/v1/users/find' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
I need some Help, please :sweat_smile:
CodePudding user response:
I am assuming you are running your app in the development mode using command "ng serve", if so then to avoid this CORS issue you can call your backend(java/springboot) REST api through proxy support. Please go through the below section in angular documentation to know more about proxying.
https://angular.io/guide/build#proxying-to-a-backend-server
CodePudding user response:
I solved the issue by update my backend ;-) I add httpSecurity.cors() in the configure() method;
@EnableWebSecurity
@RequiredArgsConstructor
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(final HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf()
.disable()
.authorizeRequests()
.mvcMatchers("/api/v1/authenticate")
.permitAll()
.anyRequest()
.authenticated()
.and()
.exceptionHandling()
.authenticationEntryPoint(this.jwtAuthenticationEntryPoint)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
httpSecurity.cors();
httpSecurity.addFilterBefore(this.jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}
}
The backend can now getHeaders, so Authorization.
Thank you very much for your Help !!!
