Instantly share code, notes, and snippets.

Embed
What would you like to do?
Securing a Spring Boot Application with Keycloak
@Controller
public class AppController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public String getHome() {
return "index";
}
@RequestMapping(value = "/user", method = RequestMethod.GET)
public String getUser(Principal principal, Model model) {
model.addAttribute("user", principal.getName());
return "user";
}
@RequestMapping(value = "/admin", method = RequestMethod.GET)
public String getAdmin(Principal principal, Model model) {
model.addAttribute("admin", principal.getName());
return "admin";
}
@RequestMapping(value = "/logout", method = RequestMethod.GET)
public String handleLogout(HttpServletRequest request) throws ServletException {
request.logout();
return "redirect:/";
}
}
keycloak.realm=Demo
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] = User
keycloak.securityConstraints[0].authRoles[1] = Admin
keycloak.securityConstraints[0].securityCollections[0].name = user resource
keycloak.securityConstraints[0].securityCollections[0].patterns[0] = /user
keycloak.securityConstraints[1].authRoles[0] = Admin
keycloak.securityConstraints[1].securityCollections[0].name = admin resource
keycloak.securityConstraints[1].securityCollections[0].patterns[0] = /admin
compile "org.keycloak:keycloak-spring-boot-starter:3.3.0.Final"
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-spring-boot-starter</artifactId>
<version>3.3.0.Final</version>
</dependency>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment