001/* 002 * Copyright 2024 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.vonage.jwt.Jwt; 019 020public class JWTAuthMethod extends BearerAuthMethod { 021 private static final int SORT_KEY = 10; 022 023 private final Jwt jwt; 024 private final String applicationId, privateKeyContents; 025 026 public JWTAuthMethod(final String applicationId, final byte[] privateKey) { 027 jwt = Jwt.builder() 028 .applicationId(this.applicationId = applicationId) 029 .privateKeyContents(this.privateKeyContents = new String(privateKey)) 030 .build(); 031 } 032 033 public String generateToken() { 034 return jwt.generate(); 035 } 036 037 public String getApplicationId() { 038 return applicationId; 039 } 040 041 /** 042 * Convenience method for creating custom JWTs. 043 * 044 * @return A new {@link Jwt.Builder} with the application ID and private key already set. 045 * @since 8.0.0-beta2 046 */ 047 public Jwt.Builder newJwt() { 048 return Jwt.builder().applicationId(applicationId).privateKeyContents(privateKeyContents); 049 } 050 051 @Override 052 protected final String getBearerToken() { 053 return generateToken(); 054 } 055 056 @Override 057 public int getSortKey() { 058 return SORT_KEY; 059 } 060}