Example usage for org.springframework.security.authentication InsufficientAuthenticationException InsufficientAuthenticationException

List of usage examples for org.springframework.security.authentication InsufficientAuthenticationException InsufficientAuthenticationException

Introduction

In this page you can find the example usage for org.springframework.security.authentication InsufficientAuthenticationException InsufficientAuthenticationException.

Prototype

public InsufficientAuthenticationException(String msg) 

Source Link

Document

Constructs an InsufficientAuthenticationException with the specified message.

Usage

From source file:com.javaforge.tapestry.acegi.filter.ExceptionTranslationFilter.java

public void presentException(IRequestCycle requestCycle, Throwable exception,
        ExceptionPresenter exceptionPresenter) {
    Throwable rootCause = exception;

    while (rootCause instanceof ServletException) {
        rootCause = exception.getCause();
    }/*from   w w w  .  ja  va2 s  .  co m*/

    if (rootCause instanceof BindingException) {
        rootCause = exception.getCause();
    }

    if (rootCause instanceof ApplicationRuntimeException) {
        rootCause = exception.getCause();
    }

    try {
        if (rootCause instanceof AuthenticationException) {
            if (getLog().isDebugEnabled()) {
                getLog().debug("Authentication exception occurred; redirecting to authentication entry point",
                        rootCause);
            }

            sendStartAuthentication((AuthenticationException) rootCause);
        } else if (rootCause instanceof AccessDeniedException) {
            if (authenticationTrustResolver
                    .isAnonymous(SecurityContextHolder.getContext().getAuthentication())) {
                if (getLog().isDebugEnabled()) {
                    getLog().debug(
                            "Access is denied (user is anonymous); redirecting to authentication entry point",
                            rootCause);
                }

                sendStartAuthentication(new InsufficientAuthenticationException(
                        "Full authentication is required to access this resource"));
            } else {
                if (getLog().isDebugEnabled()) {
                    getLog().debug(
                            "Access is denied (user is not anonymous); delegating to AccessDeniedHandler",
                            exception);
                }

                accessDeniedHandler.handle(request, response, (AccessDeniedException) rootCause);
            }
        } else {
            exceptionPresenter.presentException(requestCycle, exception);
        }
    } catch (ServletException e) {
        exceptionPresenter.presentException(requestCycle, e);
    } catch (IOException e) {
        exceptionPresenter.presentException(requestCycle, e);
    }
}

From source file:py.una.pol.karaku.security.KarakuUserService.java

/**
 * Localiza al usuario basndose en el nombre del usuario.
 * //from ww w  . j av  a2  s  .  c o m
 * @param username
 *            el nombre del usuario que identifica al usuario cuyos datos se
 *            requiere.
 * @return la informacin del usuario.
 */
@Override
public UserDetails loadUserByUsername(String uid) {

    KarakuUser user = new KarakuUser();
    user.setUserName(uid);
    user.addRoles(loadAuthoritiesByDn(uid));

    String permiso = propertiesUtil.get(BASIC_PERMISSION_KEY, BASIC_PERMISSION_KEY_DEFAULT);

    boolean allow = false;
    for (GrantedAuthority o : user.getAuthorities()) {
        if (o.getAuthority().equals(permiso)) {
            allow = true;
        }
    }
    if (!allow) {
        throw new InsufficientAuthenticationException("No posee privilegios para este sistema");
    }
    return user;
}

From source file:de.theit.jenkins.crowd.CrowdAuthenticationManager.java

/**
 * {@inheritDoc}//from   ww w.j  ava 2  s.  c o m
 * 
 * @see org.springframework.security.AuthenticationManager#authenticate(org.springframework.security.Authentication)
 */
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String username = authentication.getPrincipal().toString();

    // checking whether there's already a SSO token
    if (null == authentication.getCredentials() && authentication instanceof CrowdAuthenticationToken
            && null != ((CrowdAuthenticationToken) authentication).getSSOToken()) {
        // SSO token available => user already authenticated
        if (LOG.isLoggable(Level.FINER)) {
            LOG.finer("User '" + username + "' already authenticated");
        }
        return authentication;
    }

    String password = authentication.getCredentials().toString();

    // ensure that the group is available, active and that the user
    // is a member of it
    if (!this.configuration.isGroupMember(username)) {
        throw new InsufficientAuthenticationException(
                userNotValid(username, this.configuration.allowedGroupNames));
    }

    String displayName = null;
    try {
        // authenticate user
        if (LOG.isLoggable(Level.FINE)) {
            LOG.fine("Authenticating user: " + username);
        }
        User user = this.configuration.crowdClient.authenticateUser(username, password);
        displayName = user.getDisplayName();
    } catch (UserNotFoundException ex) {
        if (LOG.isLoggable(Level.INFO)) {
            LOG.info(userNotFound(username));
        }
        throw new BadCredentialsException(userNotFound(username), ex);
    } catch (ExpiredCredentialException ex) {
        LOG.warning(expiredCredentials(username));
        throw new CredentialsExpiredException(expiredCredentials(username), ex);
    } catch (InactiveAccountException ex) {
        LOG.warning(accountExpired(username));
        throw new AccountExpiredException(accountExpired(username), ex);
    } catch (ApplicationPermissionException ex) {
        LOG.warning(applicationPermission());
        throw new AuthenticationServiceException(applicationPermission(), ex);
    } catch (InvalidAuthenticationException ex) {
        LOG.warning(invalidAuthentication());
        throw new AuthenticationServiceException(invalidAuthentication(), ex);
    } catch (OperationFailedException ex) {
        LOG.log(Level.SEVERE, operationFailed(), ex);
        throw new AuthenticationServiceException(operationFailed(), ex);
    }

    // user successfully authenticated
    // => retrieve the list of groups the user is a member of
    List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

    // add the "authenticated" authority to the list of granted
    // authorities...
    authorities.add(SecurityRealm.AUTHENTICATED_AUTHORITY);
    // ..and finally all authorities retrieved from the Crowd server
    authorities.addAll(this.configuration.getAuthoritiesForUser(username));

    // user successfully authenticated => create authentication token
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("User successfully authenticated; creating authentication token");
    }

    return new CrowdAuthenticationToken(username, password, authorities, null, displayName);
}

From source file:com.haulmont.restapi.idp.IdpAuthController.java

@PostMapping(value = "/v2/idp/token")
public ResponseEntity<OAuth2AccessToken> postAccessToken(Principal principal,
        @RequestParam Map<String, String> parameters, HttpServletRequest request)
        throws HttpRequestMethodNotSupportedException {

    if (!idpConfig.getIdpEnabled()) {
        log.debug("IDP authentication is disabled. Property cuba.rest.idp.enabled is false");

        throw new InvalidGrantException("IDP is not supported");
    }/* ww  w .j a va  2  s.  c o  m*/

    if (!(principal instanceof Authentication)) {
        throw new InsufficientAuthenticationException(
                "There is no client authentication. Try adding an appropriate authentication filter.");
    }

    // we cannot perform brute-force check here, since we don't know username

    String idpTicket = parameters.get("idp_ticket");
    String ipAddress = request.getRemoteAddr();

    OAuth2AccessTokenResult tokenResult = authenticate(idpTicket, request.getLocale(), ipAddress, parameters);

    return ResponseEntity.ok(tokenResult.getAccessToken());
}

From source file:com.exxonmobile.ace.hybris.storefront.security.AcceleratorAuthenticationProvider.java

/**
 * @see de.hybris.platform.spring.security.CoreAuthenticationProvider#additionalAuthenticationChecks(org.springframework.security.core.userdetails.UserDetails,
 *      org.springframework.security.authentication.AbstractAuthenticationToken)
 *///  w w w.  ja  v  a 2 s.  c  o m
@Override
protected void additionalAuthenticationChecks(final UserDetails details,
        final AbstractAuthenticationToken authentication) throws AuthenticationException {
    super.additionalAuthenticationChecks(details, authentication);

    // Check if user has supplied no password
    if (StringUtils.isEmpty((String) authentication.getCredentials())) {
        throw new BadCredentialsException("Login without password");
    }

    // Check if the user is in role admingroup
    if (getAdminAuthority() != null && details.getAuthorities().contains(getAdminAuthority())) {
        throw new LockedException("Login attempt as " + Constants.USER.ADMIN_USERGROUP + " is rejected");
    }

    // Check if the customer is B2B type
    if (!getB2bUserGroupProvider().isUserAuthorized(details.getUsername())) {
        throw new InsufficientAuthenticationException(
                messages.getMessage("checkout.error.invalid.accountType", "You are not allowed to login"));
    }

    if (!getB2bUserGroupProvider().isUserEnabled(details.getUsername())) {
        throw new DisabledException("User " + details.getUsername() + " is disabled... "
                + messages.getMessage("text.company.manage.units.disabled"));
    }
}

From source file:ch.astina.hesperid.web.services.springsecurity.internal.SpringSecurityExceptionTranslationFilter.java

private void handleException(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
        RuntimeException exception) throws IOException, ServletException {

    if (exception instanceof AuthenticationException) {
        if (logger.isDebugEnabled()) {
            logger.debug("Authentication exception occurred; redirecting to authentication entry point",
                    exception);//from  w  w  w  .ja v  a2 s . co  m
        }

        sendStartAuthentication(request, response, chain, (AuthenticationException) exception);
    } else if (exception instanceof AccessDeniedException) {
        if (authenticationTrustResolver.isAnonymous(SecurityContextHolder.getContext().getAuthentication())) {
            if (logger.isDebugEnabled()) {
                logger.debug("Access is denied (user is anonymous); redirecting to authentication entry point",
                        exception);
            }

            sendStartAuthentication(request, response, chain, new InsufficientAuthenticationException(
                    "Full authentication is required to access this resource"));
        } else {
            if (logger.isDebugEnabled()) {
                logger.debug("Access is denied (user is not anonymous); delegating to AccessDeniedHandler",
                        exception);
            }

            accessDeniedHandler.handle(request, response, (AccessDeniedException) exception);
        }
    }
}

From source file:org.socialsignin.springsocial.security.signin.SpringSocialSecurityAuthenticationFilter.java

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws AuthenticationException, IOException, ServletException {

    ServletWebRequest r = new ServletWebRequest(request);
    SpringSocialSecuritySignInDetails signInDetails = (SpringSocialSecuritySignInDetails) sessionStrategy
            .getAttribute(r, SpringSocialSecuritySignInService.SIGN_IN_DETAILS_SESSION_ATTRIBUTE_NAME);
    //SpringSocialSecuritySignInDetails signInDetails = (SpringSocialSecuritySignInDetails) request
    //   .getSession()
    //   .getAttribute(
    //      SpringSocialSecuritySignInService.SIGN_IN_DETAILS_SESSION_ATTRIBUTE_NAME);
    String alreadyAuthenticatedUserId = null;
    try {//ww  w  .  ja va2s . co  m
        alreadyAuthenticatedUserId = userIdSource.getUserId();
    } catch (IllegalStateException e) {
        // This indicates there is no user currently signed in which is the default for this filter
    }

    if (signInDetails != null) {
        UserDetails user = userDetailsService.loadUserByUsername(signInDetails.getUserId());
        if (removeSignInDetailsFromSessionOnSuccessfulAuthentication) {
            sessionStrategy.removeAttribute(r,
                    SpringSocialSecuritySignInService.SIGN_IN_DETAILS_SESSION_ATTRIBUTE_NAME);
            //request.getSession()
            //   .removeAttribute(
            //      SpringSocialSecuritySignInService.SIGN_IN_DETAILS_SESSION_ATTRIBUTE_NAME);
        }
        return authenticationFactory.createAuthenticationFromUserDetails(user);
    } else if (allowRepeatedAuthenticationAttempts && alreadyAuthenticatedUserId != null) {
        return SecurityContextHolder.getContext().getAuthentication();
    } else {
        throw new InsufficientAuthenticationException(
                "SpringSocialSecurity sign in details not found in session");
    }
}

From source file:com.orcid.api.common.server.delegator.impl.OrcidClientCredentialEndPointDelegatorImpl.java

protected Authentication getClientAuthentication() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null) {
        return authentication;
    } else {/*from  w  w w.  j  a  v  a  2  s .c  o  m*/
        throw new InsufficientAuthenticationException(
                localeManager.resolveMessage("apiError.client_authentication_notfound.exception"));
    }

}

From source file:org.cloudfoundry.identity.uaa.oauth.UaaAuthorizationEndpoint.java

@RequestMapping(value = "/oauth/authorize")
public ModelAndView authorize(Map<String, Object> model, @RequestParam Map<String, String> parameters,
        SessionStatus sessionStatus, Principal principal, HttpServletRequest request) {

    ClientDetails client;/*from   w  w w  .  j  a  v  a 2 s. c  o m*/
    String clientId;
    try {
        clientId = parameters.get("client_id");
        client = getClientServiceExtention().loadClientByClientId(clientId, IdentityZoneHolder.get().getId());
    } catch (NoSuchClientException x) {
        throw new InvalidClientException(x.getMessage());
    }

    // Pull out the authorization request first, using the OAuth2RequestFactory. All further logic should
    // query off of the authorization request instead of referring back to the parameters map. The contents of the
    // parameters map will be stored without change in the AuthorizationRequest object once it is created.
    AuthorizationRequest authorizationRequest;
    try {
        authorizationRequest = getOAuth2RequestFactory().createAuthorizationRequest(parameters);
    } catch (DisallowedIdpException x) {
        return switchIdp(model, client, clientId, request);
    }

    Set<String> responseTypes = authorizationRequest.getResponseTypes();
    String grantType = deriveGrantTypeFromResponseType(responseTypes);

    if (!supported_response_types.containsAll(responseTypes)) {
        throw new UnsupportedResponseTypeException("Unsupported response types: " + responseTypes);
    }

    if (authorizationRequest.getClientId() == null) {
        throw new InvalidClientException("A client id must be provided");
    }

    String resolvedRedirect = "";
    try {
        String redirectUriParameter = authorizationRequest.getRequestParameters().get(OAuth2Utils.REDIRECT_URI);
        try {
            resolvedRedirect = redirectResolver.resolveRedirect(redirectUriParameter, client);
        } catch (RedirectMismatchException rme) {
            throw new RedirectMismatchException(
                    "Invalid redirect " + redirectUriParameter + " did not match one of the registered values");
        }
        if (!StringUtils.hasText(resolvedRedirect)) {
            throw new RedirectMismatchException(
                    "A redirectUri must be either supplied or preconfigured in the ClientDetails");
        }

        boolean isAuthenticated = (principal instanceof Authentication)
                && ((Authentication) principal).isAuthenticated();

        if (!isAuthenticated) {
            throw new InsufficientAuthenticationException(
                    "User must be authenticated with Spring Security before authorization can be completed.");
        }

        if (!(responseTypes.size() > 0)) {
            return new ModelAndView(new RedirectView(
                    addQueryParameter(addQueryParameter(resolvedRedirect, "error", "invalid_request"),
                            "error_description", "Missing response_type in authorization request")));
        }

        authorizationRequest.setRedirectUri(resolvedRedirect);
        // We intentionally only validate the parameters requested by the client (ignoring any data that may have
        // been added to the request by the manager).
        oauth2RequestValidator.validateScope(authorizationRequest, client);

        // Some systems may allow for approval decisions to be remembered or approved by default. Check for
        // such logic here, and set the approved flag on the authorization request accordingly.
        authorizationRequest = userApprovalHandler.checkForPreApproval(authorizationRequest,
                (Authentication) principal);
        boolean approved = userApprovalHandler.isApproved(authorizationRequest, (Authentication) principal);
        authorizationRequest.setApproved(approved);

        // Validation is all done, so we can check for auto approval...
        if (authorizationRequest.isApproved()) {
            if (responseTypes.contains("token") || responseTypes.contains("id_token")) {
                return getImplicitGrantOrHybridResponse(authorizationRequest, (Authentication) principal,
                        grantType);
            }
            if (responseTypes.contains("code")) {
                return new ModelAndView(
                        getAuthorizationCodeResponse(authorizationRequest, (Authentication) principal));
            }
        }

        if ("none".equals(authorizationRequest.getRequestParameters().get("prompt"))) {
            return new ModelAndView(
                    new RedirectView(addFragmentComponent(resolvedRedirect, "error=interaction_required")));
        } else {
            // Place auth request into the model so that it is stored in the session
            // for approveOrDeny to use. That way we make sure that auth request comes from the session,
            // so any auth request parameters passed to approveOrDeny will be ignored and retrieved from the session.
            model.put(AUTHORIZATION_REQUEST, authorizationRequest);
            model.put("original_uri", UrlUtils.buildFullRequestUrl(request));
            model.put(ORIGINAL_AUTHORIZATION_REQUEST, unmodifiableMap(authorizationRequest));

            return getUserApprovalPageResponse(model, authorizationRequest, (Authentication) principal);
        }
    } catch (RedirectMismatchException e) {
        sessionStatus.setComplete();
        throw e;
    } catch (Exception e) {
        sessionStatus.setComplete();
        logger.debug("Unable to handle /oauth/authorize, internal error", e);
        if ("none".equals(authorizationRequest.getRequestParameters().get("prompt"))) {
            return new ModelAndView(
                    new RedirectView(addFragmentComponent(resolvedRedirect, "error=internal_server_error")));
        }

        throw e;
    }

}

From source file:org.cloudfoundry.identity.uaa.oauth.UaaAuthorizationEndpoint.java

@RequestMapping(value = "/oauth/authorize", method = RequestMethod.POST, params = OAuth2Utils.USER_OAUTH_APPROVAL)
public View approveOrDeny(@RequestParam Map<String, String> approvalParameters, Map<String, ?> model,
        SessionStatus sessionStatus, Principal principal) {

    if (!(principal instanceof Authentication)) {
        sessionStatus.setComplete();//from www  .  ja  v a 2  s . co m
        throw new InsufficientAuthenticationException(
                "User must be authenticated with Spring Security before authorizing an access token.");
    }

    AuthorizationRequest authorizationRequest = (AuthorizationRequest) model.get(AUTHORIZATION_REQUEST);

    if (authorizationRequest == null) {
        sessionStatus.setComplete();
        throw new InvalidRequestException("Cannot approve uninitialized authorization request.");
    }

    // Check to ensure the Authorization Request was not modified during the user approval step
    @SuppressWarnings("unchecked")
    Map<String, Object> originalAuthorizationRequest = (Map<String, Object>) model
            .get(ORIGINAL_AUTHORIZATION_REQUEST);
    if (isAuthorizationRequestModified(authorizationRequest, originalAuthorizationRequest)) {
        logger.warn("The requested scopes are invalid");
        throw new InvalidRequestException("Changes were detected from the original authorization request.");
    }

    for (String approvalParameter : approvalParameters.keySet()) {
        if (approvalParameter.startsWith(SCOPE_PREFIX)) {
            String scope = approvalParameters.get(approvalParameter).substring(SCOPE_PREFIX.length());
            Set<String> originalScopes = (Set<String>) originalAuthorizationRequest.get("scope");
            if (!originalScopes.contains(scope)) {
                sessionStatus.setComplete();

                logger.warn("The requested scopes are invalid");
                return new RedirectView(getUnsuccessfulRedirect(authorizationRequest, new InvalidScopeException(
                        "The requested scopes are invalid. Please use valid scope names in the request."),
                        false), false, true, false);
            }
        }
    }

    try {
        Set<String> responseTypes = authorizationRequest.getResponseTypes();
        String grantType = deriveGrantTypeFromResponseType(responseTypes);

        authorizationRequest.setApprovalParameters(approvalParameters);
        authorizationRequest = userApprovalHandler.updateAfterApproval(authorizationRequest,
                (Authentication) principal);
        boolean approved = userApprovalHandler.isApproved(authorizationRequest, (Authentication) principal);
        authorizationRequest.setApproved(approved);

        if (authorizationRequest.getRedirectUri() == null) {
            sessionStatus.setComplete();
            throw new InvalidRequestException("Cannot approve request when no redirect URI is provided.");
        }

        if (!authorizationRequest.isApproved()) {
            return new RedirectView(getUnsuccessfulRedirect(authorizationRequest,
                    new UserDeniedAuthorizationException("User denied access"),
                    responseTypes.contains("token")), false, true, false);
        }

        if (responseTypes.contains("token") || responseTypes.contains("id_token")) {
            return getImplicitGrantOrHybridResponse(authorizationRequest, (Authentication) principal, grantType)
                    .getView();
        }

        return getAuthorizationCodeResponse(authorizationRequest, (Authentication) principal);
    } finally {
        sessionStatus.setComplete();
    }

}