要使用Spring Security和Keycloak访问此资源,必须进行完全身份验证 [英] Full authentication is required to access this resource with Spring Security and Keycloak

查看:697
本文介绍了要使用Spring Security和Keycloak访问此资源,必须进行完全身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Keycloak 配置 Spring Security .我正在使用 Spring Boot .我的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>

我使用的是Spring Boot版本 1.5.7.RELEASE .还有密钥斗篷版本 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,security-constraints用于保护servlet容器,并且与Spring Security无关.使用SpringSecurity时不需要它,添加扩展KeycloakWebSecurityConfigurerAdapter的Secuirty Config类,请在此处检查:

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

这篇关于要使用Spring Security和Keycloak访问此资源,必须进行完全身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆