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.launchkey.example.springmvc.LaunchKeyAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String username = authentication.getName();

    try {/*from w  ww  . j  a  v a2 s . co m*/
        this.authManager.login(username);
        Boolean authorized = null;
        while (authorized == null) {
            Thread.sleep(100L);
            authorized = this.authManager.isAuthorized();
        }
        if (authorized == null) {
            throw new InsufficientAuthenticationException(
                    "The authentication request was not responded to in sufficient time");
        } else if (!authorized) {
            throw new InsufficientAuthenticationException("The authentication request was denied");
        }
    } catch (InterruptedException e) {
        throw new AuthenticationServiceException("Sleep error");
    } catch (AuthManager.AuthException e) {
        if (e.getCause() instanceof LaunchKeyException) {
            throw new BadCredentialsException("Authentication failure", e.getCause());
        }
    }

    return new UsernamePasswordAuthenticationToken(username, authentication.getCredentials(),
            new ArrayList<GrantedAuthority>());
}

From source file:org.shredzone.cilla.ws.cxf.CillaRemoteAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (!(authentication.getPrincipal() instanceof RemoteUserDetails)) {
        throw new InsufficientAuthenticationException(
                "authentication must contain a RemoteUserDetails principal");
    }/* ww w.ja  v a 2  s . co  m*/

    try {
        RemoteUserDetails userDetails = (RemoteUserDetails) authentication.getPrincipal();

        List<GrantedAuthority> authorities = loginWs.authenticate().getRights().stream()
                .map(SimpleGrantedAuthority::new).collect(toList());

        userDetails.setAuthorities(authorities);
        userDetails.setUser(userWs.fetchByLogin(userDetails.getUsername()));

        return new UsernamePasswordAuthenticationToken(userDetails, null, authorities);
    } catch (SOAPFaultException ex) {
        throw new BadCredentialsException(ex.getMessage());
    } catch (CillaServiceException ex) {
        throw new AuthenticationServiceException("couldn't get user details", ex);
    }
}

From source file:com.daimler.spm.b2bacceleratoraddon.security.B2BAcceleratorAuthenticationProvider.java

/**
 * @see de.hybris.platform.acceleratorstorefrontcommons.security.AbstractAcceleratorAuthenticationProvider#additionalAuthenticationChecks(org.springframework.security.core.userdetails.UserDetails,
 *      org.springframework.security.authentication.AbstractAuthenticationToken)
 */// ww w .  java 2  s. com
@Override
protected void additionalAuthenticationChecks(final UserDetails details,
        final AbstractAuthenticationToken authentication) throws AuthenticationException {
    super.additionalAuthenticationChecks(details, authentication);

    final UserModel userModel = getUserService().getUserForUID(StringUtils.lowerCase(details.getUsername()));
    final UserGroupModel b2bgroup = getUserService().getUserGroupForUID(B2BConstants.B2BGROUP);
    // Check if the customer is B2B type
    if (getUserService().isMemberOfGroup(userModel, b2bgroup)) {
        if (!getB2bUserGroupProvider().isUserAuthorized(details.getUsername())) {
            throw new InsufficientAuthenticationException(
                    messages.getMessage("checkout.error.invalid.accountType", "You are not allowed to login"));
        }

        // if its a b2b user, check if it is active
        if (!getB2bUserGroupProvider().isUserEnabled(details.getUsername())) {
            throw new DisabledException("User " + details.getUsername() + " is disabled... "
                    + messages.getMessage("text.company.manage.units.disabled"));
        }
    }
}

From source file:org.ng200.openolympus.controller.user.SolutionStatusController.java

@RequestMapping(value = "/solution", method = RequestMethod.GET)
public String viewSolutionStatus(final HttpServletRequest request, final Model model,
        @RequestParam(value = "id") final Solution solution, final Principal principal) {
    if (principal == null || (!solution.getUser().getUsername().equals(principal.getName())
            && !request.isUserInRole(Role.SUPERUSER))) {
        throw new InsufficientAuthenticationException(
                "You attempted to view a solution that doesn't belong to you!");
    }/*from  w  ww.j ava  2  s .  c om*/

    this.assertSuperuserOrTaskAllowed(principal, solution.getTask());
    model.addAttribute("solution", solution);
    final List<Verdict> verdicts = this.solutionService.getVerdicts(solution);
    model.addAttribute("completeScore",
            verdicts.stream().map((x) -> x.getScore()).reduce((x, y) -> x.add(y)).orElse(BigDecimal.ZERO));
    model.addAttribute("completeMaximumScore", verdicts.stream().map((x) -> x.getMaximumScore())
            .reduce((x, y) -> x.add(y)).orElse(BigDecimal.ZERO));
    model.addAttribute("verdicts", verdicts.stream().sorted((l, r) -> Long.compare(l.getId(), r.getId()))
            .collect(Collectors.toList()));
    model.addAttribute("verdictMessageStrings", new HashMap<SolutionResult.Result, String>() {
        /**
         *
         */
        private static final long serialVersionUID = 8526897014680785208L;

        {
            this.put(SolutionResult.Result.OK, "solution.result.ok");
            this.put(SolutionResult.Result.TIME_LIMIT, "solution.result.timeLimit");
            this.put(SolutionResult.Result.MEMORY_LIMIT, "solution.result.memoryLimit");
            this.put(SolutionResult.Result.OUTPUT_LIMIT, "solution.result.outputLimit");
            this.put(SolutionResult.Result.RUNTIME_ERROR, "solution.result.runtimeError");
            this.put(SolutionResult.Result.INTERNAL_ERROR, "solution.result.internalError");
            this.put(SolutionResult.Result.SECURITY_VIOLATION, "solution.result.securityViolation");
            this.put(SolutionResult.Result.COMPILE_ERROR, "solution.result.compileError");
            this.put(SolutionResult.Result.PRESENTATION_ERROR, "solution.result.presentationError");
            this.put(SolutionResult.Result.WRONG_ANSWER, "solution.result.wrongAnswer");

        }
    });

    return "tasks/solution";
}

From source file:org.duracloud.account.security.auth.AuthProvider.java

@Override
protected void additionalAuthenticationChecks(UserDetails userDetails,
        UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
    super.additionalAuthenticationChecks(userDetails, authentication);

    DuracloudUser dcUser = (DuracloudUser) userDetails;
    String userIpLimits = dcUser.getAllowableIPAddressRange();

    // if user IP limits are set, check request IP
    if (null != userIpLimits && !userIpLimits.equals("")) {
        WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails();
        String requestIp = details.getRemoteAddress();

        String[] ipLimits = userIpLimits.split(";");
        for (String ipLimit : ipLimits) {
            if (ipInRange(requestIp, ipLimit)) {
                // User's IP is within this range, grant access
                log.debug("Allowing authentication check to continue for user " + dcUser.getUsername()
                        + " because their IP " + requestIp + " exists in a valid range " + ipLimit);
                return;
            }/*from   w  w  w  .ja  v  a2 s . co  m*/
        }

        // There are IP limits, and none of them match the user's IP, deny
        log.debug("Denying authentication request for user " + dcUser.getUsername() + " because their IP "
                + requestIp + " does not match any valid ranges " + userIpLimits);
        throw new InsufficientAuthenticationException(
                "Originating IP for authentication request" + requestIp + " is not in an accepted range.");
    } else { // No user IP limits, which means all IPs are accepted
        log.debug("Allowing authentication check to continue for user " + dcUser.getUsername()
                + " because no IP limits are defined");
        return;
    }
}

From source file:org.ng200.openolympus.controller.solution.SolutionDownloadController.java

@PreAuthorize(SecurityExpressionConstants.IS_ADMIN + SecurityExpressionConstants.OR + '('
        + SecurityExpressionConstants.IS_USER + SecurityExpressionConstants.AND
        + SecurityExpressionConstants.USER_IS_OWNER + SecurityExpressionConstants.AND
        + "@oolsec.isSolutionInCurrentContest(#solution)" + ')')
@RequestMapping(method = RequestMethod.GET)
public @ResponseBody ResponseEntity<FileSystemResource> solutionDownload(final HttpServletRequest request,
        final Model model, @RequestParam(value = "id") final Solution solution, final Principal principal) {
    if (principal == null || (!solution.getUser().getUsername().equals(principal.getName())
            && !request.isUserInRole(Role.SUPERUSER))) {
        throw new InsufficientAuthenticationException(
                "You attempted to download a solution that doesn't belong to you!");
    }/*from w  ww. j  av a  2  s.  c  om*/
    Assertions.resourceExists(solution);

    final HttpHeaders headers = new HttpHeaders();
    headers.setContentDispositionFormData("attachment",
            this.storageService.getSolutionFile(solution).getFileName().toString());
    return new ResponseEntity<FileSystemResource>(
            new FileSystemResource(this.storageService.getSolutionFile(solution).toFile()), headers,
            HttpStatus.OK);
}

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

@Transactional
public Response obtainOauth2Token(String clientId, String clientSecret, String refreshToken, String grantType,
        String code, Set<String> scopes, String state, String redirectUri, String resourceId) {

    LOGGER.info(/*from ww w  . j av a  2 s.  c o  m*/
            "OAuth2 authorization requested: clientId={}, grantType={}, refreshToken={}, code={}, scopes={}, state={}, redirectUri={}",
            new Object[] { clientId, grantType, refreshToken, code, scopes, state, redirectUri });

    Authentication client = getClientAuthentication();
    if (!client.isAuthenticated()) {
        LOGGER.info(
                "Not authenticated for OAuth2: clientId={}, grantType={}, refreshToken={}, code={}, scopes={}, state={}, redirectUri={}",
                new Object[] { clientId, grantType, refreshToken, code, scopes, state, redirectUri });
        throw new InsufficientAuthenticationException(
                localeManager.resolveMessage("apiError.client_not_authenticated.exception"));
    }

    /**
     * Patch, update any orcid-grants scope to funding scope
     * */
    for (String scope : scopes) {
        if (scope.contains("orcid-grants")) {
            String newScope = scope.replace("orcid-grants", "funding");
            LOGGER.info("Client {} provided a grants scope {} which will be updated to {}",
                    new Object[] { clientId, scope, newScope });
            scopes.remove(scope);
            scopes.add(newScope);
        }
    }

    try {
        boolean isClientCredentialsGrantType = OrcidOauth2Constants.GRANT_TYPE_CLIENT_CREDENTIALS
                .equals(grantType);
        if (scopes != null) {
            List<String> toRemove = new ArrayList<String>();
            for (String scope : scopes) {
                ScopePathType scopeType = ScopePathType.fromValue(scope);
                if (scopeType.isInternalScope()) {
                    // You should not allow any internal scope here! go away!
                    String message = localeManager.resolveMessage("apiError.9015.developerMessage",
                            new Object[] {});
                    throw new OrcidInvalidScopeException(message);
                } else if (isClientCredentialsGrantType) {
                    if (!scopeType.isClientCreditalScope())
                        toRemove.add(scope);
                } else {
                    if (scopeType.isClientCreditalScope())
                        toRemove.add(scope);
                }
            }

            for (String remove : toRemove) {
                scopes.remove(remove);
            }
        }
    } catch (IllegalArgumentException iae) {
        String message = localeManager.resolveMessage("apiError.9015.developerMessage", new Object[] {});
        throw new OrcidInvalidScopeException(message);
    }

    OAuth2AccessToken token = generateToken(client, scopes, code, redirectUri, grantType, refreshToken, state);
    return getResponse(token);
}

From source file:com.sun.identity.provider.springsecurity.OpenSSOObjectDefinitionSource.java

/**
 * @inheritDoc// www  .j ava 2  s . c  o  m
 */
public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
    FilterInvocation filterInvocation = (FilterInvocation) object;
    HttpServletRequest request = filterInvocation.getRequest();
    if (isAnonymousUrl(request)) {
        return null;
    }

    SSOToken token = OpenSSOProcessingFilter.getToken(filterInvocation.getHttpRequest());
    if (token == null) {
        throw new InsufficientAuthenticationException("SSOToken does not exist");
    }

    Set actions = new HashSet();
    actions.add(filterInvocation.getHttpRequest().getMethod());
    String fullResourceUrl = filterInvocation.getFullRequestUrl();

    try {
        PolicyEvaluator policyEvaluator = PolicyEvaluatorFactory.getInstance()
                .getPolicyEvaluator("iPlanetAMWebAgentService");
        if (debug.messageEnabled()) {
            debug.message("getPolicy for resource=" + fullResourceUrl + " actions=" + actions);
        }
        PolicyDecision policyDecision = policyEvaluator.getPolicyDecision(token, fullResourceUrl, actions,
                envParams);
        Map actionDecisions = policyDecision.getActionDecisions();
        if (debug.messageEnabled()) {
            debug.message("action decisions =" + actionDecisions);
        }

        // If OpenSSO has a NULL policy decision we return
        // and Empty list. This results in a Spring "ABSTAIN" vote
        if (actionDecisions == null || actionDecisions.isEmpty()) {
            return Collections.emptyList();
        } else {
            ActionDecision actionDecision = (ActionDecision) actionDecisions.values().iterator().next();
            List<ConfigAttribute> configAtributes = new ArrayList<ConfigAttribute>();
            for (Iterator it = actionDecision.getValues().iterator(); it.hasNext();) {
                String s = (String) it.next();
                debug.message("configAttributes.add(" + s);
                configAtributes.add(new SecurityConfig(s));
            }
            return configAtributes;
        }
    } catch (Exception e) {
        debug.error("Exception while evaling policy", e);
        throw new AccessDeniedException("Error accessing to Opensso", e);
    }
}

From source file:com.haulmont.restapi.ldap.LdapAuthController.java

@RequestMapping(value = "/v2/ldap/token", method = RequestMethod.POST)
public ResponseEntity<OAuth2AccessToken> postAccessToken(Principal principal,
        @RequestParam Map<String, String> parameters, HttpServletRequest request)
        throws HttpRequestMethodNotSupportedException {

    if (!ldapConfig.getLdapEnabled()) {
        log.debug("LDAP authentication is disabled. Property cuba.rest.ldap.enabled is false");

        throw new InvalidGrantException("LDAP is not supported");
    }//from  w ww .  j a  v a  2 s  .  c o  m

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

    String grantType = parameters.get(OAuth2Utils.GRANT_TYPE);
    if (!"password".equals(grantType)) {
        throw new InvalidGrantException("grant type not supported for ldap/token endpoint");
    }

    String username = parameters.get("username");

    if (restApiConfig.getStandardAuthenticationUsers().contains(username)) {
        log.info("User {} is not allowed to use external login in REST API", username);
        throw new BadCredentialsException("Bad credentials");
    }

    String ipAddress = request.getRemoteAddr();

    String password = parameters.get("password");

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

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