Friday, June 23, 2023

Angular - Keycloak - Spring Cloud Gateway Setup

Note:

This setup won't work if you try to run it thru the ng-serve development server. You have to deploy your app on an Nginx server or embedded in your war spring boot project.

Angular

Use keycloak-angular  package to have Keycloak manage the login process.

In your Angular application app.module.ts add:

function initializeKeycloak(keycloak: KeycloakService) {
return () =>
keycloak.init({
config: {
/**
* For Development use.
* Angular proxy will collide with the Spring Cloud Gateway.
*/
// url: 'http://localhost:8080/auth',
url: window.location.origin + '/auth',
realm: 'myRealm',
clientId: 'myClient',
},
initOptions: {
onLoad: 'login-required',
// onLoad: 'check-sso',
// checkLoginIframe: false,
// silentCheckSsoRedirectUri:
// window.location.origin + '/zaa/ensemble/assets/silent-check-sso.html',
},
loadUserProfileAtStartUp: true,
bearerExcludedUrls: ['']
});
}
providers: [
{
provide: APP_INITIALIZER,
useFactory: initializeKeycloak,
multi: true,
deps: [KeycloakService],
}

.

Spring-cloud-gateway
Add a route to support Keycloak (assuming it's running as an OCI container it will look like this:

spring:
   codec:
     max-in-memory-size: 500KB
   
   cloud:
      gateway:
         routes:
            - id: keycloak
              uri: ${KEYCLOAK_ROUTE:http://keycloak:8080/auth/}
              predicates:
              - Path=/auth/**

Note the code variable above. I had to add this filter to manage the size of a javascript file imported by the HTML frame generated by Keycloak that was over the Codec default size.

package com.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.config.WebFluxConfigurer;

@Configuration
public class WebFluxConfiguration implements WebFluxConfigurer {
    @Override
    public void configureHttpMessageCodecs(ServerCodecConfigurer configurer) {
        configurer.defaultCodecs().maxInMemorySize(500 * 1024);
    }
}


Keycloak

Under myRealm/Security Defenses, update the frame-ancestors to avoid CORS issue:

Content-Security-Policy  frame-src 'self'; frame-ancestors https://mydomain.com:8085; object-src 'none';

where mydomain.com is the host where you deploy your Gateway.

No comments:

Post a Comment