Keycloak Integration with Spring Boot

夙愿已清 提交于 2019-12-04 15:39:16

1) First add these dependencies to your build.gradle (I'm using gradle, but it's the same for pom.xml if you're a Maven guy):

// keycloak
compile 'org.keycloak:keycloak-spring-boot-adapter:2.5.1.Final'
compile 'org.keycloak:keycloak-tomcat8-adapter:2.5.1.Final'

2) Then provide your Keycloak config in the application.properties file (by this time you should have configured your realm and added a client via Keycloak web-ui):

keycloak.realm=[YOUR-REALM]
keycloak.bearer-only=true
keycloak.auth-server-url=https://[YOUR-KEYCLOAK-INSTANCE-ADDRESS]:[PORT]/auth
keycloak.ssl-required=external
keycloak.resource=[CLIEND-ID]
keycloak.credentials.secret=[YOUR-CLIENT-SECRET-ID]
keycloak.cors=true


keycloak.securityConstraints[0].securityCollections[0].name=insecure stuff
keycloak.securityConstraints[0].securityCollections[0].patterns[0]=/test-endpoint-1/*

keycloak.securityConstraints[1].securityCollections[0].name=admin stuff
keycloak.securityConstraints[1].securityCollections[0].authRoles[0]=[ROLE-2]
keycloak.securityConstraints[1].securityCollections[0].patterns[0]=/test-endpoint-2/*

Here I'm allowing any one to access everything at /test-endpoint-1/*, whereas admin users with the [ROLE-2] role can access anything under /test-endpoint-2/*.

Ah, forgot to mention, the client Access Type is bearer-only. And yes, with this setup you don't need keycloak.json. Hope this helps :)

UPDATE

The new API has changed a little bit, so given the latest versions:

kotlinVersion = '1.3.10'
springBootVersion = '2.1.1.RELEASE'
keycloakVersion = '4.6.0.Final'

dependencyManagement {
    imports {
        mavenBom "org.keycloak.bom:keycloak-adapter-bom:${keycloakVersion}"
    }
}

dependencies {
    // keycloak
    compile 'org.keycloak:keycloak-spring-boot-starter'
}

application.properties will in this case look like the following:

keycloak.realm=[YOUR-REALM]
keycloak.bearer-only=true
keycloak.auth-server-url=https://[YOUR-KEYCLOAK-INSTANCE-ADDRESS]:[PORT]/auth
keycloak.ssl-required=external
keycloak.resource=[CLIEND-ID]
keycloak.credentials.secret=[YOUR-CLIENT-SECRET-ID]
keycloak.cors=true
keycloak.enabled=true

keycloak.securityConstraints[0].securityCollections[0].name=insecure stuff
keycloak.securityConstraints[0].securityCollections[0].patterns[0]=/test-endpoint-1/*


keycloak.securityConstraints[1].securityCollections[0].name=admin stuff
keycloak.securityConstraints[1].authRoles[0]=[ROLE-2]
keycloak.securityConstraints[1].securityCollections[0].patterns[0]=/test-endpoint-2/*

Doesn't want to add keycloak.json if spring-boot adapter is added and all the configurations are made in application.properties.Export in keycloak console is used for exporting all those roles,resources,policies and all other configurations made in the console.That is just to export the setting of that particular realm.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!