Commit b8c0564e authored by redmitry@list.ru's avatar redmitry@list.ru

put "roles" claim into KC Roles

parent cd8c8bd4
/**
* *****************************************************************************
* Copyright (C) 2020 ELIXIR ES, Spanish National Bioinformatics Institute (INB)
* and Barcelona Supercomputing Center (BSC)
*
* Modifications to the initial code base are copyright of their respective
* authors, or their employers as appropriate.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*****************************************************************************
*/
package es.bsc.inb.elixir.openebench.rest;
import java.io.IOException;
import java.security.Principal;
import java.util.List;
import java.util.Map;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.ext.Provider;
import org.keycloak.KeycloakPrincipal;
import org.keycloak.KeycloakSecurityContext;
import org.keycloak.representations.AccessToken;
/**
* Filter maps token's "roles" claim into the Keycloak Realm Roles, so
* isUserInRole() can work properly.
*
* @author Dmitry Repchevsky
*/
@Provider
public class KeycloakRolesFilter implements ContainerRequestFilter {
@Override
public void filter(ContainerRequestContext ctx) throws IOException {
final SecurityContext sc = ctx.getSecurityContext();
if (sc != null) {
final Principal principal = sc.getUserPrincipal();
if (principal instanceof KeycloakPrincipal) {
final KeycloakPrincipal kp = (KeycloakPrincipal)principal;
final KeycloakSecurityContext ksc = kp.getKeycloakSecurityContext();
final AccessToken token = ksc.getToken();
final AccessToken.Access access = token.getRealmAccess();
final Map<String, Object> claims = token.getOtherClaims();
final List roles = (List)claims.get("roles");
if (roles != null) {
for (Object role : roles) {
access.addRole(role.toString());
}
}
}
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment