简体   繁体   中英

Spring Boot Keycloak - How to verify Bearer token?

Keycloak version 2.4.0_FINAL.

In my Spring Boot REST API, I want to verify bearer tokens in Keycloak.

I followed the following steps:

I added the maven dependencies and the following to the application.properties.

keycloak.realm = realm
keycloak.auth-server-url = http://localhost:8080/auth
keycloak.ssl-required = external
keycloak.resource = app
keycloak.bearer-only = true
keycloak.credentials.secret = ...

keycloak.securityConstraints[0].securityCollections[0].patterns[0] = /r/secure/*

What is the next step? According to me, this was the last step but it does not seem to do something.

Update application.properties:

server.port = 8081
org.keycloak keycloak-tomcat8-adapter 2.4.0.Final
keycloak.realm = myapp
keycloak.auth-server-url = http://localhost:8080/auth
keycloak.ssl-required = external
keycloak.resource = mybackend
keycloak.bearer-only = true
keycloak.credentials.secret = ...
keycloak.use-resource-role-mappings = false

keycloak.securityConstraints[0].securityCollections[0].name = secure
keycloak.securityConstraints[0].securityCollections[0].patterns[0] = /r/secure/*

Your security constraint must at least contain a role , ie :

keycloak.security-constraints[0].securityCollections[0].authRoles[0]=admin

Be sure to add this tole in keycloak and assign it to your user.

You can solve your problem using spring security, if that's an option for you. I find it better. The instructions can be found here .

For example:

@Override
protected void configure(HttpSecurity http) throws Exception
{
    super.configure(http);
    http
            .authorizeRequests()
            .antMatchers("/customers*").hasRole("USER")
            .antMatchers("/admin*").hasRole("ADMIN")
            .anyRequest().permitAll();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM