| /* |
| ******************************************************************************* |
| * Copyright (c) 2018 Contributors to the Eclipse Foundation |
| * |
| * See the NOTICE file(s) distributed with this work for additional |
| * information regarding copyright ownership. |
| * |
| * This program and the accompanying materials are made available under the |
| * terms of the Eclipse Public License v. 2.0 which is available at |
| * http://www.eclipse.org/legal/epl-2.0. |
| * |
| * SPDX-License-Identifier: EPL-2.0 |
| ******************************************************************************* |
| */ |
| |
| package org.eclipse.openk.auth2.util; |
| |
| import com.google.gson.JsonSyntaxException; |
| import com.google.gson.reflect.TypeToken; |
| import org.apache.commons.codec.binary.Base64; |
| import org.apache.http.HttpStatus; |
| import org.apache.log4j.Logger; |
| import org.eclipse.openk.auth2.model.JwtPayload; |
| import org.eclipse.openk.auth2.model.KeyCloakUser; |
| import org.eclipse.openk.common.JsonGeneratorBase; |
| import org.eclipse.openk.core.exceptions.HttpStatusException; |
| import java.io.UnsupportedEncodingException; |
| 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) throws HttpStatusException { |
| |
| if (token != null && !token.isEmpty()) { |
| 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); |
| try { |
| jwtPayload = new String(decodedBytes, "UTF-8" ); |
| } catch (UnsupportedEncodingException e) { |
| LOGGER.error( "Unsupported encoding", e ); |
| jwtPayload = new String(decodedBytes ); |
| } |
| |
| return getJwtPayloadFromJson(jwtPayload); |
| } |
| else { |
| throw new HttpStatusException(HttpStatus.SC_UNAUTHORIZED); |
| } |
| |
| } |
| |
| public static JwtPayload getJwtPayloadFromJson(String json) { |
| return org.eclipse.openk.common.JsonGeneratorBase.getGson().fromJson(json, JwtPayload.class); |
| } |
| |
| public static List<KeyCloakUser> getUserListFromJson(String json) throws HttpStatusException { |
| 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 HttpStatusException(HttpStatus.SC_INTERNAL_SERVER_ERROR); |
| } |
| } |
| |
| public static String formatToken(String accessToken) { |
| return accessToken != null ? accessToken.replace("Bearer", "").trim() : ""; |
| } |
| |
| } |