List of usage examples for org.springframework.security.authentication InsufficientAuthenticationException InsufficientAuthenticationException
public InsufficientAuthenticationException(String msg)
InsufficientAuthenticationException
with the specified message. From source file:com.evolveum.midpoint.security.impl.SecurityEnforcerImpl.java
/** * Spring security method. It is practically applicable only for simple cases. *///from ww w . j a v a 2 s . com @Override public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException { if (object instanceof MethodInvocation) { MethodInvocation methodInvocation = (MethodInvocation) object; // TODO } else if (object instanceof FilterInvocation) { FilterInvocation filterInvocation = (FilterInvocation) object; // TODO } else { SecurityUtil.logSecurityDeny(object, ": Unknown type of secure object"); throw new IllegalArgumentException("Unknown type of secure object"); } Object principalObject = authentication.getPrincipal(); if (!(principalObject instanceof MidPointPrincipal)) { if (authentication.getPrincipal() instanceof String && "anonymousUser".equals(principalObject)) { SecurityUtil.logSecurityDeny(object, ": Not logged in"); throw new InsufficientAuthenticationException("Not logged in."); } throw new IllegalArgumentException("Expected that spring security principal will be of type " + MidPointPrincipal.class.getName() + " but it was " + principalObject.getClass()); } Collection<String> configActions = SecurityUtil.getActions(configAttributes); for (String configAction : configActions) { boolean isAuthorized; try { isAuthorized = isAuthorized(configAction, null, null, null, null, null); } catch (SchemaException e) { throw new SystemException(e.getMessage(), e); } if (isAuthorized) { return; } } SecurityUtil.logSecurityDeny(object, ": Not authorized", null, configActions); // Sparse exception method by purpose. We do not want to expose details to attacker. // Better message is logged. throw new AccessDeniedException("Not authorized"); }
From source file:org.artifactory.webapp.servlet.AccessFilter.java
@SuppressWarnings({ "ThrowableInstanceNeverThrown" }) private void useAnonymousIfPossible(HttpServletRequest request, HttpServletResponse response, FilterChain chain, SecurityContext securityContext) throws IOException, ServletException { boolean anonAccessEnabled = context.getAuthorizationService().isAnonAccessEnabled(); if (anonAccessEnabled || authInterceptors.accept(request)) { log.debug("Using anonymous"); Authentication authentication = getNonUiCachedAuthentication(request); if (authentication == null) { log.debug("Creating the Anonymous token"); final UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken( UserInfo.ANONYMOUS, ""); AuthenticationDetailsSource ads = new HttpAuthenticationDetailsSource(); //noinspection unchecked authRequest.setDetails(ads.buildDetails(request)); // explicitly ask for the default spring authentication manager by name (we have another one which // is only used by the basic authentication filter) AuthenticationManager authenticationManager = context.beanForType("authenticationManager", AuthenticationManager.class); authentication = authenticationManager.authenticate(authRequest); if (authentication != null && authentication.isAuthenticated() && !RequestUtils.isUiRequest(request)) { AuthCacheKey authCacheKey = new AuthCacheKey(authFilter.getCacheKey(request), request.getRemoteAddr()); nonUiAuthCache.put(authCacheKey, authentication); log.debug("Added anonymous authentication {} to cache", authentication); }//from w w w. j ava 2 s.c o m } else { log.debug("Using cached anonymous authentication"); } useAuthentication(request, response, chain, authentication, securityContext); } else { if (authFilter.acceptEntry(request)) { log.debug("Sending request requiring authentication"); authFilter.commence(request, response, new InsufficientAuthenticationException("Authentication is required")); } else { log.debug("No filter or entry just chain"); chain.doFilter(request, response); } } }
From source file:org.cloudfoundry.identity.uaa.oauth.AccessController.java
@RequestMapping("/oauth/confirm_access") public String confirm(Map<String, Object> model, final HttpServletRequest request, Principal principal, SessionStatus sessionStatus) throws Exception { if (!(principal instanceof Authentication)) { sessionStatus.setComplete();//w w w . j av a2 s .co m throw new InsufficientAuthenticationException( "User must be authenticated with before authorizing access."); } AuthorizationRequest clientAuthRequest = (AuthorizationRequest) model.remove("authorizationRequest"); if (clientAuthRequest == null) { model.put("error", "No authorization request is present, so we cannot confirm access (we don't know what you are asking for)."); // response.sendError(HttpServletResponse.SC_BAD_REQUEST); } else { String clientId = clientAuthRequest.getClientId(); BaseClientDetails client = (BaseClientDetails) clientDetailsService.loadClientByClientId(clientId); // TODO: Need to fix the copy constructor to copy additionalInfo BaseClientDetails modifiableClient = new BaseClientDetails(client); modifiableClient.setClientSecret(null); model.put("auth_request", clientAuthRequest); model.put("redirect_uri", getRedirectUri(modifiableClient, clientAuthRequest)); Map<String, Object> additionalInfo = client.getAdditionalInformation(); String clientDisplayName = (String) additionalInfo.get(ClientConstants.CLIENT_NAME); model.put("client_display_name", (clientDisplayName != null) ? clientDisplayName : clientId); // Find the auto approved scopes for this clients Set<String> autoApproved = client.getAutoApproveScopes(); Set<String> autoApprovedScopes = new HashSet<>(); if (autoApproved != null) { if (autoApproved.contains("true")) { autoApprovedScopes.addAll(client.getScope()); } else { autoApprovedScopes.addAll(autoApproved); } } List<Approval> filteredApprovals = new ArrayList<Approval>(); // Remove auto approved scopes List<Approval> approvals = approvalStore.getApprovals(Origin.getUserId((Authentication) principal), clientId); for (Approval approval : approvals) { if (!(autoApprovedScopes.contains(approval.getScope()))) { filteredApprovals.add(approval); } } ArrayList<String> approvedScopes = new ArrayList<String>(); ArrayList<String> deniedScopes = new ArrayList<String>(); for (Approval approval : filteredApprovals) { switch (approval.getStatus()) { case APPROVED: approvedScopes.add(approval.getScope()); break; case DENIED: deniedScopes.add(approval.getScope()); break; default: logger.error("Encountered an unknown scope. This is not supposed to happen"); break; } } ArrayList<String> undecidedScopes = new ArrayList<String>(); // Filter the scopes approved/denied from the ones requested for (String scope : clientAuthRequest.getScope()) { if (!approvedScopes.contains(scope) && !deniedScopes.contains(scope) && !autoApprovedScopes.contains(scope)) { undecidedScopes.add(scope); } } List<Map<String, String>> approvedScopeDetails = getScopes(approvedScopes); model.put("approved_scopes", approvedScopeDetails); List<Map<String, String>> undecidedScopeDetails = getScopes(undecidedScopes); model.put("undecided_scopes", undecidedScopeDetails); List<Map<String, String>> deniedScopeDetails = getScopes(deniedScopes); model.put("denied_scopes", deniedScopeDetails); List<Map<String, String>> allScopes = new ArrayList<>(); allScopes.addAll(approvedScopeDetails); allScopes.addAll(undecidedScopeDetails); allScopes.addAll(deniedScopeDetails); model.put("scopes", allScopes); model.put("message", "To confirm or deny access POST to the following locations with the parameters requested."); Map<String, Object> options = new HashMap<String, Object>() { { put("confirm", new HashMap<String, String>() { { put("location", getLocation(request, "oauth/authorize")); put("path", getPath(request, "oauth/authorize")); put("key", OAuth2Utils.USER_OAUTH_APPROVAL); put("value", "true"); } }); put("deny", new HashMap<String, String>() { { put("location", getLocation(request, "oauth/authorize")); put("path", getPath(request, "oauth/authorize")); put("key", OAuth2Utils.USER_OAUTH_APPROVAL); put("value", "false"); } }); } }; model.put("options", options); } return "access_confirmation"; }
From source file:org.slc.sli.api.resources.util.ResourceUtil.java
/** * Analyzes security context to get SLIPrincipal for user. * /*from w ww . j av a2s .c o m*/ * @return SLIPrincipal from security context */ public static SLIPrincipal getSLIPrincipalFromSecurityContext() { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth instanceof AnonymousAuthenticationToken || auth.getPrincipal() instanceof String || !auth.isAuthenticated()) { throw new InsufficientAuthenticationException("Login Required"); } // lookup security/login information SLIPrincipal principal = (SLIPrincipal) auth.getPrincipal(); return principal; }
From source file:org.slc.sli.api.resources.v1.HomeResource.java
/** * Provides a set of initial information when a user logs in. This * includes a self link and links to resources with which the user * is associated.//from www. j a va 2 s .co m */ @GET public Response getHomeUri(@Context final UriInfo uriInfo) { Home home = null; // get the entity ID and EntityDefinition for user Pair<String, EntityDefinition> pair = this.getEntityInfoForUser(); if (pair != null) { String userId = pair.getLeft(); EntityDefinition defn = pair.getRight(); EntityBody body = new EntityBody(); body.put("id", userId); // prepare a list of links with the self link List<EmbeddedLink> links = ResourceUtil.getLinks(this.entityDefs, defn, body, uriInfo); // create a final map of links to relevant links HashMap<String, Object> linksMap = new HashMap<String, Object>(); linksMap.put(ResourceConstants.LINKS, links); // return as browser response home = new Home(defn.getStoredCollectionName(), linksMap); } else { throw new InsufficientAuthenticationException("No entity mapping found for user"); } return Response.ok(home).build(); }
From source file:org.springframework.security.oauth.consumer.filter.OAuthConsumerProcessingFilter.java
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; Set<String> accessTokenDeps = getAccessTokenDependencies(request, response, chain); if (!accessTokenDeps.isEmpty()) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (isRequireAuthenticated() && !authentication.isAuthenticated()) { throw new InsufficientAuthenticationException("An authenticated principal must be present."); }/* ww w. j ava 2s . com*/ OAuthSecurityContext context = OAuthSecurityContextHolder.getContext(); if (context == null) { throw new IllegalStateException( "No OAuth security context has been established. Unable to access resources."); } Map<String, OAuthConsumerToken> accessTokens = context.getAccessTokens(); for (String dependency : accessTokenDeps) { if (!accessTokens.containsKey(dependency)) { throw new AccessTokenRequiredException( getProtectedResourceDetailsService().loadProtectedResourceDetailsById(dependency)); } } chain.doFilter(request, response); } else { if (LOG.isDebugEnabled()) { LOG.debug("No access token dependencies for request."); } chain.doFilter(servletRequest, servletResponse); } }
From source file:org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint.java
@RequestMapping(value = "/oauth/authorize") public ModelAndView authorize(Map<String, Object> model, @RequestParam Map<String, String> parameters, SessionStatus sessionStatus, Principal principal) { logger.info("paramters:" + parameters.toString()); logger.info("model:" + model.toString()); // 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 = getOAuth2RequestFactory() .createAuthorizationRequest(parameters); Set<String> responseTypes = authorizationRequest.getResponseTypes(); if (!responseTypes.contains("token") && !responseTypes.contains("code")) { throw new UnsupportedResponseTypeException("Unsupported response types: " + responseTypes); }/* w w w .j a v a 2s . co m*/ if (authorizationRequest.getClientId() == null) { throw new InvalidClientException("A client id must be provided"); } try { if (!(principal instanceof Authentication) || !((Authentication) principal).isAuthenticated()) { throw new InsufficientAuthenticationException( "User must be authenticated with Spring Security before authorization can be completed."); } ClientDetails client = getClientDetailsService() .loadClientByClientId(authorizationRequest.getClientId()); // The resolved redirect URI is either the redirect_uri from the parameters or the one from // clientDetails. Either way we need to store it on the AuthorizationRequest. String redirectUriParameter = authorizationRequest.getRequestParameters().get(OAuth2Utils.REDIRECT_URI); String resolvedRedirect = redirectResolver.resolveRedirect(redirectUriParameter, client); if (!StringUtils.hasText(resolvedRedirect)) { throw new RedirectMismatchException( "A redirectUri must be either supplied or preconfigured in the ClientDetails"); } 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); // TODO: is this call necessary? 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")) { return getImplicitGrantResponse(authorizationRequest); } if (responseTypes.contains("code")) { return new ModelAndView( getAuthorizationCodeResponse(authorizationRequest, (Authentication) principal)); } } // 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("authorizationRequest", authorizationRequest); return getUserApprovalPageResponse(model, authorizationRequest, (Authentication) principal); } catch (RuntimeException e) { sessionStatus.setComplete(); throw e; } }
From source file:org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint.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) { logger.info("paramters2:" + approvalParameters.toString()); logger.info("model:" + model.toString()); logger.info("PID:" + approvalParameters.get("PID")); String PID = (String) approvalParameters.get("PID"); httpSession.setAttribute("PID", PID); logger.info("session PID:" + httpSession.getAttribute("PID")); if (!(principal instanceof Authentication)) { sessionStatus.setComplete();// w w w .j a va2 s . co m throw new InsufficientAuthenticationException( "User must be authenticated with Spring Security before authorizing an access token."); } AuthorizationRequest authorizationRequest = (AuthorizationRequest) model.get("authorizationRequest"); if (authorizationRequest == null) { sessionStatus.setComplete(); throw new InvalidRequestException("Cannot approve uninitialized authorization request."); } try { Set<String> responseTypes = authorizationRequest.getResponseTypes(); 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")) { return getImplicitGrantResponse(authorizationRequest).getView(); } return getAuthorizationCodeResponse(authorizationRequest, (Authentication) principal); } finally { sessionStatus.setComplete(); } }
From source file:org.unitedinternet.cosmo.dav.acegisecurity.DavAccessDecisionManager.java
/** * <p>/*from ww w .j a va2 s . com*/ * </p> * * @throws InsufficientAuthenticationException * if * <code>Authentication</code> is not a * {@link UsernamePasswordAuthenticationToken} or a * {@link TicketAuthenticationToken}. */ @Override public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException { AclEvaluator evaluator = null; if (authentication instanceof UsernamePasswordAuthenticationToken) { CosmoUserDetails details = (CosmoUserDetails) authentication.getPrincipal(); evaluator = new UserAclEvaluator(details.getUser()); } else if (authentication instanceof PreAuthenticatedAuthenticationToken) { User user = userService.getUser((String) authentication.getPrincipal()); evaluator = new UserAclEvaluator(user); } else if (authentication instanceof TicketAuthenticationToken) { Ticket ticket = (Ticket) authentication.getPrincipal(); evaluator = new TicketAclEvaluator(ticket); } else { LOG.error("Unrecognized authentication token"); throw new InsufficientAuthenticationException("Unrecognized authentication token"); } HttpServletRequest request = ((FilterInvocation) object).getHttpRequest(); String path = request.getPathInfo(); if (path == null) { path = "/"; } // remove trailing slash that denotes a collection if (!path.equals("/") && path.endsWith("/")) { path = path.substring(0, path.length() - 1); } try { match(path, request.getMethod(), evaluator); } catch (AclEvaluationException e) { throw new DavAccessDeniedException(request.getRequestURI(), e.getPrivilege()); } }