use of com.tremolosecurity.proxy.auth.AuthInfo in project OpenUnison by TremoloSecurity.
the class ClientCredentialsGrantPostAuth method runAfterSuccessfulAuthentication.
@Override
public void runAfterSuccessfulAuthentication(HttpServletRequest req, HttpServletResponse resp, UrlHolder holder, AuthChainType act, RequestHolder reqHolder, AuthController actl, NextSys next) throws IOException, ServletException {
HttpSession session = req.getSession();
AuthInfo authData = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo();
if (!azSys.checkRules(authData, GlobalEntries.getGlobalEntries().getConfigManager(), trust.getClientAzRules(), new HashMap<String, Object>())) {
AccessLog.log(AccessEvent.AzFail, holder.getApp(), req, authData, new StringBuilder().append("client not authorized for client_credentials grant on trust '").append(trust.getClientID()).append("'").toString());
resp.sendError(403);
return;
}
JSONObject existingClaims = new JSONObject();
for (String attrName : authData.getAttribs().keySet()) {
Attribute attr = authData.getAttribs().get(attrName);
if (attr.getValues().size() == 1) {
existingClaims.put(attrName, attr.getValues().get(0));
} else {
JSONArray vals = new JSONArray();
vals.addAll(attr.getValues());
existingClaims.put(attrName, vals);
}
}
OpenIDConnectAccessToken access = new OpenIDConnectAccessToken();
OidcSessionState oidcSession = idp.createUserSession(req, trust.getClientID(), holder, trust, authData.getUserDN(), GlobalEntries.getGlobalEntries().getConfigManager(), access, UUID.randomUUID().toString(), authData.getAuthChain(), existingClaims, null);
Gson gson = new Gson();
String json = gson.toJson(access);
resp.setContentType("application/json");
resp.getOutputStream().write(json.getBytes("UTF-8"));
resp.getOutputStream().flush();
if (logger.isDebugEnabled()) {
logger.debug("Token JSON : '" + json + "'");
}
AccessLog.log(AccessEvent.AzSuccess, holder.getApp(), req, authData, "");
}
use of com.tremolosecurity.proxy.auth.AuthInfo in project OpenUnison by TremoloSecurity.
the class TokenData method completeFederation.
private void completeFederation(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException, MalformedURLException {
final OpenIDConnectTransaction transaction = (OpenIDConnectTransaction) request.getSession().getAttribute(OpenIDConnectIdP.TRANSACTION_DATA);
final AuthInfo authInfo = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo();
if (!authInfo.isAuthComplete()) {
logger.warn("Attempted completetd federation before autthentication is completeed, clearing authentication and redirecting to the original URL");
UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
request.getSession().removeAttribute(ProxyConstants.AUTH_CTL);
holder.getConfig().createAnonUser(request.getSession());
StringBuffer b = new StringBuffer();
b.append(transaction.getRedirectURI()).append("?error=login_reset");
response.sendRedirect(b.toString());
return;
}
request.setAttribute(AzSys.FORCE, "true");
NextSys completeFed = new NextSys() {
public void nextSys(final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException {
UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
HttpFilterRequest filterReq = new HttpFilterRequestImpl(request, null);
HttpFilterResponse filterResp = new HttpFilterResponseImpl(response);
PostProcess postProc = new PostProcess() {
@Override
public void postProcess(HttpFilterRequest req, HttpFilterResponse resp, UrlHolder holder, HttpFilterChain chain) throws Exception {
postResponse(transaction, request, response, authInfo, holder);
}
@Override
public boolean addHeader(String name) {
return false;
}
};
HttpFilterChain chain = new HttpFilterChainImpl(holder, postProc);
try {
chain.nextFilter(filterReq, filterResp, chain);
} catch (Exception e) {
throw new ServletException(e);
}
}
};
AzSys az = new AzSys();
az.doAz(request, response, completeFed);
}
use of com.tremolosecurity.proxy.auth.AuthInfo in project OpenUnison by TremoloSecurity.
the class ScalePassword method doFilter.
@Override
public void doFilter(HttpFilterRequest request, HttpFilterResponse response, HttpFilterChain chain) throws Exception {
Gson gson = new Gson();
request.getServletRequest().setAttribute("com.tremolosecurity.unison.proxy.noRedirectOnError", "com.tremolosecurity.unison.proxy.noRedirectOnError");
if (request.getRequestURI().endsWith("/password/config")) {
response.setContentType("application/json");
ScalePasswordUser ssru = new ScalePasswordUser();
ssru.setConfig(scaleConfig);
AuthInfo userData = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo();
Attribute displayNameAttribute = userData.getAttribs().get(this.scaleConfig.getDisplayNameAttribute());
if (displayNameAttribute != null) {
ssru.setDisplayName(displayNameAttribute.getValues().get(0));
} else {
ssru.setDisplayName("Unknown");
}
ScaleJSUtils.addCacheHeaders(response);
response.getWriter().println(gson.toJson(ssru).trim());
} else if (request.getMethod().equalsIgnoreCase("POST") && request.getRequestURI().endsWith("/password/submit")) {
AuthInfo userData = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo();
String json = new String((byte[]) request.getAttribute(ProxySys.MSG_BODY));
ScaleJSPasswordRequest sr = gson.fromJson(json, ScaleJSPasswordRequest.class);
ScaleError errors = new ScaleError();
if (sr.getPassword1() == null || sr.getPassword2() == null) {
errors.getErrors().add("Passwords are missing");
} else if (!sr.getPassword1().equals(sr.getPassword2())) {
errors.getErrors().add("Passwords do not match");
} else {
List<String> valErrors = this.validator.validate(sr.getPassword1(), userData);
if (valErrors != null && !valErrors.isEmpty()) {
errors.getErrors().addAll(valErrors);
}
if (errors.getErrors().isEmpty()) {
ConfigManager cfgMgr = GlobalEntries.getGlobalEntries().getConfigManager();
WFCall wfCall = new WFCall();
wfCall.setName(this.scaleConfig.getWorkflowName());
wfCall.setReason(this.scaleConfig.getReason());
wfCall.setUidAttributeName(this.scaleConfig.getUidAttribute());
if (this.scaleConfig.isRunSynchronously()) {
wfCall.getRequestParams().put(ProvisioningParams.UNISON_EXEC_TYPE, ProvisioningParams.UNISON_EXEC_SYNC);
} else {
wfCall.getRequestParams().put(ProvisioningParams.UNISON_EXEC_TYPE, ProvisioningParams.UNISON_EXEC_ASYNC);
}
TremoloUser tu = new TremoloUser();
tu.setUid(userData.getAttribs().get(this.scaleConfig.getUidAttribute()).getValues().get(0));
tu.getAttributes().add(new Attribute(this.scaleConfig.getUidAttribute(), userData.getAttribs().get(this.scaleConfig.getUidAttribute()).getValues().get(0)));
tu.setUserPassword(sr.getPassword1());
wfCall.setUser(tu);
try {
com.tremolosecurity.provisioning.workflow.ExecuteWorkflow exec = new com.tremolosecurity.provisioning.workflow.ExecuteWorkflow();
exec.execute(wfCall, GlobalEntries.getGlobalEntries().getConfigManager());
} catch (Exception e) {
logger.error("Could not update user", e);
if (this.scaleConfig.isRunSynchronously()) {
errors.getErrors().add("Unable to set your password, make sure it meets with complexity requirements");
} else {
errors.getErrors().add("Please contact your system administrator");
}
}
}
}
if (errors.getErrors().size() > 0) {
response.setStatus(500);
response.getWriter().print(gson.toJson(errors).trim());
response.getWriter().flush();
}
}
}
use of com.tremolosecurity.proxy.auth.AuthInfo in project OpenUnison by TremoloSecurity.
the class OAuth2BearerLastMile method processToken.
@Override
public void processToken(HttpServletRequest request, HttpServletResponse response, AuthStep as, HttpSession session, HashMap<String, Attribute> authParams, AuthChainType act, String realmName, String scope, ConfigManager cfg, String lmToken) throws ServletException, IOException {
Attribute attr = authParams.get("lookupByAttribute");
boolean lookupByAttribute = false;
if (attr != null) {
lookupByAttribute = attr.getValues().get(0).equalsIgnoreCase("true");
}
String lookupAttrName = "";
if (lookupByAttribute) {
lookupAttrName = authParams.get("lookupAttributeName").getValues().get(0);
}
boolean useURIforLastMile = false;
attr = authParams.get("useURIForLastMile");
if (attr != null) {
useURIforLastMile = attr.getValues().get(0).equalsIgnoreCase("true");
}
String encKeyAlias = authParams.get("encKeyAlias").getValues().get(0);
SecretKey key = cfg.getSecretKey(encKeyAlias);
com.tremolosecurity.lastmile.LastMile lmresp = new com.tremolosecurity.lastmile.LastMile();
try {
lmresp.loadLastMielToken(lmToken, key);
StringBuffer uri = new StringBuffer();
if (useURIforLastMile) {
uri.append(request.getRequestURI());
} else {
uri.append('/').append(realmName);
if (scope != null) {
uri.append('/').append(scope);
}
}
if (!lmresp.isValid(uri.toString())) {
as.setExecuted(true);
as.setSuccess(false);
cfg.getAuthManager().nextAuth(request, response, request.getSession(), false);
sendFail(response, realmName, scope, "invalid_token", "the token is invalid");
return;
}
} catch (Exception e) {
throw new ServletException("Invalid token");
}
String dn = lmresp.getAttributes().get(0).getValues().get(0);
try {
LDAPSearchResults res;
if (lookupByAttribute) {
res = cfg.getMyVD().search(act.getRoot(), 2, equal(lookupAttrName, dn).toString(), new ArrayList<String>());
} else {
res = cfg.getMyVD().search(dn, 0, "(objectClass=*)", new ArrayList<String>());
}
if (res.hasMore()) {
LDAPEntry entry = res.next();
Iterator<LDAPAttribute> it = entry.getAttributeSet().iterator();
AuthInfo authInfo = new AuthInfo(entry.getDN(), (String) session.getAttribute(ProxyConstants.AUTH_MECH_NAME), act.getName(), act.getLevel());
AuthController actl = (AuthController) session.getAttribute(ProxyConstants.AUTH_CTL);
if (actl == null) {
actl = new AuthController();
session.setAttribute(ProxyConstants.AUTH_CTL, actl);
}
actl.setAuthInfo(authInfo);
while (it.hasNext()) {
LDAPAttribute attrib = it.next();
attr = new Attribute(attrib.getName());
String[] vals = attrib.getStringValueArray();
for (int i = 0; i < vals.length; i++) {
attr.getValues().add(vals[i]);
}
authInfo.getAttribs().put(attr.getName(), attr);
}
as.setExecuted(true);
as.setSuccess(true);
cfg.getAuthManager().nextAuth(request, response, request.getSession(), false);
} else {
as.setExecuted(true);
as.setSuccess(false);
cfg.getAuthManager().nextAuth(request, response, request.getSession(), false);
sendFail(response, realmName, scope, null, null);
}
} catch (LDAPException e) {
throw new ServletException("Error loading user", e);
}
}
use of com.tremolosecurity.proxy.auth.AuthInfo in project OpenUnison by TremoloSecurity.
the class OAuth2JWT method lookupUser.
public static void lookupUser(AuthStep as, HttpSession session, MyVDConnection myvd, String noMatchOU, String uidAttr, String lookupFilter, AuthChainType act, Map jwtNVP, String defaultObjectClass) {
boolean uidIsFilter = !lookupFilter.isEmpty();
String filter = "";
if (uidIsFilter) {
StringBuffer b = new StringBuffer();
int lastIndex = 0;
int index = lookupFilter.indexOf('$');
while (index >= 0) {
b.append(lookupFilter.substring(lastIndex, index));
lastIndex = lookupFilter.indexOf('}', index) + 1;
String reqName = lookupFilter.substring(index + 2, lastIndex - 1);
b.append(jwtNVP.get(reqName).toString());
index = lookupFilter.indexOf('$', index + 1);
}
b.append(lookupFilter.substring(lastIndex));
filter = b.toString();
if (logger.isDebugEnabled()) {
logger.debug("Filter : '" + filter + "'");
}
} else {
StringBuffer b = new StringBuffer();
String userParam = (String) jwtNVP.get(uidAttr);
b.append('(').append(uidAttr).append('=').append(userParam).append(')');
if (userParam == null) {
filter = "(!(objectClass=*))";
} else {
filter = equal(uidAttr, userParam).toString();
}
}
try {
String root = act.getRoot();
if (root == null || root.trim().isEmpty()) {
root = GlobalEntries.getGlobalEntries().getConfigManager().getCfg().getLdapRoot();
}
LDAPSearchResults res = myvd.search(root, 2, filter, new ArrayList<String>());
if (res.hasMore()) {
LDAPEntry entry = res.next();
Iterator<LDAPAttribute> it = entry.getAttributeSet().iterator();
AuthInfo authInfo = new AuthInfo(entry.getDN(), (String) session.getAttribute(ProxyConstants.AUTH_MECH_NAME), act.getName(), act.getLevel());
((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).setAuthInfo(authInfo);
while (it.hasNext()) {
LDAPAttribute attrib = it.next();
Attribute attr = new Attribute(attrib.getName());
String[] vals = attrib.getStringValueArray();
for (int i = 0; i < vals.length; i++) {
attr.getValues().add(vals[i]);
}
authInfo.getAttribs().put(attr.getName(), attr);
}
for (Object o : jwtNVP.keySet()) {
String s = (String) o;
Object v = jwtNVP.get(s);
Attribute attr = authInfo.getAttribs().get(s);
if (attr == null) {
attr = new Attribute(s);
authInfo.getAttribs().put(attr.getName(), attr);
}
if (v instanceof String) {
String val = (String) v;
if (!attr.getValues().contains(val)) {
attr.getValues().add(val);
}
} else if (v instanceof Object[]) {
for (Object vo : ((Object[]) v)) {
String vv = (String) vo;
if (vv != null && !attr.getValues().contains(vv)) {
attr.getValues().add(vv);
}
}
}
}
as.setSuccess(true);
} else {
loadUnlinkedUser(session, noMatchOU, uidAttr, act, jwtNVP, defaultObjectClass);
as.setSuccess(true);
}
} catch (LDAPException e) {
if (e.getResultCode() != LDAPException.INVALID_CREDENTIALS) {
logger.error("Could not authenticate user", e);
}
as.setSuccess(false);
}
}
Aggregations