2  * ============LICENSE_START=======================================================
 
   3  * ONAP : ccsdk features
 
   4  * ================================================================================
 
   5  * Copyright (C) 2021 highstreet technologies GmbH Intellectual Property.
 
   7  * ================================================================================
 
   8  * Licensed under the Apache License, Version 2.0 (the "License");
 
   9  * you may not use this file except in compliance with the License.
 
  10  * You may obtain a copy of the License at
 
  12  *     http://www.apache.org/licenses/LICENSE-2.0
 
  14  * Unless required by applicable law or agreed to in writing, software
 
  15  * distributed under the License is distributed on an "AS IS" BASIS,
 
  16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
  17  * See the License for the specific language governing permissions and
 
  18  * limitations under the License.
 
  19  * ============LICENSE_END=========================================================
 
  22 package org.onap.ccsdk.features.sdnr.wt.oauthprovider.providers;
 
  24 import com.auth0.jwt.JWT;
 
  25 import com.auth0.jwt.algorithms.Algorithm;
 
  26 import com.auth0.jwt.exceptions.JWTDecodeException;
 
  27 import com.auth0.jwt.exceptions.JWTVerificationException;
 
  28 import com.auth0.jwt.interfaces.DecodedJWT;
 
  29 import com.auth0.jwt.interfaces.JWTVerifier;
 
  30 import java.io.IOException;
 
  31 import java.security.Security;
 
  32 import java.util.Arrays;
 
  33 import java.util.Date;
 
  34 import java.util.Optional;
 
  35 import javax.servlet.http.Cookie;
 
  36 import javax.servlet.http.HttpServletRequest;
 
  37 import org.bouncycastle.jce.provider.BouncyCastleProvider;
 
  38 import org.onap.ccsdk.features.sdnr.wt.oauthprovider.data.Config;
 
  39 import org.onap.ccsdk.features.sdnr.wt.oauthprovider.data.UserTokenPayload;
 
  40 import org.onap.ccsdk.features.sdnr.wt.oauthprovider.http.AuthHttpServlet;
 
  41 import org.apache.shiro.authc.BearerToken;
 
  42 import org.slf4j.Logger;
 
  43 import org.slf4j.LoggerFactory;
 
  45 public class TokenCreator {
 
  47     private static final Logger LOG = LoggerFactory.getLogger(AuthHttpServlet.class.getName());
 
  48     private final String issuer;
 
  49     private static TokenCreator _instance;
 
  50     private final long tokenLifetimeSeconds;
 
  51     private final Algorithm algorithm;
 
  53     private static final String ROLES_CLAIM = "roles";
 
  54     private static final String FAMILYNAME_CLAIM = "family_name";
 
  55     private static final String NAME_CLAIM = "name";
 
  56     private static final String PROVIDERID_CLAIM = "provider_id";
 
  57     private static final String COOKIE_NAME_AUTH = "token";
 
  61                 new BouncyCastleProvider()
 
  64     public static TokenCreator getInstance(Config config) throws IllegalArgumentException, IOException {
 
  65         if (_instance == null) {
 
  66             _instance = new TokenCreator(config);
 
  71     public static TokenCreator getInstance(String alg, String secret, String issuer, long tokenLifetime)
 
  72             throws IllegalArgumentException, IOException {
 
  73         return getInstance(alg, secret, null, issuer, tokenLifetime);
 
  76     public static TokenCreator getInstance(String alg, String secret, String pubkey, String issuer, long tokenLifetime)
 
  77             throws IllegalArgumentException, IOException {
 
  78         if (_instance == null) {
 
  79             _instance = new TokenCreator(alg, secret, pubkey, issuer, tokenLifetime);
 
  84     private TokenCreator(Config config) throws IllegalArgumentException, IOException {
 
  85         this(config.getAlgorithm(), config.getTokenSecret(), config.getPublicKey(), config.getTokenIssuer(),
 
  86                 config.getTokenLifetime());
 
  89     private TokenCreator(String alg, String secret, String pubkey, String issuer, long tokenLifetime)
 
  90             throws IllegalArgumentException, IOException {
 
  92         this.tokenLifetimeSeconds = tokenLifetime;
 
  93         this.algorithm = this.createAlgorithm(alg, secret, pubkey);
 
  96     private Algorithm createAlgorithm(String alg, String secret, String pubkey)
 
  97             throws IllegalArgumentException, IOException {
 
  99             alg = Config.TOKENALG_HS256;
 
 102             case Config.TOKENALG_HS256:
 
 103                 return Algorithm.HMAC256(secret);
 
 104             case Config.TOKENALG_RS256:
 
 105                 return Algorithm.RSA256(RSAKeyReader.getPublicKey(pubkey), RSAKeyReader.getPrivateKey(secret));
 
 106             case Config.TOKENALG_RS512:
 
 107                 return Algorithm.RSA512(RSAKeyReader.getPublicKey(pubkey), RSAKeyReader.getPrivateKey(secret));
 
 108             case Config.TOKENALG_CLIENT_RS256:
 
 109                 return Algorithm.RSA256(RSAKeyReader.getPublicKey(pubkey), null);
 
 110             case Config.TOKENALG_CLIENT_RS512:
 
 111                 return Algorithm.RSA512(RSAKeyReader.getPublicKey(pubkey), null);
 
 113         throw new IllegalArgumentException(String.format("unable to find algorithm for %s", alg));
 
 117     public BearerToken createNewJWT(UserTokenPayload data) {
 
 118         final String token = JWT.create().withIssuer(issuer).withExpiresAt(new Date(data.getExp()))
 
 119                 .withIssuedAt(new Date(data.getIat())).withSubject(data.getPreferredUsername())
 
 120                 .withClaim(NAME_CLAIM, data.getGivenName()).withClaim(FAMILYNAME_CLAIM, data.getFamilyName())
 
 121                 .withClaim(PROVIDERID_CLAIM, data.getProviderId())
 
 122                 .withArrayClaim(ROLES_CLAIM, data.getRoles().toArray(new String[data.getRoles().size()]))
 
 123                 .sign(this.algorithm);
 
 124         LOG.trace("token created: {}", token);
 
 125         return new BearerToken(token);
 
 128     public DecodedJWT verify(String token) {
 
 129         DecodedJWT jwt = null;
 
 130         LOG.debug("try to verify token {}", token);
 
 132             JWTVerifier verifier = JWT.require(this.algorithm).withIssuer(issuer).build();
 
 133             jwt = verifier.verify(token);
 
 135         } catch (JWTVerificationException e) {
 
 136             LOG.warn("unable to verify token {}:", token, e);
 
 141     public long getDefaultExp() {
 
 142         return new Date().getTime() + (this.tokenLifetimeSeconds * 1000);
 
 145     public long getDefaultExp(long expIn) {
 
 146         return new Date().getTime() + expIn;
 
 149     public long getDefaultIat() {
 
 150         return new Date().getTime();
 
 153     public String getBearerToken(HttpServletRequest req) {
 
 154         return this.getBearerToken(req, false);
 
 157     public String getBearerToken(HttpServletRequest req, boolean checkCookie) {
 
 158         final String authHeader = req.getHeader("Authorization");
 
 159         if ((authHeader == null || !authHeader.startsWith("Bearer")) && checkCookie) {
 
 160             Cookie[] cookies = req.getCookies();
 
 161             Optional<Cookie> ocookie = Optional.empty();
 
 162             if (cookies != null) {
 
 163                 ocookie = Arrays.stream(cookies).filter(c -> c != null && COOKIE_NAME_AUTH.equals(c.getName()))
 
 166             if (ocookie.isEmpty()) {
 
 169             return ocookie.get().getValue();
 
 171         return authHeader.substring(7);
 
 174     public UserTokenPayload decode(HttpServletRequest req) throws JWTDecodeException {
 
 175         final String token = this.getBearerToken(req);
 
 176         return token != null ? this.decode(token) : null;
 
 179     public UserTokenPayload decode(String token) {
 
 183         DecodedJWT jwt = JWT.decode(token);
 
 184         UserTokenPayload data = new UserTokenPayload();
 
 185         data.setRoles(Arrays.asList(jwt.getClaim(ROLES_CLAIM).asArray(String.class)));
 
 186         data.setExp(jwt.getExpiresAt().getTime());
 
 187         data.setFamilyName(jwt.getClaim(FAMILYNAME_CLAIM).asString());
 
 188         data.setGivenName(jwt.getClaim(NAME_CLAIM).asString());
 
 189         data.setPreferredUsername(jwt.getClaim(NAME_CLAIM).asString());
 
 190         data.setProviderId(jwt.getClaim(PROVIDERID_CLAIM).asString());
 
 194     public Cookie createAuthCookie(BearerToken data) {
 
 195         Cookie cookie = new Cookie(COOKIE_NAME_AUTH, data.getToken());
 
 196         cookie.setMaxAge((int) this.tokenLifetimeSeconds);
 
 198         cookie.setHttpOnly(true);
 
 199         cookie.setSecure(true);