238f888bbd30f901b95bb7d93ab595b02a9a8b5d
[ccsdk/features.git] / sdnr / wt / oauth-provider / provider-jar / src / main / java / org / onap / ccsdk / features / sdnr / wt / oauthprovider / providers / TokenCreator.java
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP : ccsdk features
4  * ================================================================================
5  * Copyright (C) 2021 highstreet technologies GmbH Intellectual Property.
6  * All rights reserved.
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
11  *
12  *     http://www.apache.org/licenses/LICENSE-2.0
13  *
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=========================================================
20  *
21  */
22 package org.onap.ccsdk.features.sdnr.wt.oauthprovider.providers;
23
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 javax.servlet.http.HttpServletRequest;
35 import org.apache.shiro.authc.BearerToken;
36 import org.bouncycastle.jce.provider.BouncyCastleProvider;
37 import org.onap.ccsdk.features.sdnr.wt.oauthprovider.data.Config;
38 import org.onap.ccsdk.features.sdnr.wt.oauthprovider.data.UserTokenPayload;
39 import org.onap.ccsdk.features.sdnr.wt.oauthprovider.http.AuthHttpServlet;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 public class TokenCreator {
44
45     private static final Logger LOG = LoggerFactory.getLogger(AuthHttpServlet.class.getName());
46     private final String issuer;
47     private static TokenCreator _instance;
48     private final long tokenLifetimeSeconds;
49     private final Algorithm algorithm;
50
51     private static final String ROLES_CLAIM = "roles";
52     private static final String FAMILYNAME_CLAIM = "family_name";
53     private static final String NAME_CLAIM = "name";
54
55     static {
56         Security.addProvider(
57                 new BouncyCastleProvider()
58        );
59     }
60     public static TokenCreator getInstance(Config config) throws IllegalArgumentException, IOException {
61         if (_instance == null) {
62             _instance = new TokenCreator(config);
63         }
64         return _instance;
65     }
66
67     public static TokenCreator getInstance(String alg, String secret, String issuer, long tokenLifetime)
68             throws IllegalArgumentException, IOException {
69         return getInstance(alg, secret, null, issuer, tokenLifetime);
70     }
71
72     public static TokenCreator getInstance(String alg, String secret, String pubkey, String issuer, long tokenLifetime)
73             throws IllegalArgumentException, IOException {
74         if (_instance == null) {
75             _instance = new TokenCreator(alg, secret, pubkey, issuer, tokenLifetime);
76         }
77         return _instance;
78     }
79
80     private TokenCreator(Config config) throws IllegalArgumentException, IOException {
81         this(config.getAlgorithm(), config.getTokenSecret(), config.getPublicKey(), config.getTokenIssuer(),
82                 config.getTokenLifetime());
83     }
84
85     private TokenCreator(String alg, String secret, String pubkey, String issuer, long tokenLifetime)
86             throws IllegalArgumentException, IOException {
87         this.issuer = issuer;
88         this.tokenLifetimeSeconds = tokenLifetime;
89         this.algorithm = this.createAlgorithm(alg, secret, pubkey);
90     }
91
92     private Algorithm createAlgorithm(String alg, String secret, String pubkey)
93             throws IllegalArgumentException, IOException {
94         if(alg==null) {
95             alg = Config.TOKENALG_HS256;
96         }
97         switch (alg) {
98             case Config.TOKENALG_HS256:
99                 return Algorithm.HMAC256(secret);
100             case Config.TOKENALG_RS256:
101                 return Algorithm.RSA256(RSAKeyReader.getPublicKey(pubkey), RSAKeyReader.getPrivateKey(secret));
102             case Config.TOKENALG_RS512:
103                 return Algorithm.RSA512(RSAKeyReader.getPublicKey(pubkey), RSAKeyReader.getPrivateKey(secret));
104             case Config.TOKENALG_CLIENT_RS256:
105                 return Algorithm.RSA256(RSAKeyReader.getPublicKey(pubkey), null);
106             case Config.TOKENALG_CLIENT_RS512:
107                 return Algorithm.RSA512(RSAKeyReader.getPublicKey(pubkey), null);
108         }
109         throw new IllegalArgumentException(String.format("unable to find algorithm for %s", alg));
110
111     }
112
113     public BearerToken createNewJWT(UserTokenPayload data) {
114         final String token = JWT.create().withIssuer(issuer).withExpiresAt(new Date(data.getExp()))
115                 .withIssuedAt(new Date(data.getIat())).withSubject(data.getPreferredUsername())
116                 .withClaim(NAME_CLAIM, data.getGivenName()).withClaim(FAMILYNAME_CLAIM, data.getFamilyName())
117                 .withArrayClaim(ROLES_CLAIM, data.getRoles().toArray(new String[data.getRoles().size()]))
118                 .sign(this.algorithm);
119         LOG.trace("token created: {}", token);
120         return new BearerToken(token);
121     }
122
123     public DecodedJWT verify(String token) {
124         DecodedJWT jwt = null;
125         LOG.debug("try to verify token {}", token);
126         try {
127             JWTVerifier verifier = JWT.require(this.algorithm).withIssuer(issuer).build();
128             jwt = verifier.verify(token);
129
130         } catch (JWTVerificationException e) {
131             LOG.warn("unable to verify token {}:", token, e);
132         }
133         return jwt;
134     }
135
136     public long getDefaultExp() {
137         return new Date().getTime() + (this.tokenLifetimeSeconds * 1000);
138     }
139
140     public long getDefaultExp(long expIn) {
141         return new Date().getTime() + expIn;
142     }
143
144     public long getDefaultIat() {
145         return new Date().getTime();
146     }
147
148     public UserTokenPayload decode(HttpServletRequest req) throws JWTDecodeException {
149         final String authHeader = req.getHeader("Authorization");
150         if (authHeader == null || !authHeader.startsWith("Bearer")) {
151             return null;
152         }
153         DecodedJWT jwt = JWT.decode(authHeader.substring(7));
154         UserTokenPayload data = new UserTokenPayload();
155         data.setRoles(Arrays.asList(jwt.getClaim(ROLES_CLAIM).asArray(String.class)));
156         data.setExp(jwt.getExpiresAt().getTime());
157         data.setFamilyName(jwt.getClaim(FAMILYNAME_CLAIM).asString());
158         data.setGivenName(jwt.getClaim(NAME_CLAIM).asString());
159         data.setPreferredUsername(jwt.getClaim(NAME_CLAIM).asString());
160
161         return data;
162     }
163
164 }