Search in sources :

Example 6 with DisabledException

use of org.springframework.security.authentication.DisabledException in project spring-security by spring-projects.

the class GoogleAccountsAuthenticationProvider method authenticate.

public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    User googleUser = (User) authentication.getPrincipal();
    GaeUser user = userRegistry.findUser(googleUser.getUserId());
    if (user == null) {
        // User not in registry. Needs to register
        user = new GaeUser(googleUser.getUserId(), googleUser.getNickname(), googleUser.getEmail());
    }
    if (!user.isEnabled()) {
        throw new DisabledException("Account is disabled");
    }
    return new GaeUserAuthentication(user, authentication.getDetails());
}
Also used : GaeUser(samples.gae.users.GaeUser) User(com.google.appengine.api.users.User) DisabledException(org.springframework.security.authentication.DisabledException) GaeUser(samples.gae.users.GaeUser)

Example 7 with DisabledException

use of org.springframework.security.authentication.DisabledException in project spring-security by spring-projects.

the class BasicAuthenticationEntryPointTests method testNormalOperation.

@Test
public void testNormalOperation() throws Exception {
    BasicAuthenticationEntryPoint ep = new BasicAuthenticationEntryPoint();
    ep.setRealmName("hello");
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRequestURI("/some_path");
    MockHttpServletResponse response = new MockHttpServletResponse();
    // ep.afterPropertiesSet();
    String msg = "These are the jokes kid";
    ep.commence(request, response, new DisabledException(msg));
    assertThat(response.getStatus()).isEqualTo(401);
    assertThat(response.getErrorMessage()).isEqualTo(msg);
    assertThat(response.getHeader("WWW-Authenticate")).isEqualTo("Basic realm=\"hello\"");
}
Also used : MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) DisabledException(org.springframework.security.authentication.DisabledException) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.Test)

Example 8 with DisabledException

use of org.springframework.security.authentication.DisabledException in project ORCID-Source by ORCID.

the class OrcidUserDetailsService method loadUserByUsername.

/**
     * Locates the user based on the username. In the actual implementation, the
     * search may possibly be case insensitive, or case insensitive depending on
     * how the implementation instance is configured. In this case, the
     * <code>UserDetails</code> object that comes back may have a username that
     * is of a different case than what was actually requested..
     * 
     * @param username
     *            the username identifying the user whose data is required.
     * @return a fully populated user record (never <code>null</code>)
     * @throws org.springframework.security.core.userdetails.UsernameNotFoundException
     *             if the user could not be found or the user has no
     *             GrantedAuthority
     */
@Override
@Transactional(propagation = Propagation.REQUIRED)
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    LOGGER.info("About to load user by username = {}", username);
    ProfileEntity profile = obtainEntity(username);
    if (profile == null) {
        throw new UsernameNotFoundException("Bad username or password");
    }
    if (profile.getPrimaryRecord() != null) {
        throw new DeprecatedProfileException("orcid.frontend.security.deprecated_with_primary", profile.getPrimaryRecord().getId(), profile.getId());
    }
    if (profile.getDeactivationDate() != null && !securityMgr.isAdmin()) {
        throw new DisabledException("Account not active, please call helpdesk");
    }
    if (!profile.getClaimed() && !securityMgr.isAdmin()) {
        throw new UnclaimedProfileExistsException("orcid.frontend.security.unclaimed_exists");
    }
    String primaryEmail = null;
    // Clients doesnt have primary email, so, we need to cover that case.
    if (profile.getPrimaryEmail() != null)
        primaryEmail = profile.getPrimaryEmail().getId();
    OrcidProfileUserDetails userDetails = null;
    if (profile.getOrcidType() != null) {
        OrcidType orcidType = OrcidType.fromValue(profile.getOrcidType().value());
        userDetails = new OrcidProfileUserDetails(profile.getId(), primaryEmail, profile.getEncryptedPassword(), orcidType, profile.getGroupType());
    } else {
        userDetails = new OrcidProfileUserDetails(profile.getId(), primaryEmail, profile.getEncryptedPassword());
    }
    return userDetails;
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) OrcidType(org.orcid.jaxb.model.message.OrcidType) DisabledException(org.springframework.security.authentication.DisabledException) OrcidProfileUserDetails(org.orcid.core.oauth.OrcidProfileUserDetails) ProfileEntity(org.orcid.persistence.jpa.entities.ProfileEntity) Transactional(org.springframework.transaction.annotation.Transactional)

Example 9 with DisabledException

use of org.springframework.security.authentication.DisabledException in project ORCID-Source by ORCID.

the class AjaxAuthenticationFailureHandler method onAuthenticationFailure.

public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
    response.setContentType("application/json");
    PrintWriter writer = response.getWriter();
    writer.println("{");
    writer.println("\"success\": false");
    if (exception.getCause() instanceof UnclaimedProfileExistsException) {
        writer.println(",");
        writer.println("\"unclaimed\": true");
    } else if (exception.getCause() instanceof DeprecatedProfileException) {
        writer.println(",");
        writer.println("\"deprecated\": true");
        DeprecatedProfileException exc = (DeprecatedProfileException) exception.getCause();
        if (exc != null && exc.getPrimary() != null) {
            writer.println(",");
            writer.println("\"primary\":\"" + exc.getPrimary() + "\"");
        }
    } else if (exception.getCause() instanceof DisabledException) {
        writer.println(",");
        writer.println("\"disabled\": true");
    }
    writer.println("}");
}
Also used : DisabledException(org.springframework.security.authentication.DisabledException) DeprecatedProfileException(org.orcid.core.security.DeprecatedProfileException) UnclaimedProfileExistsException(org.orcid.core.security.UnclaimedProfileExistsException) PrintWriter(java.io.PrintWriter)

Example 10 with DisabledException

use of org.springframework.security.authentication.DisabledException in project midpoint by Evolveum.

the class MidpointRestAuthenticator method handleRequest.

public void handleRequest(AuthorizationPolicy policy, Message m, ContainerRequestContext requestCtx) {
    if (policy == null) {
        RestServiceUtil.createAbortMessage(requestCtx);
        return;
    }
    T authenticationContext = createAuthenticationContext(policy, requestCtx);
    if (authenticationContext == null) {
        return;
    }
    String enteredUsername = authenticationContext.getUsername();
    if (enteredUsername == null) {
        RestServiceUtil.createAbortMessage(requestCtx);
        return;
    }
    LOGGER.trace("Authenticating username '{}' to REST service", enteredUsername);
    // We need to create task before attempting authentication. Task ID is also a session ID.
    Task task = taskManager.createTaskInstance(ModelRestService.OPERATION_REST_SERVICE);
    task.setChannel(SchemaConstants.CHANNEL_REST_URI);
    ConnectionEnvironment connEnv = ConnectionEnvironment.create(SchemaConstants.CHANNEL_REST_URI);
    connEnv.setSessionIdOverride(task.getTaskIdentifier());
    UsernamePasswordAuthenticationToken token;
    try {
        token = getAuthenticationEvaluator().authenticate(connEnv, authenticationContext);
    } catch (UsernameNotFoundException | BadCredentialsException e) {
        LOGGER.trace("Exception while authenticating username '{}' to REST service: {}", enteredUsername, e.getMessage(), e);
        requestCtx.abortWith(Response.status(Status.UNAUTHORIZED).header("WWW-Authenticate", "Basic authentication failed. Cannot authenticate user.").build());
        return;
    } catch (DisabledException | LockedException | CredentialsExpiredException | AccessDeniedException | AuthenticationCredentialsNotFoundException | AuthenticationServiceException e) {
        LOGGER.trace("Exception while authenticating username '{}' to REST service: {}", enteredUsername, e.getMessage(), e);
        requestCtx.abortWith(Response.status(Status.FORBIDDEN).build());
        return;
    }
    UserType user = ((MidPointPrincipal) token.getPrincipal()).getUser();
    task.setOwner(user.asPrismObject());
    //  m.put(RestServiceUtil.MESSAGE_PROPERTY_TASK_NAME, task);
    if (!authorizeUser(user, null, enteredUsername, connEnv, requestCtx)) {
        return;
    }
    String oid = requestCtx.getHeaderString("Switch-To-Principal");
    OperationResult result = task.getResult();
    if (StringUtils.isNotBlank(oid)) {
        try {
            PrismObject<UserType> authorizedUser = model.getObject(UserType.class, oid, null, task, result);
            task.setOwner(authorizedUser);
            if (!authorizeUser(AuthorizationConstants.AUTZ_REST_PROXY_URL, user, authorizedUser, enteredUsername, connEnv, requestCtx)) {
                return;
            }
            if (!authorizeUser(authorizedUser.asObjectable(), null, authorizedUser.getName().getOrig(), connEnv, requestCtx)) {
                return;
            }
        } catch (ObjectNotFoundException | SchemaException | SecurityViolationException | CommunicationException | ConfigurationException | ExpressionEvaluationException e) {
            LOGGER.trace("Exception while authenticating user identified with '{}' to REST service: {}", oid, e.getMessage(), e);
            requestCtx.abortWith(Response.status(Status.UNAUTHORIZED).header("WWW-Authenticate", "Proxy Authentication failed. Cannot authenticate user.").build());
            return;
        }
    }
    m.put(RestServiceUtil.MESSAGE_PROPERTY_TASK_NAME, task);
    LOGGER.trace("Authorized to use REST service ({})", user);
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) Task(com.evolveum.midpoint.task.api.Task) AccessDeniedException(org.springframework.security.access.AccessDeniedException) ExpressionEvaluationException(com.evolveum.midpoint.util.exception.ExpressionEvaluationException) SecurityViolationException(com.evolveum.midpoint.util.exception.SecurityViolationException) DisabledException(org.springframework.security.authentication.DisabledException) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) ConfigurationException(com.evolveum.midpoint.util.exception.ConfigurationException) MidPointPrincipal(com.evolveum.midpoint.security.api.MidPointPrincipal) SchemaException(com.evolveum.midpoint.util.exception.SchemaException) LockedException(org.springframework.security.authentication.LockedException) AuthenticationCredentialsNotFoundException(org.springframework.security.authentication.AuthenticationCredentialsNotFoundException) CredentialsExpiredException(org.springframework.security.authentication.CredentialsExpiredException) CommunicationException(com.evolveum.midpoint.util.exception.CommunicationException) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException) ConnectionEnvironment(com.evolveum.midpoint.security.api.ConnectionEnvironment) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) UserType(com.evolveum.midpoint.xml.ns._public.common.common_3.UserType)

Aggregations

DisabledException (org.springframework.security.authentication.DisabledException)11 Test (org.junit.Test)5 AuthenticationException (org.springframework.security.core.AuthenticationException)3 UserType (com.evolveum.midpoint.xml.ns._public.common.common_3.UserType)2 UnclaimedProfileExistsException (org.orcid.core.security.UnclaimedProfileExistsException)2 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)2 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)2 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)2 Authentication (org.springframework.security.core.Authentication)2 UsernameNotFoundException (org.springframework.security.core.userdetails.UsernameNotFoundException)2 OperationResult (com.evolveum.midpoint.schema.result.OperationResult)1 ConnectionEnvironment (com.evolveum.midpoint.security.api.ConnectionEnvironment)1 MidPointPrincipal (com.evolveum.midpoint.security.api.MidPointPrincipal)1 Task (com.evolveum.midpoint.task.api.Task)1 CommunicationException (com.evolveum.midpoint.util.exception.CommunicationException)1 ConfigurationException (com.evolveum.midpoint.util.exception.ConfigurationException)1 ExpressionEvaluationException (com.evolveum.midpoint.util.exception.ExpressionEvaluationException)1 ObjectNotFoundException (com.evolveum.midpoint.util.exception.ObjectNotFoundException)1 SchemaException (com.evolveum.midpoint.util.exception.SchemaException)1 SecurityViolationException (com.evolveum.midpoint.util.exception.SecurityViolationException)1