aboutsummaryrefslogtreecommitdiffstats
path: root/sdnr/wt/oauth-provider/provider-jar/src/main/java/org/onap/ccsdk/features/sdnr/wt/oauthprovider/providers/TokenCreator.java
blob: e7e9b72f93162beac976b9517fc06517fd651ffb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
/*
 * ============LICENSE_START=======================================================
 * ONAP : ccsdk features
 * ================================================================================
 * Copyright (C) 2021 highstreet technologies GmbH Intellectual Property.
 * All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 *
 */
package org.onap.ccsdk.features.sdnr.wt.oauthprovider.providers;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import java.util.Arrays;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.onap.ccsdk.features.sdnr.wt.oauthprovider.data.Config;
import org.onap.ccsdk.features.sdnr.wt.oauthprovider.data.UserTokenPayload;
import org.onap.ccsdk.features.sdnr.wt.oauthprovider.http.AuthHttpServlet;
import org.opendaylight.aaa.shiro.filters.backport.BearerToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TokenCreator {

    private static final Logger LOG = LoggerFactory.getLogger(AuthHttpServlet.class.getName());
    private static final long DEFAULT_TOKEN_LIFETIME_MS = 30 * 60 * 1000;
    private final String issuer;
    private static TokenCreator _instance;
    private final String secret;

    private static final String ROLES_CLAIM = "roles";
    private static final String FAMILYNAME_CLAIM = "family_name";
    private static final String NAME_CLAIM = "name";

    public static TokenCreator getInstance(Config config) {
        if (_instance == null) {
            _instance = new TokenCreator(config);
        }
        return _instance;
    }
    public static TokenCreator getInstance(String secret, String issuer) {
        if (_instance == null) {
            _instance = new TokenCreator(secret, issuer);
        }
        return _instance;
    }

    private TokenCreator(Config config) {
        this(config.getTokenSecret(),config.getTokenIssuer());
    }
    private TokenCreator(String secret, String issuer) {
        this.secret = secret;
        this.issuer = issuer;
    }

    public BearerToken createNewJWT(UserTokenPayload data) {
        Algorithm algorithm = Algorithm.HMAC256(secret);
        final String token = JWT.create().withIssuer(issuer).withExpiresAt(new Date(data.getExp()))
                .withSubject(data.getPreferredUsername()).withClaim(NAME_CLAIM, data.getGivenName())
                .withClaim(FAMILYNAME_CLAIM, data.getFamilyName())
                .withArrayClaim(ROLES_CLAIM, data.getRoles().toArray(new String[data.getRoles().size()]))
                .sign(algorithm);
        return new BearerToken(token);
    }

    public DecodedJWT verify(String token) {
        DecodedJWT jwt = null;
        LOG.debug("try to verify token {}", token);
        try {
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm).withIssuer(issuer).build();
            jwt = verifier.verify(token);

        } catch (JWTVerificationException e) {
            LOG.warn("unable to verify token {}:", token, e);
        }
        return jwt;
    }

    public long getDefaultExp() {
        return new Date().getTime() + DEFAULT_TOKEN_LIFETIME_MS;
    }

    public long getDefaultExp(long exp_in) {
        return new Date().getTime() + exp_in;
    }

    public UserTokenPayload decode(HttpServletRequest req) throws JWTDecodeException {
        final String authHeader = req.getHeader("Authorization");
        if (authHeader == null || !authHeader.startsWith("Bearer")) {
            return null;
        }
        DecodedJWT jwt = JWT.decode(authHeader.substring(7));
        UserTokenPayload data = new UserTokenPayload();
        data.setRoles(Arrays.asList(jwt.getClaim(ROLES_CLAIM).asArray(String.class)));
        data.setExp(jwt.getExpiresAt().getTime());
        data.setFamilyName(jwt.getClaim(FAMILYNAME_CLAIM).asString());
        data.setGivenName(jwt.getClaim(NAME_CLAIM).asString());
        data.setPreferredUsername(jwt.getClaim(NAME_CLAIM).asString());

        return data;
    }
}