RestMacAuthPBean.java
2.76 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
71
72
73
74
75
76
77
78
79
80
81
package fi.codecrew.moya.beans.auth;
import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import fi.codecrew.moya.beans.EventBean;
import fi.codecrew.moya.model.LanEvent;
import fi.codecrew.moya.utilities.UserLoginUtils;
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);
@EJB
private EventBean eventbean;
@Override
public AuthenticationResult authenticate(String jaasUsername, String password) {
String username = UserLoginUtils.getUsernameFromJaasString(jaasUsername);
String domain = UserLoginUtils.getDomainFromJaasString(jaasUsername);
LanEvent event = eventbean.getEventForHostname(domain);
AuthenticationResult ret = null;
if ((username == null || username.isEmpty()) && password.startsWith(JaasBeanLocal.REST_PREFIX)) {
ret = new AuthenticationResult();
ret.setUsertype(UserType.REST.name());
if(restAuth(password, event) != null) {
ret.setUsername(jaasUsername);
}
//ret.setUsername(restAuth(password, event) + '@'+domain);
}
return ret;
}
private String restAuth(String restauth, LanEvent event) {
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], event);
}
public String authenticateApp(String pathInfo, String appId, String userId, String appStamp, String mac, LanEvent event) {
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, event);
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;
}
}