Instantly share code, notes, and snippets.

Embed
What would you like to do?
Securing a Spring Boot Application with Keycloak
package com.thomasvitale.keycloak.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
@Controller
public class PublicLibraryController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public String getHome() {
return "index";
}
@RequestMapping(value = "/books", method = RequestMethod.GET)
public String getBooks(Principal principal, Model model) {
model.addAttribute("member", principal.getName());
return "books";
}
@RequestMapping(value = "/manager", method = RequestMethod.GET)
public String getManager(Principal principal, Model model) {
model.addAttribute("librarian", principal.getName());
return "manager";
}
@RequestMapping(value = "/logout", method = RequestMethod.GET)
public String logout(HttpServletRequest request) throws ServletException {
request.logout();
return "redirect:/";
}
}
keycloak.realm=public-library
keycloak.resource=app-client
keycloak.auth-server-url=http://localhost:8180/auth
keycloak.ssl-required=external
keycloak.public-client=true
keycloak.principal-attribute=preferred_username
keycloak.securityConstraints[0].authRoles[0]=Member
keycloak.securityConstraints[0].authRoles[1]=Librarian
keycloak.securityConstraints[0].securityCollections[0].name=member resource
keycloak.securityConstraints[0].securityCollections[0].patterns[0]=/books
keycloak.securityConstraints[1].authRoles[0]=Librarian
keycloak.securityConstraints[1].securityCollections[0].name=librarian resource
keycloak.securityConstraints[1].securityCollections[0].patterns[0]=/manager
buildscript {
ext {
springBootVersion = '2.0.8.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
group = 'com.thomasvitale'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
ext {
set('keycloakVersion', '4.8.3.Final')
}
dependencies {
// Spring
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-devtools'
// Keycloak
implementation 'org.keycloak:keycloak-spring-boot-starter'
// Test
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
dependencyManagement {
imports {
mavenBom "org.keycloak.bom:keycloak-adapter-bom:${keycloakVersion}"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment