001/*
002 *   Copyright 2020 Vonage
003 *
004 *   Licensed under the Apache License, Version 2.0 (the "License");
005 *   you may not use this file except in compliance with the License.
006 *   You may obtain a copy of the License at
007 *
008 *        http://www.apache.org/licenses/LICENSE-2.0
009 *
010 *   Unless required by applicable law or agreed to in writing, software
011 *   distributed under the License is distributed on an "AS IS" BASIS,
012 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *   See the License for the specific language governing permissions and
014 *   limitations under the License.
015 */
016package com.vonage.client.auth;
017
018import com.nexmo.jwt.Jwt;
019import org.apache.http.client.methods.RequestBuilder;
020
021import java.io.IOException;
022import java.nio.file.Files;
023import java.nio.file.Path;
024
025public class JWTAuthMethod extends AbstractAuthMethod {
026    private static final int SORT_KEY = 10;
027    private Jwt jwt;
028
029    public JWTAuthMethod(final String applicationId, final byte[] privateKey) {
030        this.jwt = Jwt.builder().applicationId(applicationId).privateKeyContents(new String(privateKey)).build();
031    }
032
033    public JWTAuthMethod(String applicationId, Path path) throws IOException {
034        this(applicationId, Files.readAllBytes(path));
035    }
036
037    public String generateToken() {
038        return this.jwt.generate();
039    }
040
041    @Override
042    public RequestBuilder apply(RequestBuilder request) {
043        String token = this.jwt.generate();
044
045        request.setHeader("Authorization", "Bearer " + token);
046        return request;
047    }
048
049    @Override
050    public int getSortKey() {
051        return SORT_KEY;
052    }
053}