RestMacAuthPBean.java 2.24 KB
package fi.codecrew.moya.beans.auth;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import fi.codecrew.moya.AuthenticationResult;
import fi.codecrew.moya.beans.JaasBean.UserType;
import fi.codecrew.moya.beans.JaasBeanLocal;
import fi.codecrew.moya.model.ApiApplicationInstance;
import fi.codecrew.moya.utilities.PasswordFunctions;

@LocalBean
@Stateless
public class RestMacAuthPBean extends ApiAuth implements AuthenticationFormat {

	private static final Logger logger = LoggerFactory.getLogger(RestMacAuthPBean.class);
	
	@Override
	public AuthenticationResult authenticate(String username, String password) {

		AuthenticationResult ret = null;
		if ((username == null || username.isEmpty()) && password.startsWith(JaasBeanLocal.REST_PREFIX)) {
			ret = new AuthenticationResult();
			ret.setUsertype(UserType.REST.name());
			ret.setUsername(restAuth(password));
		}
		return ret;
	}

	private String restAuth(String restauth) {
		String[] authsplit = restauth.split(":", 6);
		logger.info("Trying to auth with rest {}", (Object) authsplit);
		if (authsplit.length != 6 || !authsplit[0].equals("rest")) {
			return null;
		}

		return authenticateApp(authsplit[5], authsplit[1], authsplit[2], authsplit[3], authsplit[4]);
	}

	public String authenticateApp(String pathInfo, String appId, String userId, String appStamp, String mac) {

		logger.info("Authenticat app with pathinfo {}, appid {}, userid {}, appstamp {}, mac {}",
				new Object[] { pathInfo, appId, userId, appStamp, mac });
		if (mac == null) {
			logger.warn("Rest auth failed: Mac is null");
			return null;
		}
		ApiApplicationInstance apiInstance = verifyAppInstance(appId, userId);
		if (apiInstance == null)
			return null;

		String ret = null;
		String macSource = PasswordFunctions.mkSeparatedString("+", pathInfo, appId, userId, appStamp,
				apiInstance.getSecretKey());
		String macHash = PasswordFunctions.calculateSha1(macSource);
		logger.info("Calculated hash {}, comparing to {}", macHash, mac);
		if (mac.equalsIgnoreCase(macHash)) {
			ret = getUsername(apiInstance);
		} else {
			logger.warn("Rest auth failed: Calculated hash does not match received mac: Calculated {}, received {}",
					macHash, mac);
		}

		return ret;
	}

}