Key cloak using spring and angular

25 Views Asked by At

Hello guys I am new to keycloak implementation to both UI and backend for backend I am using spring boot and I followed a example and was able to hit my backend endpoints successfully through post man then I implemented the keycloack security to my UI and now I am not able to hit those endpoints anymore and getting the following error -

Access to XMLHttpRequest at 'http://localhost:8085/patient from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

I tried the token I am getting from keycloak through postman and its getting the desired result then why am i getting this error.

I will share my config files -

My security config file for keycloak

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {
    
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.csrf().disable().authorizeHttpRequests().anyRequest().authenticated();
        
        httpSecurity.oauth2ResourceServer().jwt();
        
        httpSecurity.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        
        
        return httpSecurity.build();
    }

}

My cors config-

@Configuration
public class CorsConfig{
    @Bean
    public CorsWebFilter corsWebFilter() {

        final CorsConfiguration corsConfig = new CorsConfiguration();
        corsConfig.setAllowedOrigins(Collections.singletonList("*"));
        corsConfig.setMaxAge(3600L);
        corsConfig.setAllowedMethods(Arrays.asList("GET", "POST","PUT","DELETE"));
        corsConfig.addAllowedHeader("*");

        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfig);

        return new CorsWebFilter(source);
    }  
}

I am successful to login through my UI into the keycloak here how i am saving and appending the token -

import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from '@angular/router';
import { KeycloakAuthGuard, KeycloakService } from 'keycloak-angular';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard extends KeycloakAuthGuard {
  
  constructor(
    protected override readonly router: Router,
    protected readonly keycloak: KeycloakService
  ) {
    super(router, keycloak);
  }
  
  async isAccessAllowed(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Promise<boolean | UrlTree> {
    
    if (!this.authenticated) {
      await this.keycloak.login({
        redirectUri: window.location.origin + state.url,
      });
    }

    // Access token
    const token = this.keycloak.getKeycloakInstance().token;
    //console.log("Tokenn"+token)
    if (token) {
      sessionStorage.setItem("KeyToken", token);
    } else {
      console.error("Token is undefined or null");
    }


    return this.authenticated;
  }
}

And this is how i am appending the token -

@Injectable({
  providedIn: 'root'
})
export class GlobleHttpInterceptorService implements HttpInterceptor{

  constructor(
    public router: Router,
    private snackBarService:SnackBarService,
    private injector: Injector,
    private rot: ActivatedRoute,
    public loaderService: LoaderService,
    public authService: AuthService
  ) { }
  intercept(req: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    this.loaderService.isLoading.next(true);

    var token:any = sessionStorage.getItem("KeyToken");
    console.log("Globe Token:"+token)
    const route = this.injector.get(Router);
    

    if(token !== null){
      //let headers = new HttpHeaders();  
      let headers = req.headers;
      headers = headers.append("Authorization", "Bearer" + token);
      //headers.append("Access-Control-Allow-Origin", "*" );
      console.log("Globe Headers:"+token)
      req = req.clone({headers});
    }

    return next.handle(req)
    .pipe(
      finalize(
        () => {
          let lMe = this
          setTimeout(function(){
            lMe.loaderService.isLoading.next(false);
          },100)
          
        }
      ),
        catchError((error: HttpErrorResponse) => {
          switch (error.status) {
            case 401: //login  
            console.log("rot",this.rot.url);
            //this.authService.getItLogin();
            if ((route.url == "/" || route.url == '/login')) {
            this.snackBarService.error("Session has expired");
              this.router.navigate(["/"]);
            }else{
              sessionStorage.setItem("backUrl", route.url);
              this.router.navigate(["/"]);
            }
             
              break;
            case 403: //forbiden Error 
              console.log("error",error);
             // this.snackBarService.error(error.error?.message);

          }
          //console.log("console error >>>>>", error)
            let errorMsg = '';
            if (error.error instanceof ErrorEvent) {
                //console.log('This is client side error');
                errorMsg = `Error: ${error.error.message}`;
            } else {
               // this.snackBarService.error(error.error?.message);
                //console.log('This is server side error');
                errorMsg = `Error Code: ${error.status},  Message: ${error.message}`;
            }
            console.log(errorMsg);
            return throwError(errorMsg);
        })
    )

    //throw new Error('Method not implemented.');
  }

Can someone please help me solve this problem the same token works through postman again mentioning the error i am getting -

Access to XMLHttpRequest at 'http://localhost:8085/patient from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

Error getting patients: Error Code: 0, Message: Http failure response for http://localhost:8085/patient/all?page=0&size=100: 0 Unknown Error - error from my globe interceptor file

0

There are 0 best solutions below