Search in sources :

Example 16 with AuthenticationInfo

use of org.apache.sling.auth.core.spi.AuthenticationInfo in project sling by apache.

the class XingOauthAuthenticationHandler method extractCredentials.

// we need the OAuth access token and the user from XING (/v1/users/me)
@Override
public AuthenticationInfo extractCredentials(final HttpServletRequest request, final HttpServletResponse response) {
    logger.debug("extract credentials");
    if (oAuthService == null) {
        logger.error("OAuthService is null, check configuration");
        return null;
    }
    try {
        final HttpSession httpSession = request.getSession(true);
        Token accessToken = (Token) httpSession.getAttribute(OAuthConstants.ACCESS_TOKEN);
        XingUser xingUser = (XingUser) httpSession.getAttribute(USER_SESSION_ATTRIBUTE_NAME);
        if (accessToken == null) {
            // we need the request token and verifier to get an access token
            final Token requestToken = (Token) httpSession.getAttribute(OAuthConstants.TOKEN);
            final String verifier = request.getParameter(OAuthConstants.VERIFIER);
            if (requestToken == null || verifier == null) {
                return null;
            }
            accessToken = oAuthService.getAccessToken(requestToken, new Verifier(verifier));
            logger.debug("access token: {}", accessToken);
            httpSession.setAttribute(OAuthConstants.ACCESS_TOKEN, accessToken);
        }
        if (xingUser == null) {
            xingUser = fetchUser(accessToken);
            logger.debug("xing user: {}", xingUser);
            httpSession.setAttribute(USER_SESSION_ATTRIBUTE_NAME, xingUser);
        }
        final AuthenticationInfo authenticationInfo = new AuthenticationInfo(XingOauth.AUTH_TYPE, xingUser.getId());
        authenticationInfo.put(XingOauth.AUTHENTICATION_CREDENTIALS_ACCESS_TOKEN_KEY, accessToken);
        authenticationInfo.put(XingOauth.AUTHENTICATION_CREDENTIALS_USER_KEY, xingUser);
        return authenticationInfo;
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        removeAuthFromSession(request);
        return null;
    }
}
Also used : HttpSession(javax.servlet.http.HttpSession) Token(org.scribe.model.Token) XingUser(org.apache.sling.auth.xing.api.XingUser) Verifier(org.scribe.model.Verifier) AuthenticationInfo(org.apache.sling.auth.core.spi.AuthenticationInfo) IOException(java.io.IOException)

Example 17 with AuthenticationInfo

use of org.apache.sling.auth.core.spi.AuthenticationInfo in project sling by apache.

the class SlingAuthenticator method logout.

/**
     * Logs out the user calling all applicable
     * {@link org.apache.sling.auth.core.spi.AuthenticationHandler}
     * authentication handlers.
     */
@Override
public void logout(HttpServletRequest request, HttpServletResponse response) {
    // ensure the response is not committed yet
    if (response.isCommitted()) {
        throw new IllegalStateException("Response already committed");
    }
    // make sure impersonation is dropped
    setSudoCookie(request, response, new AuthenticationInfo("dummy", request.getRemoteUser()));
    final String path = getHandlerSelectionPath(request);
    final Collection<AbstractAuthenticationHandlerHolder>[] holdersArray = this.authHandlerCache.findApplicableHolders(request);
    for (int m = 0; m < holdersArray.length; m++) {
        final Collection<AbstractAuthenticationHandlerHolder> holderSet = holdersArray[m];
        if (holderSet != null) {
            for (AbstractAuthenticationHandlerHolder holder : holderSet) {
                if (isNodeRequiresAuthHandler(path, holder.path)) {
                    log.debug("logout: dropping authentication using handler: {}", holder);
                    try {
                        holder.dropCredentials(request, response);
                    } catch (IOException ioe) {
                        log.error("logout: Failed dropping authentication through handler " + holder, ioe);
                    }
                }
            }
        }
    }
    if (httpBasicHandler != null) {
        httpBasicHandler.dropCredentials(request, response);
    }
    redirectAfterLogout(request, response);
}
Also used : Collection(java.util.Collection) IOException(java.io.IOException) AuthenticationInfo(org.apache.sling.auth.core.spi.AuthenticationInfo)

Example 18 with AuthenticationInfo

use of org.apache.sling.auth.core.spi.AuthenticationInfo in project sling by apache.

the class SlingAuthenticator method handleLoginFailure.

private boolean handleLoginFailure(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationInfo authInfo, final Exception reason) {
    String user = authInfo.getUser();
    boolean processRequest = false;
    if (reason.getClass().getName().contains("TooManySessionsException")) {
        // to many users, send a 503 Service Unavailable
        log.info("handleLoginFailure: Too many sessions for {}: {}", user, reason.getMessage());
        try {
            response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "SlingAuthenticator: Too Many Users");
        } catch (IOException ioe) {
            log.error("handleLoginFailure: Cannot send status 503 to client", ioe);
        }
    } else if (reason instanceof LoginException) {
        log.info("handleLoginFailure: Unable to authenticate {}: {}", user, reason.getMessage());
        if (isAnonAllowed(request) && !expectAuthenticationHandler(request) && !AuthUtil.isValidateRequest(request)) {
            log.debug("handleLoginFailure: LoginException on an anonymous resource, fallback to getAnonymousResolver");
            processRequest = getAnonymousResolver(request, response, new AuthenticationInfo(null));
        } else {
            // request authentication information and send 403 (Forbidden)
            // if no handler can request authentication information.
            AuthenticationHandler.FAILURE_REASON_CODES code = AuthenticationHandler.FAILURE_REASON_CODES.INVALID_LOGIN;
            String message = "User name and password do not match";
            if (reason.getCause() instanceof CredentialExpiredException) {
                // force failure attribute to be set so handlers can
                // react to this special circumstance
                Object creds = authInfo.get("user.jcr.credentials");
                if (creds instanceof SimpleCredentials && ((SimpleCredentials) creds).getAttribute("PasswordHistoryException") != null) {
                    code = AuthenticationHandler.FAILURE_REASON_CODES.PASSWORD_EXPIRED_AND_NEW_PASSWORD_IN_HISTORY;
                    message = "Password expired and new password found in password history";
                } else {
                    code = AuthenticationHandler.FAILURE_REASON_CODES.PASSWORD_EXPIRED;
                    message = "Password expired";
                }
            } else if (reason.getCause() instanceof AccountLockedException) {
                code = AuthenticationHandler.FAILURE_REASON_CODES.ACCOUNT_LOCKED;
                message = "Account is locked";
            } else if (reason.getCause() instanceof AccountNotFoundException) {
                code = AuthenticationHandler.FAILURE_REASON_CODES.ACCOUNT_NOT_FOUND;
                message = "Account was not found";
            }
            // preset a reason for the login failure
            request.setAttribute(AuthenticationHandler.FAILURE_REASON_CODE, code);
            ensureAttribute(request, AuthenticationHandler.FAILURE_REASON, message);
            doLogin(request, response);
        }
    } else {
        // general problem, send a 500 Internal Server Error
        log.error("handleLoginFailure: Unable to authenticate " + user, reason);
        try {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "SlingAuthenticator: data access error, reason=" + reason.getClass().getSimpleName());
        } catch (IOException ioe) {
            log.error("handleLoginFailure: Cannot send status 500 to client", ioe);
        }
    }
    return processRequest;
}
Also used : SimpleCredentials(javax.jcr.SimpleCredentials) AccountLockedException(javax.security.auth.login.AccountLockedException) LoginException(org.apache.sling.api.resource.LoginException) IOException(java.io.IOException) CredentialExpiredException(javax.security.auth.login.CredentialExpiredException) AccountNotFoundException(javax.security.auth.login.AccountNotFoundException) AuthenticationInfo(org.apache.sling.auth.core.spi.AuthenticationInfo)

Example 19 with AuthenticationInfo

use of org.apache.sling.auth.core.spi.AuthenticationInfo in project sling by apache.

the class SlingAuthenticator method getAnonymousCredentials.

/**
     * Returns credentials to use for anonymous resource access. If an anonymous
     * user is configued, this returns an {@link AuthenticationInfo} instance
     * whose authentication type is <code>null</code> and the user name and
     * password are set according to the {@link #PAR_ANONYMOUS_USER} and
     * {@link #PAR_ANONYMOUS_PASSWORD} configurations. Otherwise
     * the user name and password fields are just <code>null</code>.
     */
private AuthenticationInfo getAnonymousCredentials() {
    AuthenticationInfo info = new AuthenticationInfo(null);
    if (this.anonUser != null) {
        info.setUser(this.anonUser);
        info.setPassword(this.anonPassword);
    }
    return info;
}
Also used : AuthenticationInfo(org.apache.sling.auth.core.spi.AuthenticationInfo)

Example 20 with AuthenticationInfo

use of org.apache.sling.auth.core.spi.AuthenticationInfo in project sling by apache.

the class FormAuthenticationHandlerTest method testRedirectionAfterLogin.

/**
     * Test for SLING-3443 Parameter based redirection should only handle relative paths
     * @throws Exception PowerMock.expectPrivate throws Exception and UrlEncoder.encode
     *                          throws UnsupportedEncodingException
     * @since 1.0.6
     */
@Test
public void testRedirectionAfterLogin() throws Exception {
    // Create mocks
    final HttpServletRequest request = createMock(HttpServletRequest.class);
    final HttpServletResponse response = createMock(HttpServletResponse.class);
    final AuthenticationInfo authenticationInfo = createMock(AuthenticationInfo.class);
    // Use PowerMock to mock private method
    final String methodName = "refreshAuthData";
    final FormAuthenticationHandler authenticationHandler = PowerMock.createPartialMock(FormAuthenticationHandler.class, methodName);
    final Method[] methods = MemberMatcher.methods(FormAuthenticationHandler.class, methodName);
    PowerMock.expectPrivate(authenticationHandler, methods[0], request, response, authenticationInfo);
    // Mock the static method since we are just unit testing the authentication succeeded flow
    PowerMock.mockStatic(DefaultAuthenticationFeedbackHandler.class);
    expect(DefaultAuthenticationFeedbackHandler.handleRedirect(request, response)).andReturn(false);
    // Mocks the Authenticator.LOGIN_RESOURCE attribute
    final String url = "http://www.blah.com";
    expect(request.getAttribute(Authenticator.LOGIN_RESOURCE)).andReturn(url);
    // Mocks the HttpServletRequest and HttpServletResponse object
    expect(request.getMethod()).andReturn("POST");
    expect(request.getRequestURI()).andReturn("http://blah/blah/j_security_check");
    String contextPath = "/blah";
    expect(request.getContextPath()).andReturn(contextPath).anyTimes();
    expect(response.isCommitted()).andReturn(false);
    // Mocking method with void return type
    response.resetBuffer();
    expectLastCall().once();
    // The request should be redirected to the context root rather than the
    // passing the parameter directly
    response.sendRedirect(cmpEq(contextPath));
    // Replay the mocks
    replay(request);
    replay(response);
    replay(authenticationInfo);
    replay(authenticationHandler);
    // Test the method
    authenticationHandler.authenticationSucceeded(request, response, authenticationInfo);
    // Verify mocks
    verify(request, response, authenticationInfo, authenticationHandler);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) Method(java.lang.reflect.Method) AuthenticationInfo(org.apache.sling.auth.core.spi.AuthenticationInfo) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

AuthenticationInfo (org.apache.sling.auth.core.spi.AuthenticationInfo)36 Test (org.junit.Test)25 HttpServletRequest (javax.servlet.http.HttpServletRequest)8 HttpServletResponse (javax.servlet.http.HttpServletResponse)8 SimpleCredentials (javax.jcr.SimpleCredentials)4 IOException (java.io.IOException)3 Collection (java.util.Collection)2 Credentials (javax.jcr.Credentials)2 LoginException (org.apache.sling.api.resource.LoginException)2 Method (java.lang.reflect.Method)1 AccountLockedException (javax.security.auth.login.AccountLockedException)1 AccountNotFoundException (javax.security.auth.login.AccountNotFoundException)1 CredentialExpiredException (javax.security.auth.login.CredentialExpiredException)1 Cookie (javax.servlet.http.Cookie)1 HttpSession (javax.servlet.http.HttpSession)1 ResourceResolver (org.apache.sling.api.resource.ResourceResolver)1 FormCredentials (org.apache.sling.auth.form.impl.jaas.FormCredentials)1 XingUser (org.apache.sling.auth.xing.api.XingUser)1 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)1 Token (org.scribe.model.Token)1