需要使用Spring Security和Keycloak访问此资源的完全身份验证
问题描述:
我正在尝试配置我的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配置Spring安全在这里,security-constraints
用于保护servlet容器并与Spring Security无关。使用SpringSecurity时不需要它,添加一个Secuirty Config类,扩展为KeycloakWebSecurityConfigurerAdapter
,请点击此处:http://www.keycloak.org/docs/3.3/securing_apps/topics/oidc/java/spring-security-adapter.html
谢谢您的回答。我有问题,我宁愿使用“keycloak.json”而不是使用Spring属性文件。在加载应用程序时,加载keycloak.json。但是,如果我尝试休息一下,我会得到一个异常,我必须在config中设置'realm'。你可以帮我吗? –
在这种情况下,不要使用Spring Boot适配器,只使用Spring Security适配器,并确保在您的'keycloak.json'中指定了th领域。 –