RestMacAuthPBean.java
2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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;
}
}