All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.identityx.auth.impl.JoseResponseAuthenticator Maven / Gradle / Ivy

package com.identityx.auth.impl;

import java.io.UnsupportedEncodingException;
import java.security.PrivateKey;
import java.text.MessageFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.identityx.auth.def.IResponse;
import com.identityx.auth.def.ITokenKey;
import com.identityx.auth.impl.keys.PrivateApiKey;
import com.identityx.auth.support.RequestAuthenticationException;
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.JWSObject;
import com.nimbusds.jose.JWSSigner;
import com.nimbusds.jose.Payload;
import com.nimbusds.jose.crypto.RSASSASigner;

public class JoseResponseAuthenticator extends DigestResponseAuthenticator {

	private static final Log log = LogFactory.getLog(JoseResponseAuthenticator.class);
	private JWSAlgorithm currentAlgorithm = JWSAlgorithm.RS256;
	public static final String AUTHENTICATION_SCHEME = "JWS";
	public static final String JWS = "JWS";
	private String signingCerts;
	
	
	public String getSigningCerts() {
		return signingCerts;
	}


	public void setSigningCerts(String signingCerts) {
		this.signingCerts = signingCerts;
	}


	@Override
	public String buildAuthorizationHeader(IResponse response, final ITokenKey apiKey, final String nonce, String dateStamp, String timeStamp) throws UnsupportedEncodingException {
						
    	if (!(apiKey instanceof PrivateApiKey)) {
    		throw new IllegalArgumentException("apiKey needs to be of type AsymApiKey");
    	}
    	PrivateKey privateKey = (PrivateKey)((PrivateApiKey)apiKey).getKey();
    	if (privateKey == null) {
    		throw new IllegalArgumentException("apiKey needs to contain a valid private key");
    	}
    	
    	if (log.isTraceEnabled()) {
			log.trace(MessageFormat.format("Timestamp: {0}", new Object[] { timeStamp }));
		}
    	
    	String canonicalResponse = buildCanonicalResponse(response);
        String canonicalResponseHashHex = toHex(hash(canonicalResponse));
        log.debug("canonicalResponseHashHex:" + canonicalResponseHashHex);

    	JWSPayload jwsPayload = new JWSPayload(apiKey.getId(), nonce, dateStamp, timeStamp, getSignedHeadersString(response), canonicalResponseHashHex, signingCerts);
    	
        String stringToSign = null;
		try {
			stringToSign = (new ObjectMapper()).writeValueAsString(jwsPayload);
		} catch (JsonProcessingException e1) {
			log.error("Failed to serialize the jws token", e1);
			throw new RequestAuthenticationException("Failed to serialize the jws token", e1);
		}

        if (log.isDebugEnabled()) {
        	log.debug("String to Sign: " + stringToSign);
        }

        JWSSigner signer = new RSASSASigner(privateKey);
        JWSObject jwsObject = new JWSObject(new JWSHeader(currentAlgorithm), new Payload(stringToSign));
        try {
			jwsObject.sign(signer);
		} catch (JOSEException e) {
			log.error("Failed to sign the jws token", e);
			throw new RequestAuthenticationException("Failed to sign the jws token", e);
		}

        String jwsString = jwsObject.serialize();    
        String authorizationHeader = AUTHENTICATION_SCHEME + " " + createNameValuePair(JWS, jwsString);
	        
        log.debug("AUTHORIZATION HEADER is " + authorizationHeader);    
        return authorizationHeader;
        
	}

	@Override
    protected List getSignedHeaderNames(IResponse response) {
    	ArrayList result = new ArrayList();
		String authHeader = response.getHeaders().getFirst(AuthSettings.AUTHORIZATION_HEADER);
		if (authHeader == null) return null;
		JWSPayload jwsPayload = getJWSPayloadFromHeader(authHeader);
		String headers = jwsPayload.getSignedHeadersString();
		if (headers != null) {
			for (String headerName : headers.split(";")) {
				result.add(headerName.toLowerCase().replaceAll("\\s", ""));
			}
		}
		return result;
    }

	public JWSPayload getJWSPayloadFromHeader(String authHeader) {
		
		JWSObject jwsObject = getJWSObjectFromHeader(authHeader);
		String jsonPayload = jwsObject.getPayload().toJSONObject().toJSONString();
			    	
		ObjectMapper mapper= new ObjectMapper();
		JWSPayload jwsPayload = null;
		try {
			jwsPayload = mapper.readValue(jsonPayload, JWSPayload.class);
		} catch (Exception e) {
			log.error("Can't get the JWSObject from the header", e);
			throw new RuntimeException("Can't get the JWSObject from the header", e);			
		}
		return jwsPayload;
	}

	public JWSObject getJWSObjectFromHeader(String authHeader) {
		
		String jwsString = authHeader.substring(JoseRequestAuthenticator.AUTHENTICATION_SCHEME.length() + 1);
		if (!jwsString.startsWith(JoseRequestAuthenticator.JWS + "=")) {
			log.error("Can't get the JWSObject from the header");
			throw new RuntimeException("Unknown format for header:" + authHeader);
		}
		jwsString = jwsString.replace(" ", "");
		jwsString = jwsString.substring(JoseRequestAuthenticator.JWS.length() + 1);
		JWSObject jwsObject;
		try {
			jwsObject = JWSObject.parse(jwsString);
		} catch (ParseException e) {
			log.error("Can't get the JWSObject from the header", e);
			throw new RuntimeException("Can't get the JWSObject from the header", e);
		}
		return jwsObject;
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy