private UaaAuthentication getAuthentication() { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth == null) { throw new InsufficientAuthenticationException("User authentication missing"); } else if (!(auth instanceof OAuth2Authentication)) { throw new InsufficientAuthenticationException("Unrecognizable authentication"); } Authentication userAuth = ((OAuth2Authentication) auth).getUserAuthentication(); if (!(userAuth instanceof UaaAuthentication)) { throw new InsufficientAuthenticationException("Unrecognizable user authentication"); } return (UaaAuthentication) userAuth; }
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { MfaProvider provider = null; try { if (isGrantTypeSupported(request.getParameter(GRANT_TYPE))) { provider = checkMfaCode(request); UaaUser user = getUaaUser(); if (provider != null) { publishEvent(new MfaAuthenticationSuccessEvent(user, getAuthentication(), provider.getType().toValue())); } } filterChain.doFilter(request, response); } catch (InsufficientAuthenticationException x) { handleException(new JsonError(400, "invalid_request", x.getMessage()), response); } catch (MissingMfaCodeException | UserMfaConfigDoesNotExistException e) { UaaUser user = getUaaUser(); publishEvent(new MfaAuthenticationFailureEvent(user, getAuthentication(), provider != null ? provider.getType().toValue() : "null")); handleException(new JsonError(400, "invalid_request", e.getMessage()), response); } catch (InvalidMfaCodeException e) { UaaUser user = getUaaUser(); publishEvent(new MfaAuthenticationFailureEvent(user, getAuthentication(), provider != null ? provider.getType().toValue() : "null")); handleException(new JsonError(401, "unauthorized", "Bad credentials"), response); } }
public static RuntimeException unauthorizedAccess(String resourceName) { // not hide, and not filtering out a list, this // is an unauthorized direct resource access, complain Authentication user = user(); if (user == null || user.getAuthorities().size() == 0) return new InsufficientAuthenticationException( "Cannot access " + resourceName + " as anonymous"); else return new AccessDeniedException( "Cannot access " + resourceName + " with the current privileges"); }
@Override protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest clientToken) { Authentication userAuth = SecurityContextHolder.getContext().getAuthentication(); if (userAuth==null || !userAuth.isAuthenticated()) { throw new InsufficientAuthenticationException("There is no currently logged in user"); } Assert.state(clientToken instanceof ImplicitTokenRequest, "An ImplicitTokenRequest is required here. Caller needs to wrap the TokenRequest."); OAuth2Request requestForStorage = ((ImplicitTokenRequest)clientToken).getOAuth2Request(); return new OAuth2Authentication(requestForStorage, userAuth); }
public static RuntimeException unauthorizedAccess() { // not hide, and not filtering out a list, this // is an unauthorized direct resource access, complain Authentication user = user(); if (user == null || user.getAuthorities().size() == 0) return new InsufficientAuthenticationException( "Operation unallowed with the current privileges"); else return new AccessDeniedException("Operation unallowed with the current privileges"); }
@Override protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest clientToken) { Authentication userAuth = SecurityContextHolder.getContext().getAuthentication(); if (userAuth==null || !userAuth.isAuthenticated()) { throw new InsufficientAuthenticationException("There is no currently logged in user"); } Assert.state(clientToken instanceof ImplicitTokenRequest, "An ImplicitTokenRequest is required here. Caller needs to wrap the TokenRequest."); OAuth2Request requestForStorage = ((ImplicitTokenRequest)clientToken).getOAuth2Request(); return new OAuth2Authentication(requestForStorage, userAuth); } }
/** * @param principal the currently authentication principal * @return a client id if there is one in the principal */ protected String getClientId(Principal principal) { Authentication client = (Authentication) principal; if (!client.isAuthenticated()) { throw new InsufficientAuthenticationException("The client is not authenticated."); } String clientId = client.getName(); if (client instanceof OAuth2Authentication) { // Might be a client and user combined authentication clientId = ((OAuth2Authentication) client).getOAuth2Request().getClientId(); } return clientId; }
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."); } 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); } }
public IdentityProvider resolveOriginProvider(String idToken) throws AuthenticationException { try { String claimsString = JwtHelper.decode(ofNullable(idToken).orElse("")).getClaims(); Map<String, Object> claims = JsonUtils.readValue(claimsString, new TypeReference<Map<String, Object>>() {}); String issuer = (String) claims.get(ClaimConstants.ISS); if (isEmpty(issuer)) { throw new InsufficientAuthenticationException("Issuer is missing in id_token"); } //1. Check if issuer is registered provider try { return ((XOAuthProviderConfigurator) getProviderProvisioning()).retrieveByIssuer(issuer, IdentityZoneHolder.get().getId()); } catch (IncorrectResultSizeDataAccessException x) { logger.debug("No registered identity provider found for given issuer. Checking for uaa."); } //2. If not, check if issuer is self if (idTokenWasIssuedByTheUaa(issuer)) { //3. If yes, handle origin correctly String originKey = (String) claims.get(ClaimConstants.ORIGIN); if (!isEmpty(originKey)) { return buildInternalUaaIdpConfig(issuer, originKey); } } //All other cases: throw Exception throw new InsufficientAuthenticationException(String.format("Unable to map issuer, %s , to a single registered provider", issuer)); } catch (IllegalArgumentException | JsonUtils.JsonUtilException x) { throw new InsufficientAuthenticationException("Unable to decode expected id_token"); } }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { try { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication==null || (!(authentication instanceof OAuth2Authentication))) { throw new InvalidTokenException("Missing oauth token."); } authenticationManager.authenticate(authentication); chain.doFilter(request,response); } catch (OAuth2Exception e) { authenticationEntryPoint.commence( (HttpServletRequest)request, (HttpServletResponse)response, new InsufficientAuthenticationException("Insufficient authentication", e)); SecurityContextHolder.clearContext(); } catch (AuthenticationException e) { authenticationEntryPoint.commence((HttpServletRequest)request,(HttpServletResponse)response,e); SecurityContextHolder.clearContext(); } }
} else { logger.debug("No assertion or filter, not attempting SAML authentication for token endpoint."); throw new InsufficientAuthenticationException("SAML Assertion is missing"); } else { logger.debug("No assertion or authentication manager, not attempting JWT bearer authentication for token endpoint."); throw new InsufficientAuthenticationException("Assertion is missing");
new InsufficientAuthenticationException(failed.getMessage(), failed));
throw new InsufficientAuthenticationException( "Cannot access " + service + "." + method + " as anonymous");
String message = failed.getMessage(); logger.debug("Authentication request failed with Oauth exception: " + message); InsufficientAuthenticationException ex = new InsufficientAuthenticationException (message, failed); onUnsuccessfulAuthentication(request, response, ex); authenticationEntryPoint.commence(request, response, ex);
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { String requestToken = request.getParameter(getTokenParameterName()); if (requestToken == null) { throw new InvalidOAuthParametersException("An OAuth token id is required."); } OAuthProviderToken token = getTokenServices().getToken(requestToken); if (token == null) { throw new InvalidOAuthTokenException("No callback value has been provided for request token " + requestToken + "."); } String callbackURL = token.getCallbackUrl(); if (isRequire10a() && callbackURL == null) { throw new InvalidOAuthTokenException("No callback value has been provided for request token " + requestToken + "."); } if (callbackURL != null) { request.setAttribute(CALLBACK_ATTRIBUTE, callbackURL); } Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication == null || !authentication.isAuthenticated()) { throw new InsufficientAuthenticationException("User must be authenticated before authorizing a request token."); } String verifier = getVerifierServices().createVerifier(); request.setAttribute(VERIFIER_ATTRIBUTE, verifier); getTokenServices().authorizeRequestToken(requestToken, verifier, authentication); return authentication; }
throw new InsufficientAuthenticationException( "User must be authenticated with before authorizing access.");
private XMLObject unmarshallObject(String xmlString) throws UnmarshallingException, XMLParserException, UnsupportedEncodingException { BasicParserPool parser = new BasicParserPool(); parser.setNamespaceAware(true); /* Base64URL encoded */ byte bytes[] = xmlString.getBytes("utf-8"); if (bytes == null || bytes.length == 0) throw new InsufficientAuthenticationException("Invalid assertion encoding"); Reader reader = new InputStreamReader(new ByteArrayInputStream(bytes)); Document doc = parser.parse(reader); Element samlElement = doc.getDocumentElement(); UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory(); Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(samlElement); if (unmarshaller == null) { throw new InsufficientAuthenticationException("Unsuccessful to unmarshal assertion string"); } return unmarshaller.unmarshall(samlElement); }
throw new InsufficientAuthenticationException("Passcode information is missing."); pi = JsonUtils.readValue(eCode.getData(), PasscodeInformation.class); } catch (JsonUtils.JsonUtilException e) { throw new InsufficientAuthenticationException("Unable to deserialize passcode object.", e); throw new InsufficientAuthenticationException("Invalid passcode");
protected Authentication validateRequest(TokenRequest request) { //things to validate //1. Authentication must exist and be authenticated Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication == null || !authentication.isAuthenticated() || !(authentication instanceof UaaOauth2Authentication)) { throw new InsufficientAuthenticationException("Invalid authentication object:"+authentication); } UaaOauth2Authentication oauth2Authentication = (UaaOauth2Authentication)authentication; //2. authentication must be a user, and authenticated if (oauth2Authentication.getUserAuthentication() == null || !oauth2Authentication.getUserAuthentication().isAuthenticated()) { throw new InsufficientAuthenticationException("Authentication containing a user is required"); } //3. parameter requesting_client_id must be present if (request.getRequestParameters()==null || request.getRequestParameters().get(USER_TOKEN_REQUESTING_CLIENT_ID)==null) { throw new InvalidGrantException("Parameter "+USER_TOKEN_REQUESTING_CLIENT_ID+" is required."); } //4. grant_type must be user_token if (!TokenConstants.GRANT_TYPE_USER_TOKEN.equals(request.getGrantType())) { throw new InvalidGrantException("Invalid grant type"); } //5. requesting client must have user_token grant type ClientDetails requesting = clientDetailsService.loadClientByClientId(request.getRequestParameters().get(USER_TOKEN_REQUESTING_CLIENT_ID), IdentityZoneHolder.get().getId()); super.validateGrantType(GRANT_TYPE_USER_TOKEN, requesting); //6. receiving client must have refresh_token grant type ClientDetails receiving = clientDetailsService.loadClientByClientId(request.getRequestParameters().get(CLIENT_ID), IdentityZoneHolder.get().getId()); super.validateGrantType(GRANT_TYPE_REFRESH_TOKEN, receiving); return oauth2Authentication.getUserAuthentication(); }
throw new InsufficientAuthenticationException( "There is no client authentication. Try adding an appropriate authentication filter.");