我正在嘗試配置我的Spring Security和Keycloak。我正在使用Spring Boot。我在我的pom中有以下依賴項。需要使用Spring Security和Keycloak訪問此資源的完全身份驗證
<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>
我用的是彈簧引導版本1.5.7.RELEASE。而keycloak版本3.2.1.Final 及以下屬性在我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
我沒有任何其他配置。對於我的端點,我使用JAX-RS。 要請求我的令牌,我使用Chrome應用郵差。這裏是要求:
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
我的申請請求:
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>
但我的反應是:
{
"timestamp": <timestamp>,
"status": 401,
"error": "Unauthorized",
"message": "Full authentication is required to access this resource",
"path": "/api/product"
}
謝謝您的回答。我有問題,我寧願使用「keycloak.json」而不是使用Spring屬性文件。在加載應用程序時,加載keycloak.json。但是,如果我嘗試休息一下,我會得到一個異常,我必須在config中設置'realm'。你可以幫我嗎? –
在這種情況下,不要使用Spring Boot適配器,只使用Spring Security適配器,並確保在您的'keycloak.json'中指定了th領域。 –