org.alfresco.repo.security.authentication.AuthenticationException Java Examples

The following examples show how to use org.alfresco.repo.security.authentication.AuthenticationException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RemoteConnectorServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static JSONObject doExecuteJSONRequest(RemoteConnectorRequest request, RemoteConnectorService service) throws ParseException, IOException, AuthenticationException
{
    // Set as JSON
    request.setContentType(MimetypeMap.MIMETYPE_JSON);
    
    // Perform the request
    RemoteConnectorResponse response = service.executeRequest(request);
    
    // Parse this as JSON
    JSONParser parser = new JSONParser();
    String jsonText = response.getResponseBodyAsString();
    Object json = parser.parse(jsonText);
    
    // Check it's the right type and return
    if (json instanceof JSONObject)
    {
        return (JSONObject)json;
    }
    else
    {
        throw new ParseException(0, json);
    }
}
 
Example #2
Source File: BasicHttpAuthenticatorFactory.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Checks if a user ticket is still valid
 * 
 * @return {@link Boolean} value: <code>true</code> if the ticket is still valid, <code>false</code> if the ticket is not valid any more
 */
private boolean isTicketValid()
{
    try
    {
        authenticationService.validate(ticket);
        return true;
    }
    catch (AuthenticationException e)
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("User ticket is not valid. Passing to the Basic authentication handling. Reqeust information:\n"
                    + "    ticket: " + ticket + "\n"
                    + "    request: " + servletReq.getQueryString() + "\n"
                    + "    error: " + e, e);
        }

        return false;
    }
}
 
Example #3
Source File: AuditAppTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Perform a login attempt (to be used to create audit entries)
 */
private void login(final String username, final String password) throws Exception 
{
    // Force a failed login
    RunAsWork<Void> failureWork = new RunAsWork<Void>() 
    {
        @Override
        public Void doWork() throws Exception 
        {
            try 
            {
                authenticationService.authenticate(username, password.toCharArray());
                fail("Failed to force authentication failure");
            } 
            catch (AuthenticationException e) 
            {
                // Expected
            }
            return null;
        }
    };
    AuthenticationUtil.runAs(failureWork, AuthenticationUtil.getSystemUserName());
}
 
Example #4
Source File: RepoService.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
public NodeRef addUserDescription(final String personId, final TestNetwork network, final String personDescription)
{
	return AuthenticationUtil.runAsSystem(new RunAsWork<NodeRef>()
	{
		//@Override
		public NodeRef doWork() throws Exception
		{
			NodeRef userRef = personService.getPersonOrNull(personId);
			if (userRef == null)
			{
				throw new AuthenticationException("User name does not exist: " + personId);
			}

			ContentWriter writer = contentService.getWriter(userRef, ContentModel.PROP_PERSONDESC, true);
			writer.setMimetype(MimetypeMap.MIMETYPE_HTML);
			writer.putContent(personDescription);

			log("Updated person description " + personId + (network != null ? " in network " + network : ""));
			return userRef;
		}
	});
}
 
Example #5
Source File: AuditWebScriptTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Perform a failed login attempt
 */
private void loginWithFailure(final String username) throws Exception
{
    // Force a failed login
    RunAsWork<Void> failureWork = new RunAsWork<Void>()
    {
        @Override
        public Void doWork() throws Exception
        {
            try
            {
                authenticationService.authenticate(username, "crud".toCharArray());
                fail("Failed to force authentication failure");
            }
            catch (AuthenticationException e)
            {
                // Expected
            }
            return null;
        }
    };
    AuthenticationUtil.runAs(failureWork, AuthenticationUtil.getSystemUserName());
}
 
Example #6
Source File: MultiTAdminServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void enableTenant(String tenantDomain)
{ 
    tenantDomain = getTenantDomain(tenantDomain);
    
    if (! existsTenant(tenantDomain))
    {
        throw new AuthenticationException("Tenant does not exist: " + tenantDomain);
    }
    
    if (isEnabledTenant(tenantDomain))
    {
        logger.warn("Tenant already enabled: " + tenantDomain);
    }
    
    TenantUpdateEntity tenantUpdateEntity = tenantAdminDAO.getTenantForUpdate(tenantDomain);
    tenantUpdateEntity.setEnabled(true);
    tenantAdminDAO.updateTenant(tenantUpdateEntity);
    
    notifyAfterEnableTenant(tenantDomain);
}
 
Example #7
Source File: AlfrescoImapUserManager.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * The login method.
 * 
 */
public boolean test(String userid, String password)
{
    try
    {
        authenticationService.authenticate(userid, password.toCharArray());
        String email = null;
        if (personService.personExists(userid))
        {
            NodeRef personNodeRef = personService.getPerson(userid);
            email = (String) nodeService.getProperty(personNodeRef, ContentModel.PROP_EMAIL);
        }
        GreenMailUser user = new AlfrescoImapUser(email, userid, password);
        addUser(user);
    }
    catch (AuthenticationException ex)
    {
        logger.error("IMAP authentication failed for userid: " + userid);
        return false;
    }
    return true;
}
 
Example #8
Source File: AuthenticationsImpl.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public LoginTicketResponse createTicket(LoginTicket loginRequest, Parameters parameters)
{
    validateLoginRequest(loginRequest);
    try
    {
        // get ticket
        authenticationService.authenticate(loginRequest.getUserId(), loginRequest.getPassword().toCharArray());

        LoginTicketResponse response = new LoginTicketResponse();
        response.setUserId(loginRequest.getUserId());
        response.setId(authenticationService.getCurrentTicket());

        return response;
    }
    catch (AuthenticationException e)
    {
        throw new PermissionDeniedException("Login failed");
    }
    finally
    {
        AuthenticationUtil.clearCurrentSecurityContext();
    }
}
 
Example #9
Source File: MultiTAdminServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void disableTenant(String tenantDomain)
{ 
    tenantDomain = getTenantDomain(tenantDomain);
    
    if (! existsTenant(tenantDomain))
    {
        throw new AuthenticationException("Tenant does not exist: " + tenantDomain);
    }
    
    if (! isEnabledTenant(tenantDomain))
    {
        logger.warn("Tenant already disabled: " + tenantDomain);
    }
    
    notifyBeforeDisableTenant(tenantDomain);
    
    // update tenant attributes / tenant cache - need to disable after notifying listeners (else they cannot disable) 
    TenantUpdateEntity tenantUpdateEntity = tenantAdminDAO.getTenantForUpdate(tenantDomain);
    tenantUpdateEntity.setEnabled(false);
    tenantAdminDAO.updateTenant(tenantUpdateEntity);
}
 
Example #10
Source File: IdentityServiceAuthenticationComponentTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test (expected=AuthenticationException.class)
public void testAuthenticationFail()
{
    when(mockAuthzClient.obtainAccessToken("username", "password"))
            .thenThrow(new HttpResponseException("Unauthorized", 401, "Unauthorized", null));

    authComponent.authenticateImpl("username", "password".toCharArray());
}
 
Example #11
Source File: IdentityServiceAuthenticationComponent.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void authenticateImpl(String userName, char[] password) throws AuthenticationException
{

    if (authzClient == null)
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("AuthzClient was not set, possibly due to the 'identity-service.authentication.enable-username-password-authentication=false' property. ");
        }

        throw new AuthenticationException("User not authenticated because AuthzClient was not set.");
    }

    try
    {
        // Attempt to get an access token using the user credentials
        authzClient.obtainAccessToken(userName, new String(password));

        // Successfully obtained access token so treat as authenticated user
        setCurrentUser(userName);
    }
    catch (HttpResponseException e)
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("Failed to authenticate user against Keycloak. Status: " + e.getStatusCode() + " Reason: "+ e.getReasonPhrase());
        }

        throw new AuthenticationException("Failed to authenticate user against Keycloak.", e);
    }
}
 
Example #12
Source File: AuthenticationTest.java    From alfresco-mvc with Apache License 2.0 5 votes vote down vote up
@Test
public void authentifiedAsGuest_atLeastUserAuthenticationRequired() {

	Assertions.assertThrows(AuthenticationException.class, () -> {
		service.getNamePropertyAsUser(nodeRef);
	});
}
 
Example #13
Source File: InvitationServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void invalidateTasksByUser(String userName) throws AuthenticationException
{
    List<Invitation> listForInvitee = listPendingInvitationsForInvitee(userName);
    for (Invitation inv : listForInvitee)
    {
        cancel(inv.getInviteId());
    }
}
 
Example #14
Source File: LDAPInitialDirContextFactoryImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public InitialDirContext getInitialDirContext(String principal,
        String credentials)
        throws AuthenticationException
{
    return getInitialDirContext(principal, credentials, null);
}
 
Example #15
Source File: MultiTAdminServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public Tenant getTenant(String tenantDomain)
{
    tenantDomain = getTenantDomain(tenantDomain);
    if (! existsTenant(tenantDomain))
    {
        throw new AuthenticationException("Tenant does not exist: " + tenantDomain);
    }
    
    return getTenantAttributes(tenantDomain);
}
 
Example #16
Source File: ReauthenticatingAdvice.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public Object invoke(MethodInvocation mi) throws Throwable 
{
    while (true)
    {
        try
        {
            MethodInvocation clone = ((ReflectiveMethodInvocation)mi).invocableClone();
            return clone.proceed();
        }
        catch (AuthenticationException ae)
        {
            // Sleep for an interval and try again.
            try
            {
                Thread.sleep(fRetryInterval);
            }
            catch (InterruptedException ie)
            {
                // Do nothing.
            }
            try
            {
                // Reauthenticate.
                fAuthService.authenticate(fUser, fPassword.toCharArray());
                String ticket = fAuthService.getCurrentTicket();
                fTicketHolder.setTicket(ticket);
                // Modify the ticket argument.
                mi.getArguments()[0] = ticket;
            }
            catch (Exception e)
            {
                // Do nothing.
            }
        }
    }
}
 
Example #17
Source File: RemoteAlfrescoTicketServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Returns the current Alfresco Ticket for the current user on
 *  the remote system, fetching if it isn't already cached.
 */
public RemoteAlfrescoTicketInfo getAlfrescoTicket(String remoteSystemId)
   throws AuthenticationException, NoCredentialsFoundException, NoSuchSystemException, RemoteSystemUnavailableException
{
    // Check we know about the system
    ensureRemoteSystemKnown(remoteSystemId);
    
    // Grab the user's details
    BaseCredentialsInfo creds = getRemoteCredentials(remoteSystemId);
    PasswordCredentialsInfo credentials = ensureCredentialsFound(remoteSystemId, creds);
    
    // Is there a cached ticket?
    String cacheKey = toCacheKey(remoteSystemId, credentials);
    String ticket = ticketsCache.get(cacheKey);
    
    // Refresh if if isn't cached
    if (ticket == null)
    {
        return refreshTicket(remoteSystemId, credentials);
    }
    else
    {
        if (logger.isDebugEnabled())
            logger.debug("Cached ticket found for " + creds.getRemoteUsername() + " on " + remoteSystemId);
            
        // Wrap and return
        return new AlfTicketRemoteAlfrescoTicketImpl(ticket);
    }
}
 
Example #18
Source File: RemoteAlfrescoTicketServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Forces a re-fetch of the Alfresco Ticket for the current user,
 *  if possible, and marks the credentials as failing if not. 
 */
public RemoteAlfrescoTicketInfo refetchAlfrescoTicket(String remoteSystemId)
   throws AuthenticationException, NoCredentialsFoundException, NoSuchSystemException, RemoteSystemUnavailableException
{
    // Check we know about the system
    ensureRemoteSystemKnown(remoteSystemId);
    
    // Grab the user's details
    BaseCredentialsInfo creds = getRemoteCredentials(remoteSystemId);
    PasswordCredentialsInfo credentials = ensureCredentialsFound(remoteSystemId, creds);
    
    // Trigger the refresh
    return refreshTicket(remoteSystemId, credentials);
}
 
Example #19
Source File: AuthenticationsImpl.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void deleteTicket(String me, Parameters parameters, WithResponse withResponse)
{
    if (!People.DEFAULT_USER.equals(me))
    {
        throw new InvalidArgumentException("Invalid parameter: " + me);
    }

    final String ticket = getTicket(parameters);
    try
    {
        final String ticketUser = ticketComponent.validateTicket(ticket);

        final String currentUser = AuthenticationUtil.getFullyAuthenticatedUser();
        // do not go any further if tickets are different
        // or the user is not fully authenticated
        if (currentUser == null || !currentUser.equals(ticketUser))
        {
            throw new NotFoundException(NotFoundException.DEFAULT_MESSAGE_ID, new String[] { ticket });
        }
        else
        {
            // delete the ticket
            authenticationService.invalidateTicket(ticket);
        }
    }
    catch (AuthenticationException e)
    {
        throw new NotFoundException(NotFoundException.DEFAULT_MESSAGE_ID, new String[] { ticket });
    }
}
 
Example #20
Source File: AuthenticationsImpl.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public LoginTicketResponse validateTicket(String me, Parameters parameters, WithResponse withResponse)
{
    if (!People.DEFAULT_USER.equals(me))
    {
        throw new InvalidArgumentException("Invalid parameter: " + me);
    }

    final String ticket = getTicket(parameters);
    try
    {
        final String ticketUser = ticketComponent.validateTicket(ticket);

        final String currentUser = AuthenticationUtil.getFullyAuthenticatedUser();
        // do not go any further if tickets are different
        // or the user is not fully authenticated
        if (currentUser == null || !currentUser.equals(ticketUser))
        {
            throw new NotFoundException(NotFoundException.DEFAULT_MESSAGE_ID, new String[] { ticket });
        }
    }
    catch (AuthenticationException e)
    {
        throw new NotFoundException(NotFoundException.DEFAULT_MESSAGE_ID, new String[] { ticket });
    }
    LoginTicketResponse response = new LoginTicketResponse();
    response.setId(ticket);
    return response;
}
 
Example #21
Source File: EmailServer.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * authenticate with a user/password
 * @param userName
 * @param password
 * @return true - authenticated
 */
protected boolean authenticateUserNamePassword(String userName, char[] password)
{
    try
    {
        getAuthenticationComponent().authenticate(userName, password);
        return true;
    }
    catch (AuthenticationException e)
    {
        return false;
    }
}
 
Example #22
Source File: LoginTicket.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status)
{
    // retrieve ticket from request and current ticket
    String ticket = req.getExtensionPath();
    if (ticket == null || ticket.length() == 0)
    {
        throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "Ticket not specified");
    }
    
    // construct model for ticket
    Map<String, Object> model = new HashMap<String, Object>(1, 1.0f);
    model.put("ticket",  ticket);
    
    try
    {
        String ticketUser = ticketComponent.validateTicket(ticket);
        
        String currentUser = AuthenticationUtil.getFullyAuthenticatedUser();

        // do not go any further if tickets are different 
        // or the user is not fully authenticated
        if (currentUser == null || !currentUser.equals(ticketUser))
        {
            status.setRedirect(true);
            status.setCode(HttpServletResponse.SC_NOT_FOUND);
            status.setMessage("Ticket not found");
        }
    }
    catch (AuthenticationException e)
    {
        status.setRedirect(true);
        status.setCode(HttpServletResponse.SC_NOT_FOUND);
        status.setMessage("Ticket not found");
    }
    
    return model;
}
 
Example #23
Source File: LoginTicketDelete.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status)
{
    // retrieve ticket from request and current ticket
    String ticket = req.getExtensionPath();
    if (ticket == null || ticket.length() == 0)
    {
        throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "Ticket not specified");
    }
    
    // construct model for ticket
    Map<String, Object> model = new HashMap<String, Object>(1, 1.0f);
    model.put("ticket",  ticket);
    
    try
    {
        String ticketUser = ticketComponent.validateTicket(ticket);

        // do not go any further if tickets are different
        if (!AuthenticationUtil.getFullyAuthenticatedUser().equals(ticketUser))
        {
            status.setCode(HttpServletResponse.SC_NOT_FOUND);
            status.setMessage("Ticket not found");
        }
        else
        {
            // delete the ticket
            authenticationService.invalidateTicket(ticket);
            status.setMessage("Deleted Ticket " + ticket);
        }
    }
    catch(AuthenticationException e)
    {
        status.setCode(HttpServletResponse.SC_NOT_FOUND);
        status.setMessage("Ticket not found");
    }

    status.setRedirect(true);
    return model;
}
 
Example #24
Source File: AbstractLoginBean.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected Map<String, Object> login(final String username, String password)
{
    try
    {
        // get ticket
        authenticationService.authenticate(username, password.toCharArray());

        eventPublisher.publishEvent(new EventPreparator(){
            @Override
            public Event prepareEvent(String user, String networkId, String transactionId)
            {
            	// TODO need to fix up to pass correct seqNo and alfrescoClientId
                return new RepositoryEventImpl(-1l, "login", transactionId, networkId, new Date().getTime(),
                		username, null);
            }
        });
        
        // add ticket to model for javascript and template access
        Map<String, Object> model = new HashMap<String, Object>(7, 1.0f);
        model.put("username", username);
        model.put("ticket",  authenticationService.getCurrentTicket());
        
        return model;
    }
    catch(AuthenticationException e)
    {
        throw new WebScriptException(HttpServletResponse.SC_FORBIDDEN, "Login failed");
    }
    finally
    {
        AuthenticationUtil.clearCurrentSecurityContext();
    }
}
 
Example #25
Source File: AlfrescoCmisExceptionInterceptorTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testAuthenticationException() throws Throwable
{
    Exception e = new AuthenticationException("x");
    Class<?> toCatch = CmisPermissionDeniedException.class;
    
    doMockCall(e, toCatch);
    doMockCall(new RuntimeException(new RuntimeException(e)), toCatch);
}
 
Example #26
Source File: AuthenticationTest.java    From alfresco-mvc with Apache License 2.0 5 votes vote down vote up
@Test
public void authentifiedAsUser_atLeastAdminAuthenticationRequired() {

	when(authorityService.hasGuestAuthority()).thenReturn(false);

	Assertions.assertThrows(AuthenticationException.class, () -> {
		service.getNamePropertyAsAdmin(nodeRef);
	});
}
 
Example #27
Source File: LDAPInitialDirContextFactoryImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
public InitialDirContext getDefaultIntialDirContext(int pageSize) throws AuthenticationException
{
    return getDefaultIntialDirContext(pageSize, new AuthenticationDiagnostic());
}
 
Example #28
Source File: LDAPInitialDirContextFactoryImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
public InitialDirContext getDefaultIntialDirContext() throws AuthenticationException
{
    return getDefaultIntialDirContext(0, new AuthenticationDiagnostic());
}
 
Example #29
Source File: BaseSSOAuthenticationFilter.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Check if the request has specified a ticket parameter to bypass the standard authentication.
 * 
 * @param servletContext
 *            the servlet context
 * @param req
 *            the request
 * @param resp
 *            the response
 * @return boolean
 */
protected boolean checkForTicketParameter(ServletContext servletContext, HttpServletRequest req, HttpServletResponse resp)
{
    // Check if the request includes an authentication ticket

    boolean ticketValid = false;
    String ticket = req.getParameter(ARG_TICKET);
    
    if (ticket != null && ticket.length() != 0)
    {
        if (getLogger().isTraceEnabled())
        {
            getLogger().trace(
                "Logon via ticket from " + req.getRemoteHost() + " (" + req.getRemoteAddr() + ":" + req.getRemotePort() + ")" +
                    " ticket=" + ticket);
        }
        
        UserTransaction tx = null;
        try
        {
            // Get a cached user with a valid ticket
            SessionUser user = getSessionUser(servletContext, req, resp, true);
            
            // If this isn't the same ticket, invalidate the session
            if (user != null && !ticket.equals(user.getTicket()))
            {
               if (getLogger().isDebugEnabled())
               {
                   getLogger().debug("The ticket doesn't match, invalidate the session.");
               }
               invalidateSession(req);
               user = null;
            }
            
            // If we don't yet have a valid cached user, validate the ticket and create one
            if (user == null)
            {
               if (getLogger().isDebugEnabled())
               {
                   getLogger().debug("There is no valid cached user, validate the ticket and create one.");
               }
               authenticationService.validate(ticket);
               user = createUserEnvironment(req.getSession(), authenticationService.getCurrentUserName(),
                     authenticationService.getCurrentTicket(), true);
            }
            
            // Indicate the ticket parameter was specified, and valid
            
            ticketValid = true;
        }
        catch (AuthenticationException authErr)
        {
            if (getLogger().isDebugEnabled())
            {
                getLogger().debug("Failed to authenticate user ticket: " + authErr.getMessage(), authErr);
            }
        }
        catch (Throwable e)
        {
            if (getLogger().isDebugEnabled())
            {
                getLogger().debug("Error during ticket validation and user creation: " + e.getMessage(), e);
            }
        }
        finally
        {
            try
            {
                if (tx != null)
                {
                    tx.rollback();
                }
            }
            catch (Exception tex)
            {
            }
        }
    }
    
    // Return the ticket parameter status
    
    return ticketValid;
}
 
Example #30
Source File: BaseAuthenticationFilter.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Handles the login form directly, allowing management of the session user.
 * 
 * @param req
 *            the request
 * @param res
 *            the response
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws ServletException
 *             on error
 */
protected boolean handleLoginForm(HttpServletRequest req, HttpServletResponse res) throws IOException,
        ServletException
{
    if (getLogger().isDebugEnabled())
    {
        getLogger().debug("Handling the login form.");
    }
    // Invalidate current session
    HttpSession session = req.getSession(false);
    if (session != null)
    {
        session.invalidate();
    }
    StringBuilder out = new StringBuilder(1024);
    Reader in = req.getReader();
    char[] buff = new char[1024];
    int charsRead;
    while ((charsRead = in.read(buff)) != -1)
    {
        out.append(buff, 0, charsRead);
    }
    in.close();

    try
    {
        JSONObject json = new JSONObject(out.toString());
        String username = json.getString("username");
        String password = json.getString("password");

        if (username == null || username.length() == 0)
        {
            if (getLogger().isDebugEnabled())
            {
                getLogger().debug("Username not specified in the login form.");
            }
            res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Username not specified");
            return false;
        }

        if (password == null)
        {
            if (getLogger().isDebugEnabled())
            {
                getLogger().debug("Password not specified in the login form.");
            }
            res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Password not specified");
            return false;
        }

        authenticationService.authenticate(username, password.toCharArray());
        session = req.getSession();            
        createUserEnvironment(session, username, authenticationService.getCurrentTicket(), false);
        res.setStatus(HttpServletResponse.SC_NO_CONTENT);
        return true;
    }
    catch (AuthenticationException e)
    {
        if (getLogger().isDebugEnabled())
        {
            getLogger().debug("Login failed", e);
        }
        res.sendError(HttpServletResponse.SC_FORBIDDEN, "Login failed");
    }
    catch (JSONException jErr)
    {
        if (getLogger().isDebugEnabled())
        {
            getLogger().debug("Unable to parse JSON POST body", jErr);
        }
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unable to parse JSON POST body: " + jErr.getMessage());
    }
    return false;
}