blob: fd344111bad755d660f6718d9ef9e282122b6907 [file] [log] [blame]
/**
******************************************************************************
* Copyright © 2017-2018 PTA GmbH.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
*
* http://www.eclipse.org/legal/epl-v10.html
*
******************************************************************************
*/
package org.eclipse.openk.elogbook.auth2.util;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import org.eclipse.openk.elogbook.auth2.model.JwtPayload;
import org.eclipse.openk.elogbook.auth2.model.KeyCloakUser;
import org.eclipse.openk.elogbook.common.JsonGeneratorBase;
import org.eclipse.openk.elogbook.exceptions.BtbInternalServerError;
import java.lang.reflect.Type;
import java.util.List;
public class JwtHelper {
private static final Logger LOGGER = Logger.getLogger(JwtHelper.class.getName());
private JwtHelper() {}
public static JwtPayload getJwtPayload(String token) {
String plainToken = JwtHelper.formatToken(token);
String[] parts = plainToken.split("[.]");
String jwtPayload = parts[1]; // we need only this here
Base64 decoder = new Base64(true);
byte[] decodedBytes = decoder.decode(jwtPayload);
jwtPayload = new String(decodedBytes);
return getJwtPayloadFromJson(jwtPayload);
}
public static JwtPayload getJwtPayloadFromJson(String json) {
JwtPayload jwtPayload = JsonGeneratorBase.getGson().fromJson(json, JwtPayload.class);
return JsonGeneratorBase.getGson().fromJson(json, JwtPayload.class);
}
public static List<KeyCloakUser> getUserListFromJson(String json) throws BtbInternalServerError {
try {
Type listType = new TypeToken<List<KeyCloakUser>>(){}.getType();
return JsonGeneratorBase.getGson().fromJson(json, listType);
} catch (JsonSyntaxException ex) {
LOGGER.error("Error in getUserListFromJson", ex);
throw new BtbInternalServerError("JsonSyntaxException");
}
}
public static String formatToken(String accessToken) {
return accessToken != null ? accessToken.replace("Bearer", "").trim() : "";
}
}