Cha*_*n93 2 java authentication wildfly keycloak
我正在开发一个 WildFly-Backend(在 Java 中),它接受通过“授权”HTTP 标头使用用户的 Keycloak 持有者访问令牌签名的 HTTP 请求(来自自定义前端)。
后端连接本身已经通过用于 WildFly 的 Keycloak 适配器进行了保护,但在内部,我想检查用户是谁(用户组、名称等)并返回非常有用的响应。
我认为可以只从前端发送这些数据,但是一旦他们拥有访问令牌,人们就可以轻松伪造请求。有没有办法在只有访问令牌的情况下检索用户数据之类的东西?
从那以后我想出了如何解决这个问题!
首先,在类顶部附近添加以下内容:
@Context
javax.ws.rs.core.SecurityContext securityContext;
Run Code Online (Sandbox Code Playgroud)
这将注入服务器安全的上下文。要使其与 Keycloak 一起使用,WildFly 需要安装 Wildfly 适配器,并且必须将 web.xml 配置为使用 Keycloak。
在我们继续之前,我们需要 Keycloak-Core 库,例如每个 Maven:
<!-- https://mvnrepository.com/artifact/org.keycloak/keycloak-core -->
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-core</artifactId>
<version>4.4.0.Final</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
4.4.0.Final是撰写此答案时的最新版本;建议使用最新版本或与Keycloak服务器匹配的版本。
接下来,在要检索用户信息的位置,检索 UserPrincipal:
if (securityContext != null && securityContext.getUserPrincipal() instanceof KeycloakPrincipal) {
KeycloakPrincipal principal = ((KeycloakPrincipal) securityContext.getUserPrincipal());
Run Code Online (Sandbox Code Playgroud)
附加检查是故障保存,因此可以单独处理非 Keycloak 配置。
从铸造的 KeycloakPrinciple 中,检索 KeycloakSecurityContext 和用户的令牌:
AccessToken token = principal.getKeycloakSecurityContext().getToken();
Run Code Online (Sandbox Code Playgroud)
在某些情况下(取决于您的 Keycloak 和/或 WildFly 的版本),getToken() 可能会返回 null。在这些情况下,请使用 getIdToken():
IDToken token = principal.getKeycloakSecurityContext().getIdToken();
Run Code Online (Sandbox Code Playgroud)
AccessToken 扩展了 IDToken,因此在这两种情况下您都拥有完整的功能(对于此上下文)。
从令牌中,可以提取所有用户数据。例如,我们获取用户的用户名。在 Keycloak 中,此属性称为“首选用户名”。
String user = token.getPreferredUsername();
Run Code Online (Sandbox Code Playgroud)
你完成了!您的完整代码现在可能如下所示:
if (securityContext != null && securityContext.getUserPrincipal() instanceof KeycloakPrincipal) {
KeycloakPrincipal principal = ((KeycloakPrincipal) securityContext.getUserPrincipal());
AccessToken token = principal.getKeycloakSecurityContext().getToken();
// IDToken token = principal.getKeycloakSecurityContext().getIdToken();
System.out.println("User logged in: " + token.getPreferredUsername());
} else {
System.out.println("SecurityContext could not provide a Keycloak context.");
}
Run Code Online (Sandbox Code Playgroud)