001/* 002 * acme4j - Java ACME client 003 * 004 * Copyright (C) 2015 Richard "Shred" Körber 005 * http://acme4j.shredzone.org 006 * 007 * Licensed under the Apache License, Version 2.0 (the "License"); 008 * you may not use this file except in compliance with the License. 009 * 010 * This program is distributed in the hope that it will be useful, 011 * but WITHOUT ANY WARRANTY; without even the implied warranty of 012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 013 */ 014package org.shredzone.acme4j.challenge; 015 016import static org.shredzone.acme4j.toolbox.AcmeUtils.base64UrlEncode; 017 018import java.io.Serial; 019 020import org.shredzone.acme4j.Login; 021import org.shredzone.acme4j.exception.AcmeProtocolException; 022import org.shredzone.acme4j.toolbox.AcmeUtils; 023import org.shredzone.acme4j.toolbox.JSON; 024import org.shredzone.acme4j.toolbox.JoseUtils; 025 026/** 027 * A generic extension of {@link Challenge} that handles challenges with a {@code token} 028 * and {@code keyAuthorization}. 029 */ 030public class TokenChallenge extends Challenge { 031 @Serial 032 private static final long serialVersionUID = 1634133407432681800L; 033 034 protected static final String KEY_TOKEN = "token"; 035 036 /** 037 * Creates a new generic {@link TokenChallenge} object. 038 * 039 * @param login 040 * {@link Login} the resource is bound with 041 * @param data 042 * {@link JSON} challenge data 043 */ 044 public TokenChallenge(Login login, JSON data) { 045 super(login, data); 046 } 047 048 /** 049 * Gets the token. 050 */ 051 protected String getToken() { 052 var token = getJSON().get(KEY_TOKEN).asString(); 053 if (!AcmeUtils.isValidBase64Url(token)) { 054 throw new AcmeProtocolException("Invalid token: " + token); 055 } 056 return token; 057 } 058 059 /** 060 * Computes the key authorization for the given token. 061 * <p> 062 * The default is {@code token + '.' + base64url(jwkThumbprint)}. Subclasses may 063 * override this method if a different algorithm is used. 064 * 065 * @param token 066 * Token to be used 067 * @return Key Authorization string for that token 068 * @since 2.12 069 */ 070 protected String keyAuthorizationFor(String token) { 071 var pk = getLogin().getKeyPair().getPublic(); 072 return token + '.' + base64UrlEncode(JoseUtils.thumbprint(pk)); 073 } 074 075 /** 076 * Returns the authorization string. 077 * <p> 078 * The default uses {@link #keyAuthorizationFor(String)} to compute the key 079 * authorization of {@link #getToken()}. Subclasses may override this method if a 080 * different algorithm is used. 081 */ 082 public String getAuthorization() { 083 return keyAuthorizationFor(getToken()); 084 } 085 086}