use of org.alfresco.repo.web.auth.TicketCredentials in project alfresco-remote-api by Alfresco.
the class AuthenticationFilter method doFilter.
// Various services required by NTLM authenticator
/**
* Run the authentication filter
*
* @param context ServletContext
* @param req ServletRequest
* @param resp ServletResponse
* @param chain FilterChain
* @exception ServletException
* @exception IOException
*/
@Override
public void doFilter(ServletContext context, ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
if (logger.isDebugEnabled())
logger.debug("Entering AuthenticationFilter.");
// Assume it's an HTTP request
HttpServletRequest httpReq = (HttpServletRequest) req;
HttpServletResponse httpResp = (HttpServletResponse) resp;
// Get the user details object from the session
SessionUser user = getSessionUser(context, httpReq, httpResp, false);
if (user == null) {
if (logger.isDebugEnabled())
logger.debug("There is no user in the session.");
// Get the authorization header
String authHdr = httpReq.getHeader("Authorization");
if (authHdr != null && authHdr.length() > 5 && authHdr.substring(0, 5).equalsIgnoreCase("BASIC")) {
if (logger.isDebugEnabled())
logger.debug("Basic authentication details present in the header.");
byte[] encodedString = Base64.decodeBase64(authHdr.substring(5).getBytes());
// ALF-13621: Due to browser inconsistencies we have to try a fallback path of encodings
Set<String> attemptedAuths = new HashSet<String>(ENCODINGS.length * 2);
for (String encoding : ENCODINGS) {
CharsetDecoder decoder = Charset.forName(encoding).newDecoder().onMalformedInput(CodingErrorAction.REPORT);
try {
// Attempt to decode using this charset
String basicAuth = decoder.decode(ByteBuffer.wrap(encodedString)).toString();
// It decoded OK but we may already have tried this string.
if (!attemptedAuths.add(basicAuth)) {
// Already tried - no need to try again
continue;
}
String username = null;
String password = null;
// Split the username and password
int pos = basicAuth.indexOf(":");
if (pos != -1) {
username = basicAuth.substring(0, pos);
password = basicAuth.substring(pos + 1);
} else {
username = basicAuth;
password = "";
}
// Go to the repo and authenticate
Authorization auth = new Authorization(username, password);
if (auth.isTicket()) {
authenticationService.validate(auth.getTicket());
} else {
authenticationService.authenticate(username, password.toCharArray());
if (authenticationListener != null) {
authenticationListener.userAuthenticated(new BasicAuthCredentials(username, password));
}
}
user = createUserEnvironment(httpReq.getSession(), authenticationService.getCurrentUserName(), authenticationService.getCurrentTicket(), false);
// Success so break out
break;
} catch (CharacterCodingException e) {
if (logger.isDebugEnabled())
logger.debug("Didn't decode using " + decoder.getClass().getName(), e);
} catch (AuthenticationException ex) {
if (logger.isDebugEnabled())
logger.debug("Authentication error ", ex);
} catch (NoSuchPersonException e) {
if (logger.isDebugEnabled())
logger.debug("There is no such person error ", e);
}
}
} else {
// Check if the request includes an authentication ticket
String ticket = req.getParameter(ARG_TICKET);
if (ticket != null && ticket.length() > 0) {
// PowerPoint bug fix
if (ticket.endsWith(PPT_EXTN)) {
ticket = ticket.substring(0, ticket.length() - PPT_EXTN.length());
}
if (logger.isDebugEnabled())
logger.debug("Logon via ticket from " + req.getRemoteHost() + " (" + req.getRemoteAddr() + ":" + req.getRemotePort() + ")" + " ticket=" + ticket);
// Validate the ticket
authenticationService.validate(ticket);
if (authenticationListener != null) {
authenticationListener.userAuthenticated(new TicketCredentials(ticket));
}
// Need to create the User instance if not already available
String currentUsername = authenticationService.getCurrentUserName();
user = createUserEnvironment(httpReq.getSession(), currentUsername, ticket, false);
}
}
if (user == null) {
if (logger.isDebugEnabled())
logger.debug("No user/ticket, force the client to prompt for logon details.");
httpResp.setHeader("WWW-Authenticate", "BASIC realm=\"Alfresco DAV Server\"");
httpResp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
httpResp.flushBuffer();
return;
}
} else {
if (authenticationListener != null) {
authenticationListener.userAuthenticated(new TicketCredentials(user.getTicket()));
}
}
// Chain other filters
chain.doFilter(req, resp);
}
use of org.alfresco.repo.web.auth.TicketCredentials in project alfresco-remote-api by Alfresco.
the class BaseKerberosAuthenticationFilter method authenticateRequest.
public boolean authenticateRequest(ServletContext context, HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
// Check if there is an authorization header with an SPNEGO security blob
String authHdr = req.getHeader("Authorization");
boolean reqAuth = false;
if (authHdr != null) {
if (authHdr.startsWith("Negotiate"))
reqAuth = true;
else if (authHdr.startsWith("NTLM")) {
if (getLogger().isDebugEnabled())
getLogger().debug("Received NTLM logon from client");
// Restart the authentication
restartLoginChallenge(context, req, resp);
return false;
} else if (isFallbackEnabled()) {
return performFallbackAuthentication(context, req, resp);
}
}
// Check if the user is already authenticated
SessionUser user = getSessionUser(context, req, resp, true);
HttpSession httpSess = req.getSession(true);
if (user == null) {
user = (SessionUser) httpSess.getAttribute("_alfAuthTicket");
// MNT-13191 Opening /alfresco/webdav from a Kerberos-authenticated IE11 browser causes HTTP error 500
if (user != null) {
String userName = user.getUserName();
AuthenticationUtil.setFullyAuthenticatedUser(userName);
}
}
// the next filter
if (user != null && reqAuth == false) {
// Filter validate hook
onValidate(context, req, resp, new TicketCredentials(user.getTicket()));
if (getLogger().isDebugEnabled())
getLogger().debug("Authentication not required (user), chaining ...");
return true;
}
// Check if the login page is being accessed, do not intercept the login page
if (checkLoginPage(req, resp)) {
if (getLogger().isDebugEnabled())
getLogger().debug("Login page requested, chaining ...");
return true;
}
if (authHdr == null) {
if (allowsTicketLogons()) {
if (checkForTicketParameter(context, req, resp)) {
// Filter validate hook
if (getLogger().isDebugEnabled())
getLogger().debug("Authenticated with a ticket parameter.");
if (user == null) {
user = (SessionUser) httpSess.getAttribute(getUserAttributeName());
}
onValidate(context, req, resp, new TicketCredentials(user.getTicket()));
return true;
}
}
if (getLogger().isDebugEnabled())
getLogger().debug("New Kerberos auth request from " + req.getRemoteHost() + " (" + req.getRemoteAddr() + ":" + req.getRemotePort() + ")");
// Send back a request for SPNEGO authentication
logonStartAgain(context, req, resp, true);
return false;
} else {
// Decode the received SPNEGO blob and validate
final byte[] spnegoByts = Base64.decodeBase64(authHdr.substring(10).getBytes());
if (isNTLMSSPBlob(spnegoByts, 0)) {
if (getLogger().isDebugEnabled())
getLogger().debug("Client sent an NTLMSSP security blob");
// Restart the authentication
restartLoginChallenge(context, req, resp);
return false;
}
// Check the received SPNEGO token type
int tokType = -1;
try {
tokType = SPNEGO.checkTokenType(spnegoByts, 0, spnegoByts.length);
} catch (IOException ex) {
}
if (tokType == SPNEGO.NegTokenInit) {
// Parse the SPNEGO security blob to get the Kerberos ticket
NegTokenInit negToken = new NegTokenInit();
try {
// Decode the security blob
negToken.decode(spnegoByts, 0, spnegoByts.length);
// Determine the authentication mechanism the client is using and logon
String oidStr = null;
if (negToken.numberOfOids() > 0)
oidStr = negToken.getOidAt(0).toString();
if (oidStr != null && (oidStr.equals(OID.ID_MSKERBEROS5) || oidStr.equals(OID.ID_KERBEROS5))) {
try {
NegTokenTarg negTokenTarg = doKerberosLogon(negToken, req, resp, httpSess);
if (negTokenTarg != null) {
// Allow the user to access the requested page
onValidate(context, req, resp, new KerberosCredentials(negToken, negTokenTarg));
if (getLogger().isDebugEnabled())
getLogger().debug("Authenticated through Kerberos.");
return true;
} else {
// Send back a request for SPNEGO authentication
if (getLogger().isDebugEnabled())
getLogger().debug("Failed SPNEGO authentication.");
restartLoginChallenge(context, req, resp);
return false;
}
} catch (AuthenticationException ex) {
// max user limit
if (getLogger().isDebugEnabled())
getLogger().debug("Validate failed.", ex);
onValidateFailed(context, req, resp, httpSess, new TicketCredentials(user.getTicket()));
return false;
}
} else {
if (getLogger().isDebugEnabled())
getLogger().debug("Unsupported SPNEGO mechanism " + oidStr);
// Try again!
restartLoginChallenge(context, req, resp);
}
} catch (IOException ex) {
if (getLogger().isDebugEnabled())
getLogger().debug(ex);
}
} else {
if (getLogger().isDebugEnabled())
getLogger().debug("Unknown SPNEGO token type");
// Send back a request for SPNEGO authentication
restartLoginChallenge(context, req, resp);
}
}
return false;
}
use of org.alfresco.repo.web.auth.TicketCredentials in project alfresco-remote-api by Alfresco.
the class BaseNTLMAuthenticationFilter method authenticateRequest.
public boolean authenticateRequest(ServletContext context, HttpServletRequest sreq, HttpServletResponse sresp) throws IOException, ServletException {
// Check if there is an authorization header with an NTLM security blob
String authHdr = sreq.getHeader(AUTHORIZATION);
boolean reqAuth = false;
if (authHdr != null) {
if (authHdr.startsWith(AUTH_NTLM))
reqAuth = true;
else if (authHdr.startsWith("Negotiate")) {
if (getLogger().isDebugEnabled())
getLogger().debug("Received 'Negotiate' from client, may be SPNEGO/Kerberos logon");
// Restart the authentication
restartLoginChallenge(context, sreq, sresp);
return false;
} else if (isFallbackEnabled()) {
return performFallbackAuthentication(context, sreq, sresp);
}
}
// Check if the user is already authenticated
SessionUser user = getSessionUser(context, sreq, sresp, true);
// the next filter
if (user != null && reqAuth == false) {
// Filter validate hook
onValidate(context, sreq, sresp, new TicketCredentials(user.getTicket()));
if (getLogger().isDebugEnabled())
getLogger().debug("Authentication not required (user), chaining ...");
// Chain to the next filter
return true;
}
// Check if the login page is being accessed, do not intercept the login page
if (hasLoginPage() && sreq.getRequestURI().endsWith(getLoginPage()) == true) {
if (getLogger().isDebugEnabled())
getLogger().debug("Login page requested, chaining ...");
// Chain to the next filter
return true;
}
// Check if the browser is Opera, if so then display the login page as Opera does not
// support NTLM and displays an error page if a request to use NTLM is sent to it
String userAgent = sreq.getHeader("user-agent");
if (userAgent != null && userAgent.indexOf("Opera ") != -1) {
if (getLogger().isDebugEnabled())
getLogger().debug("Opera detected, redirecting to login page");
if (hasLoginPage())
redirectToLoginPage(sreq, sresp);
else
restartLoginChallenge(context, sreq, sresp);
return false;
}
// Check the authorization header
if (authHdr == null) {
if (allowsTicketLogons()) {
if (checkForTicketParameter(context, sreq, sresp)) {
// Authentication was bypassed using a ticket parameter
return true;
}
}
if (getLogger().isDebugEnabled())
getLogger().debug("New NTLM auth request from " + sreq.getRemoteHost() + " (" + sreq.getRemoteAddr() + ":" + sreq.getRemotePort() + ") SID:" + sreq.getSession().getId());
// Send back a request for NTLM authentication
restartLoginChallenge(context, sreq, sresp);
return false;
} else {
HttpSession session = sreq.getSession();
Object sessionMutex = WebUtils.getSessionMutex(session);
// Decode the received NTLM blob and validate
final byte[] ntlmByts = Base64.decodeBase64(authHdr.substring(5).getBytes());
int ntlmTyp = NTLMMessage.isNTLMType(ntlmByts);
if (ntlmTyp == NTLM.Type1) {
// Process the type 1 NTLM message
Type1NTLMMessage type1Msg = new Type1NTLMMessage(ntlmByts);
synchronized (sessionMutex) {
processType1(type1Msg, sreq, sresp);
}
return false;
} else if (ntlmTyp == NTLM.Type3) {
// Process the type 3 NTLM message
Type3NTLMMessage type3Msg = new Type3NTLMMessage(ntlmByts);
synchronized (sessionMutex) {
return processType3(type3Msg, context, sreq, sresp);
}
} else {
if (getLogger().isDebugEnabled())
getLogger().debug("NTLM blob not handled, redirecting to login page.");
if (hasLoginPage())
redirectToLoginPage(sreq, sresp);
else
restartLoginChallenge(context, sreq, sresp);
return false;
}
}
}
use of org.alfresco.repo.web.auth.TicketCredentials in project acs-community-packaging by Alfresco.
the class BasicAuthenticationHandler method isUserAuthenticated.
/**
* Returns <code>true</code> if the user is authenticated and their details are cached in the session
*
* @param context
* the servlet context
* @param request
* the servlet request
* @return <code>true</code>, if the user is authenticated
* @throws IOException
* Signals that an I/O exception has occurred.
* @throws ServletException
* On other errors.
*/
public boolean isUserAuthenticated(ServletContext context, HttpServletRequest request) throws IOException, ServletException {
String authHdr = request.getHeader(HEADER_AUTHORIZATION);
HttpSession session = request.getSession(false);
SessionUser sessionUser = session == null ? null : (SessionUser) session.getAttribute(USER_SESSION_ATTRIBUTE);
if (sessionUser == null) {
if (remoteUserMapper != null && (!(remoteUserMapper instanceof ActivateableBean) || ((ActivateableBean) remoteUserMapper).isActive())) {
String userId = remoteUserMapper.getRemoteUser(request);
if (userId != null) {
// authenticated by other
authenticationComponent.setCurrentUser(userId);
request.getSession().setAttribute(USER_SESSION_ATTRIBUTE, new User(userId, authenticationService.getCurrentTicket(), personService.getPerson(userId)));
return true;
}
}
if (authHdr != null && authHdr.length() > 5 && authHdr.substring(0, 5).equalsIgnoreCase(BASIC_START)) {
String basicAuth = new String(Base64.decodeBase64(authHdr.substring(5).getBytes()));
String username = null;
String password = null;
int pos = basicAuth.indexOf(":");
if (pos != -1) {
username = basicAuth.substring(0, pos);
password = basicAuth.substring(pos + 1);
} else {
username = basicAuth;
password = "";
}
try {
if (logger.isDebugEnabled())
logger.debug("Authenticating user '" + username + "'");
authenticationService.authenticate(username, password.toCharArray());
// Normalize the user ID taking into account case sensitivity settings
username = authenticationService.getCurrentUserName();
if (logger.isDebugEnabled())
logger.debug("Authenticated user '" + username + "'");
authenticationListener.userAuthenticated(new BasicAuthCredentials(username, password));
request.getSession().setAttribute(USER_SESSION_ATTRIBUTE, new User(username, authenticationService.getCurrentTicket(), personService.getPerson(username)));
return true;
} catch (AuthenticationException ex) {
authenticationListener.authenticationFailed(new BasicAuthCredentials(username, password), ex);
}
}
} else {
try {
authenticationService.validate(sessionUser.getTicket());
authenticationListener.userAuthenticated(new TicketCredentials(sessionUser.getTicket()));
return true;
} catch (AuthenticationException ex) {
authenticationListener.authenticationFailed(new TicketCredentials(sessionUser.getTicket()), ex);
session.invalidate();
}
}
return false;
}
Aggregations