use of org.alfresco.repo.security.authentication.AuthenticationException in project acs-community-packaging by Alfresco.
the class AlfrescoFacesPortlet method facesRender.
/**
* @see org.apache.myfaces.portlet.MyFacesGenericPortlet#facesRender(javax.portlet.RenderRequest, javax.portlet.RenderResponse)
*/
protected void facesRender(RenderRequest request, RenderResponse response) throws PortletException, IOException {
Application.setInPortalServer(true);
try {
// Set the current locale
I18NUtil.setLocale(getLanguage(request.getPortletSession()));
if (request.getParameter(ERROR_OCCURRED) != null) {
String errorPage = getErrorPage();
if (logger.isDebugEnabled())
logger.debug("An error has occurred, redirecting to error page: " + errorPage);
response.setContentType("text/html");
PortletRequestDispatcher dispatcher = getPortletContext().getRequestDispatcher(errorPage);
dispatcher.include(request, response);
} else {
WebApplicationContext ctx = (WebApplicationContext) getPortletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
AuthenticationService auth = (AuthenticationService) ctx.getBean("AuthenticationService");
// if we have no User object in the session then an HTTP Session timeout must have occured
// use the viewId to check that we are not already on the login page
PortletSession session = request.getPortletSession();
String viewId = request.getParameter(VIEW_ID);
// keep track of last view id so we can use it as return page from multi-part requests
request.getPortletSession().setAttribute(SESSION_LAST_VIEW_ID, viewId);
SessionUser sessionUser = (SessionUser) request.getPortletSession().getAttribute(AuthenticationHelper.AUTHENTICATION_USER, PortletSession.APPLICATION_SCOPE);
User user = sessionUser instanceof User ? (User) sessionUser : null;
if (user == null && (viewId == null || viewId.equals(getLoginPage()) == false)) {
if (portalGuestAuthenticate(ctx, session, auth) != null) {
if (logger.isDebugEnabled())
logger.debug("Guest access successful.");
// perform the forward to the page processed by the Faces servlet
response.setContentType("text/html");
request.getPortletSession().setAttribute(PortletUtil.PORTLET_REQUEST_FLAG, "true");
// get the start location as configured by the web-client config
ConfigService configService = (ConfigService) ctx.getBean("webClientConfigService");
ClientConfigElement configElement = (ClientConfigElement) configService.getGlobalConfig().getConfigElement("client");
if (NavigationBean.LOCATION_MYALFRESCO.equals(configElement.getInitialLocation())) {
nonFacesRequest(request, response, "/jsp/dashboards/container.jsp");
} else {
nonFacesRequest(request, response, FacesHelper.BROWSE_VIEW_ID);
}
} else {
if (logger.isDebugEnabled())
logger.debug("No valid User login, requesting login page. ViewId: " + viewId);
// set last used username as special session value used by the LoginBean
session.setAttribute(AuthenticationHelper.SESSION_USERNAME, request.getPreferences().getValue(PREF_ALF_USERNAME, null));
// login page is the default portal page
response.setContentType("text/html");
request.getPortletSession().setAttribute(PortletUtil.PORTLET_REQUEST_FLAG, "true");
nonFacesRequest(request, response);
}
} else {
if (session.getAttribute(AuthenticationHelper.SESSION_INVALIDATED) != null) {
// remove the username preference value as explicit logout was requested by the user
if (request.getPreferences().isReadOnly(PREF_ALF_USERNAME) == false) {
request.getPreferences().reset(PREF_ALF_USERNAME);
}
session.removeAttribute(AuthenticationHelper.SESSION_INVALIDATED);
}
try {
if (user != null) {
if (logger.isDebugEnabled())
logger.debug("Validating ticket: " + user.getTicket());
// setup the authentication context
auth.validate(user.getTicket());
}
// do the normal JSF processing
super.facesRender(request, response);
} catch (AuthenticationException authErr) {
// ticket is no longer valid!
if (logger.isDebugEnabled())
logger.debug("Invalid ticket, requesting login page.");
// remove User object as it's now useless
session.removeAttribute(AuthenticationHelper.AUTHENTICATION_USER, PortletSession.APPLICATION_SCOPE);
// login page is the default portal page
response.setContentType("text/html");
request.getPortletSession().setAttribute(PortletUtil.PORTLET_REQUEST_FLAG, "true");
nonFacesRequest(request, response);
} catch (Throwable e) {
if (getErrorPage() != null) {
handleError(request, response, e);
} else {
logger.warn("No error page configured, re-throwing exception");
if (e instanceof PortletException) {
throw (PortletException) e;
} else if (e instanceof IOException) {
throw (IOException) e;
} else {
throw new PortletException(e);
}
}
}
}
}
} finally {
Application.setInPortalServer(false);
}
}
use of org.alfresco.repo.security.authentication.AuthenticationException in project acs-community-packaging by Alfresco.
the class AuthenticationHelper method getUser.
/**
* Attempts to retrieve the User object stored in the current session.
*
* @param sc
* the servlet context
* @param httpRequest
* The HTTP request
* @param httpResponse
* The HTTP response
* @return The User object representing the current user or null if it could not be found
*/
public static User getUser(final ServletContext sc, final HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
// If the remote user mapper is configured, we may be able to map in an externally authenticated user
String userId = getRemoteUser(sc, httpRequest);
final WebApplicationContext wc = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
HttpSession session = httpRequest.getSession();
User user = null;
// examine the appropriate session to try and find the User object
SessionUser sessionUser = Application.getCurrentUser(session);
// been known to leak in but shouldn't now)
if (sessionUser != null) {
if (logger.isDebugEnabled())
logger.debug("SessionUser is: " + sessionUser.getUserName());
AuthenticationService auth = (AuthenticationService) wc.getBean(AUTHENTICATION_SERVICE);
try {
auth.validate(sessionUser.getTicket());
if (sessionUser instanceof User) {
user = (User) sessionUser;
setExternalAuth(session, userId != null);
} else {
user = setUser(sc, httpRequest, sessionUser.getUserName(), sessionUser.getTicket(), userId != null);
}
} catch (AuthenticationException authErr) {
if (logger.isDebugEnabled())
logger.debug("An authentication error occured while setting the session user", authErr);
session.removeAttribute(AUTHENTICATION_USER);
if (!Application.inPortalServer()) {
if (logger.isDebugEnabled())
logger.debug("Invalidating the session.");
session.invalidate();
}
}
}
// If the remote user mapper is configured, we may be able to map in an externally authenticated user
if (userId != null) {
AuthorityService authorityService = (AuthorityService) wc.getBean(AUTHORITY_SERVICE);
// We have a previously-cached user with the wrong identity - replace them
if (user != null && !authorityService.isGuestAuthority(user.getUserName()) && !user.getUserName().equals(userId)) {
if (logger.isDebugEnabled())
logger.debug("We have a previously-cached user with the wrong identity - replace them");
session.removeAttribute(AUTHENTICATION_USER);
if (!Application.inPortalServer()) {
if (logger.isDebugEnabled())
logger.debug("Invalidating session.");
session.invalidate();
}
user = null;
}
if (user == null) {
if (logger.isDebugEnabled())
logger.debug("There are no previously-cached users.");
// If we have been authenticated by other means, just propagate through the user identity
AuthenticationComponent authenticationComponent = (AuthenticationComponent) wc.getBean(AUTHENTICATION_COMPONENT);
try {
if (logger.isDebugEnabled())
logger.debug("We have been authenticated by other means, authenticating the user: " + userId);
authenticationComponent.setCurrentUser(userId);
AuthenticationService authenticationService = (AuthenticationService) wc.getBean(AUTHENTICATION_SERVICE);
user = setUser(sc, httpRequest, userId, authenticationService.getCurrentTicket(), true);
} catch (AuthenticationException authErr) {
if (logger.isDebugEnabled())
logger.debug("An authentication error occured while setting the session user", authErr);
// Allow for an invalid external user ID to be indicated
session.removeAttribute(AUTHENTICATION_USER);
if (!Application.inPortalServer()) {
if (logger.isDebugEnabled())
logger.debug("Invalidating the session.");
session.invalidate();
}
}
}
}
return user;
}
use of org.alfresco.repo.security.authentication.AuthenticationException in project acs-community-packaging by Alfresco.
the class AuthenticationHelper method authenticate.
/**
* Helper to authenticate the current user using the supplied Ticket value.
*
* @return true if authentication successful, false otherwise.
*/
public static AuthenticationStatus authenticate(ServletContext context, HttpServletRequest httpRequest, HttpServletResponse httpResponse, String ticket) throws IOException {
if (logger.isDebugEnabled())
logger.debug("Authenticate the current user using the supplied Ticket value.");
// setup the authentication context
WebApplicationContext wc = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
AuthenticationService auth = (AuthenticationService) wc.getBean(AUTHENTICATION_SERVICE);
HttpSession session = httpRequest.getSession();
try {
// If we already have a cached user, make sure it is for the right ticket
SessionUser user = (SessionUser) session.getAttribute(AuthenticationHelper.AUTHENTICATION_USER);
if (user != null && !user.getTicket().equals(ticket)) {
if (logger.isDebugEnabled())
logger.debug("Found a previously-cached user with the wrong identity.");
session.removeAttribute(AUTHENTICATION_USER);
if (!Application.inPortalServer()) {
if (logger.isDebugEnabled())
logger.debug("The server is not running in a portal, invalidating session.");
session.invalidate();
session = httpRequest.getSession();
}
user = null;
}
// Validate the ticket and associate it with the session
auth.validate(ticket);
if (user == null) {
if (logger.isDebugEnabled())
logger.debug("Ticket is valid; caching a new user in the session.");
setUser(context, httpRequest, auth.getCurrentUserName(), ticket, false);
} else if (logger.isDebugEnabled())
logger.debug("Ticket is valid; retaining cached user in session.");
} catch (AuthenticationException authErr) {
if (logger.isDebugEnabled())
logger.debug("An AuthenticationException occured: ", authErr);
session.removeAttribute(AUTHENTICATION_USER);
if (!Application.inPortalServer()) {
if (logger.isDebugEnabled())
logger.debug("The server is not running in a portal, invalidating session.");
session.invalidate();
}
return AuthenticationStatus.Failure;
} catch (Throwable e) {
if (logger.isDebugEnabled())
logger.debug("Authentication failed due to unexpected error", e);
// Some other kind of serious failure
AuthenticationService unprotAuthService = (AuthenticationService) wc.getBean(UNPROTECTED_AUTH_SERVICE);
unprotAuthService.invalidateTicket(unprotAuthService.getCurrentTicket());
unprotAuthService.clearCurrentSecurityContext();
return AuthenticationStatus.Failure;
}
// As we are authenticating via a ticket, establish the session locale using request headers rather than web client preferences
setupThread(context, httpRequest, httpResponse, false);
return AuthenticationStatus.Success;
}
use of org.alfresco.repo.security.authentication.AuthenticationException in project acs-community-packaging by Alfresco.
the class HTTPRequestAuthenticationFilter method doFilter.
/**
* Run the filter
*
* @param sreq
* ServletRequest
* @param sresp
* ServletResponse
* @param chain
* FilterChain
* @exception IOException
* @exception ServletException
*/
public void doFilter(ServletRequest sreq, ServletResponse sresp, FilterChain chain) throws IOException, ServletException {
// Get the HTTP request/response/session
HttpServletRequest req = (HttpServletRequest) sreq;
HttpServletResponse resp = (HttpServletResponse) sresp;
// Check for the auth header
String authHdr = req.getHeader(httpServletRequestAuthHeaderName);
if (logger.isDebugEnabled()) {
if (authHdr == null) {
logger.debug("Header not found: " + httpServletRequestAuthHeaderName);
} else {
logger.debug("Header is <" + authHdr + ">");
}
}
if ((authHdr == null) || (authHdr.length() < 1)) {
resp.sendRedirect(req.getContextPath() + "/jsp/noaccess.jsp");
return;
}
// Get the user
String userName = "";
if (authPattern != null) {
Matcher matcher = authPattern.matcher(authHdr);
if (matcher.matches()) {
userName = matcher.group();
if ((userName == null) || (userName.length() < 1)) {
if (logger.isDebugEnabled()) {
logger.debug("Extracted null or empty user name from pattern " + authPatternString + " against " + authHdr);
}
resp.sendRedirect(req.getContextPath() + "/jsp/noaccess.jsp");
return;
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("no pattern match for " + authPatternString + " against " + authHdr);
}
resp.sendRedirect(req.getContextPath() + "/jsp/noaccess.jsp");
return;
}
} else {
userName = authHdr;
}
if (logger.isDebugEnabled()) {
logger.debug("User = " + userName);
}
// See if there is a user in the session and test if it matches
User user = AuthenticationHelper.getUser(this.context, req, resp);
if (user != null) {
try {
if (logger.isDebugEnabled())
logger.debug("User " + user.getUserName() + " validate ticket");
if (user.getUserName().equals(userName)) {
// Set the current locale
authComponent.clearCurrentSecurityContext();
authComponent.setCurrentUser(user.getUserName());
AuthenticationHelper.setupThread(this.context, req, resp, true);
chain.doFilter(sreq, sresp);
return;
} else {
// No match
setAuthenticatedUser(req, resp, userName);
}
} catch (AuthenticationException ex) {
if (logger.isErrorEnabled())
logger.error("Failed to validate user " + user.getUserName(), ex);
}
}
setAuthenticatedUser(req, resp, userName);
// Redirect the login page as it is never seen as we always login by name
if (req.getRequestURI().endsWith(getLoginPage()) == true) {
if (logger.isDebugEnabled())
logger.debug("Login page requested, chaining ...");
resp.sendRedirect(req.getContextPath() + BaseServlet.FACES_SERVLET + FacesHelper.BROWSE_VIEW_ID);
return;
} else {
chain.doFilter(sreq, sresp);
return;
}
}
use of org.alfresco.repo.security.authentication.AuthenticationException in project records-management by Alfresco.
the class RecordsManagementAuditServiceImplTest method xtestAuditAuthentication.
// TODO testAuditRMAction
// TODO testGetAuditTrailFile
// TODO testFileAuditTrailAsRecord
public void xtestAuditAuthentication() {
rmAuditService.stopAuditLog(filePlan);
rmAuditService.clearAuditLog(filePlan);
rmAuditService.startAuditLog(filePlan);
try {
personService.deletePerson("baboon");
authenticationService.deleteAuthentication("baboon");
} catch (Throwable e) {
// Not serious
}
// Failed login attempt ...
try {
AuthenticationUtil.pushAuthentication();
authenticationService.authenticate("baboon", "lskdfj".toCharArray());
fail("Expected authentication failure");
} catch (AuthenticationException e) {
// Good
} finally {
AuthenticationUtil.popAuthentication();
}
rmAuditService.stopAuditLog(filePlan);
List<RecordsManagementAuditEntry> result1 = getAuditTrail(ADMIN_USER);
// Check that the username is reflected correctly in the results
assertFalse("No audit results were generated for the failed login.", result1.isEmpty());
boolean found = false;
for (RecordsManagementAuditEntry entry : result1) {
String userName = entry.getUserName();
if (userName.equals("baboon")) {
found = true;
break;
}
}
assertTrue("Expected to hit failed login attempt for user", found);
// Test successful authentication
try {
personService.deletePerson("cdickons");
authenticationService.deleteAuthentication("cdickons");
} catch (Throwable e) {
// Not serious
}
authenticationService.createAuthentication("cdickons", getName().toCharArray());
Map<QName, Serializable> personProperties = new HashMap<QName, Serializable>();
personProperties.put(ContentModel.PROP_USERNAME, "cdickons");
personProperties.put(ContentModel.PROP_FIRSTNAME, "Charles");
personProperties.put(ContentModel.PROP_LASTNAME, "Dickons");
personService.createPerson(personProperties);
rmAuditService.clearAuditLog(filePlan);
rmAuditService.startAuditLog(filePlan);
try {
AuthenticationUtil.pushAuthentication();
authenticationService.authenticate("cdickons", getName().toCharArray());
} finally {
AuthenticationUtil.popAuthentication();
}
rmAuditService.stopAuditLog(filePlan);
List<RecordsManagementAuditEntry> result2 = getAuditTrail(ADMIN_USER);
found = false;
for (RecordsManagementAuditEntry entry : result2) {
String userName = entry.getUserName();
String fullName = entry.getFullName();
if (userName.equals("cdickons") && EqualsHelper.nullSafeEquals(fullName, "Charles Dickons")) {
found = true;
break;
}
}
assertTrue("Expected to hit successful login attempt for Charles Dickons (cdickons)", found);
}
Aggregations