Full authentication is required to access this resource with Spring Security and Keycloak

旧城冷巷雨未停 提交于 2019-12-12 05:10:37

问题


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"
}

回答1:


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



来源:https://stackoverflow.com/questions/46377645/full-authentication-is-required-to-access-this-resource-with-spring-security-and

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