Spring Cloud Gateway Keycloak OAuth2 OIDC Integration

Introduction

Understanding Keycloak Concepts

Setting up Keycloak

version: "3.1"
services:
keycloak:
image: quay.io/keycloak/keycloak:15.0.1
ports:
- "8080:8080"
environment:
- KEYCLOAK_USER=admin
- KEYCLOAK_PASSWORD=admin

Creating an Application with Spring Cloud Gateway

  • Gateway
  • OAuth2 Client
@RestController
public class Controller {

@GetMapping("/")
public String index(Principal principal) {
return principal.getName();
}
}
@Configuration
public class SecurityConfig {


@Bean
public SecurityWebFilterChain springSecurityFilterChain ( ServerHttpSecurity http) {

http
.authorizeExchange()
.anyExchange()
.authenticated()
.and()
.oauth2Login(); // to redirect to oauth2 login page.

return http.build();
}

}

Setting Application Property values

  • Provider’s properties — The provider of the OAuth2 mechanism i.e the realm.
  • Client properties — These are the properties of the Keycloak client to communicate with the realm.
spring:
security:
oauth2:
client:
provider:
my-keycloak-provider:
issuer-uri: http://localhost:8080/auth/realms/My-Realm
spring:
security:
oauth2:
client:
provider:
my-keycloak-provider:
issuer-uri: http://localhost:8080/auth/realms/My-Realm

registration:
keycloak-spring-gateway-client:
provider: my-keycloak-provider
client-id: spring-gateway-client
client-secret: fc36fd82-7042-4287-aef0-e9f8603abd02
authorization-grant-type: authorization_code
redirect-uri: "{baseUrl}/login/oauth2/code/keycloak"
server:
port: 9090

Starting the application

Understanding the OAuth2 Open ID Connect Flow

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Amrut Prabhu

Amrut Prabhu

Software Craftsman, Tech Enthusiast. I run https://refactorfirst.com to post all my articles