I am trying to configure my Spring Security with Keycloak . I am using Spring Boot . I have the following dependencies in my pom.
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-spring-security-adapter</artifactId>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-tomcat8-adapter</artifactId>
</dependency>
I use the spring boot version 1.5.7.RELEASE . And the keycloak version 3.2.1.Final And the following properties in my application.properties :
keycloak.enabled=true
keycloak.realm=test
keycloak.auth-server-url=http://localhost:8080/auth
keycloak.ssl-required=external
keycloak.resource=rest
keycloak.bearer-only=true
keycloak.credentials.secret=<secret>
keycloak.principal-attribute=preferred_username
keycloak.security-constraints[0].authRoles[0]=application
keycloak.security-constraints[0].securityCollections[0].name=spring secured api
keycloak.security-constraints[0].securityCollections[0].patterns[0]=/api/**
management.security.enabled=false
I don't have any other configuration. For my endpoints I use JAX-RS. To request my token I use the Chrome Application Postman. Here is the request:
POST /auth/realms/test/protocol/openid-connect/token HTTP/1.1
Host: localhost:8080
Cache-Control: no-cache
Postman-Token: <postman token>
Content-Type: application/x-www-form-urlencoded
grant_type=password&client_id=postman&username=root&password=12345678
And my application request:
GET /api/product HTTP/1.1
Host: localhost:18888
Authorization: Bearer <keycloak token from the request above>
Cache-Control: no-cache
Postman-Token: <postman token>
But my response is:
{
"timestamp": <timestamp>,
"status": 401,
"error": "Unauthorized",
"message": "Full authentication is required to access this resource",
"path": "/api/product"
}
You are not configuring Spring Security with Keycloak here, security-constraints
are used to secure the servlet container and are unrelated to Spring Security. You don't need it when using SpringSecurity, add a Secuirty Config class extending KeycloakWebSecurityConfigurerAdapter
, check here : http://www.keycloak.org/docs/3.3/securing_apps/topics/oidc/java/spring-security-adapter.html
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.