private static String resolveFromRequestParameters(HttpServletRequest request) { String[] values = request.getParameterValues("access_token"); if (values == null || values.length == 0) { return null; } if (values.length == 1) { return values[0]; } BearerTokenError error = new BearerTokenError(BearerTokenErrorCodes.INVALID_REQUEST, HttpStatus.BAD_REQUEST, "Found multiple bearer tokens in the request", "https://tools.ietf.org/html/rfc6750#section-3.1"); throw new OAuth2AuthenticationException(error); }
private HttpStatus getStatus(AuthenticationException authException) { if (authException instanceof OAuth2AuthenticationException) { OAuth2Error error = ((OAuth2AuthenticationException) authException).getError(); if (error instanceof BearerTokenError) { return ((BearerTokenError) error).getHttpStatus(); } } return HttpStatus.UNAUTHORIZED; }
/** * Constructs an {@code OAuth2AuthenticationException} using the provided parameters. * * @param error the {@link OAuth2Error OAuth 2.0 Error} * @param message the detail message */ public OAuth2AuthenticationException(OAuth2Error error, String message) { super(message); this.setError(error); }
private static String resolveFromAuthorizationHeader(HttpServletRequest request) { String authorization = request.getHeader(HttpHeaders.AUTHORIZATION); if (StringUtils.startsWithIgnoreCase(authorization, "bearer")) { Matcher matcher = authorizationPattern.matcher(authorization); if (!matcher.matches()) { BearerTokenError error = new BearerTokenError(BearerTokenErrorCodes.INVALID_TOKEN, HttpStatus.UNAUTHORIZED, "Bearer token is malformed", "https://tools.ietf.org/html/rfc6750#section-3.1"); throw new OAuth2AuthenticationException(error); } return matcher.group("token"); } return null; }
private Predicate<? super Throwable> errorCode(String errorCode) { return failed -> ((OAuth2AuthenticationException) failed).getError().getErrorCode() == errorCode; } }
/** * Constructs an {@code OAuth2AuthenticationException} using the provided parameters. * * @param error the {@link OAuth2Error OAuth 2.0 Error} * @param message the detail message * @param cause the root cause */ public OAuth2AuthenticationException(OAuth2Error error, String message, Throwable cause) { super(message, cause); this.setError(error); }
private static String resolveFromAuthorizationHeader(HttpHeaders headers) { String authorization = headers.getFirst(HttpHeaders.AUTHORIZATION); if (StringUtils.startsWithIgnoreCase(authorization, "bearer")) { Matcher matcher = authorizationPattern.matcher(authorization); if ( !matcher.matches() ) { BearerTokenError error = new BearerTokenError(BearerTokenErrorCodes.INVALID_TOKEN, HttpStatus.BAD_REQUEST, "Bearer token is malformed", "https://tools.ietf.org/html/rfc6750#section-3.1"); throw new OAuth2AuthenticationException(error); } return matcher.group("token"); } return null; }
private Map<String, String> createParameters(AuthenticationException authException) { Map<String, String> parameters = new LinkedHashMap<>(); if (this.realmName != null) { parameters.put("realm", this.realmName); } if (authException instanceof OAuth2AuthenticationException) { OAuth2Error error = ((OAuth2AuthenticationException) authException).getError(); parameters.put("error", error.getErrorCode()); if (StringUtils.hasText(error.getDescription())) { parameters.put("error_description", error.getDescription()); } if (StringUtils.hasText(error.getUri())) { parameters.put("error_uri", error.getUri()); } if (error instanceof BearerTokenError) { BearerTokenError bearerTokenError = (BearerTokenError) error; if (StringUtils.hasText(bearerTokenError.getScope())) { parameters.put("scope", bearerTokenError.getScope()); } } } return parameters; }
/** * Constructs an {@code OAuth2AuthenticationException} using the provided parameters. * * @param error the {@link OAuth2Error OAuth 2.0 Error} * @param message the detail message * @param cause the root cause */ public OAuth2AuthenticationException(OAuth2Error error, String message, Throwable cause) { super(message, cause); this.setError(error); }
private OAuth2AuthenticationException onError(JwtException e) { OAuth2Error invalidRequest = invalidToken(e.getMessage()); return new OAuth2AuthenticationException(invalidRequest, e.getMessage()); }
OAuth2Error error = ((OAuth2AuthenticationException) authException).getError();
/** * Constructs an {@code OAuth2AuthenticationException} using the provided parameters. * * @param error the {@link OAuth2Error OAuth 2.0 Error} * @param message the detail message */ public OAuth2AuthenticationException(OAuth2Error error, String message) { super(message); this.setError(error); }
private Mono<OidcUserInfo> getUserInfo(OidcUserRequest userRequest) { if (!OidcUserRequestUtils.shouldRetrieveUserInfo(userRequest)) { return Mono.empty(); } return this.oauth2UserService.loadUser(userRequest) .map(OAuth2User::getAttributes) .map(OidcUserInfo::new) .doOnNext(userInfo -> { String subject = userInfo.getSubject(); if (subject == null || !subject.equals(userRequest.getIdToken().getSubject())) { OAuth2Error oauth2Error = new OAuth2Error(INVALID_USER_INFO_RESPONSE_ERROR_CODE); throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString()); } }); }
@Test public void doFilterWhenAuthorizationResponseInvalidThenInvalidRequestError() throws Exception { String requestUri = "/login/oauth2/code/" + this.registration1.getRegistrationId(); MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri); request.setServletPath(requestUri); // NOTE: // A valid Authorization Response contains either a 'code' or 'error' parameter. // Don't set it to force an invalid Authorization Response. MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain filterChain = mock(FilterChain.class); this.filter.doFilter(request, response, filterChain); ArgumentCaptor<AuthenticationException> authenticationExceptionArgCaptor = ArgumentCaptor.forClass(AuthenticationException.class); verify(this.failureHandler).onAuthenticationFailure(any(HttpServletRequest.class), any(HttpServletResponse.class), authenticationExceptionArgCaptor.capture()); assertThat(authenticationExceptionArgCaptor.getValue()).isInstanceOf(OAuth2AuthenticationException.class); OAuth2AuthenticationException authenticationException = (OAuth2AuthenticationException) authenticationExceptionArgCaptor.getValue(); assertThat(authenticationException.getError().getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST); }
/** * Constructs an {@code OAuth2AuthenticationException} using the provided parameters. * * @param error the {@link OAuth2Error OAuth 2.0 Error} * @param message the detail message */ public OAuth2AuthenticationException(OAuth2Error error, String message) { super(message); this.setError(error); }
@Override public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException { Assert.notNull(userRequest, "userRequest cannot be null"); String registrationId = userRequest.getClientRegistration().getRegistrationId(); Class<? extends OAuth2User> customUserType; if ((customUserType = this.customUserTypes.get(registrationId)) == null) { return null; } RequestEntity<?> request = this.requestEntityConverter.convert(userRequest); ResponseEntity<? extends OAuth2User> response; try { response = this.restOperations.exchange(request, customUserType); } catch (RestClientException ex) { OAuth2Error oauth2Error = new OAuth2Error(INVALID_USER_INFO_RESPONSE_ERROR_CODE, "An error occurred while attempting to retrieve the UserInfo Resource: " + ex.getMessage(), null); throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString(), ex); } OAuth2User oauth2User = response.getBody(); return oauth2User; }
@Test public void doFilterWhenAuthorizationResponseAuthorizationRequestNotFoundThenAuthorizationRequestNotFoundError() throws Exception { String requestUri = "/login/oauth2/code/" + this.registration2.getRegistrationId(); MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri); request.setServletPath(requestUri); request.addParameter(OAuth2ParameterNames.CODE, "code"); request.addParameter(OAuth2ParameterNames.STATE, "state"); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain filterChain = mock(FilterChain.class); this.filter.doFilter(request, response, filterChain); ArgumentCaptor<AuthenticationException> authenticationExceptionArgCaptor = ArgumentCaptor.forClass(AuthenticationException.class); verify(this.failureHandler).onAuthenticationFailure(any(HttpServletRequest.class), any(HttpServletResponse.class), authenticationExceptionArgCaptor.capture()); assertThat(authenticationExceptionArgCaptor.getValue()).isInstanceOf(OAuth2AuthenticationException.class); OAuth2AuthenticationException authenticationException = (OAuth2AuthenticationException) authenticationExceptionArgCaptor.getValue(); assertThat(authenticationException.getError().getErrorCode()).isEqualTo("authorization_request_not_found"); }
/** * Constructs an {@code OAuth2AuthenticationException} using the provided parameters. * * @param error the {@link OAuth2Error OAuth 2.0 Error} * @param message the detail message * @param cause the root cause */ public OAuth2AuthenticationException(OAuth2Error error, String message, Throwable cause) { super(message, cause); this.setError(error); }
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { OAuth2LoginAuthenticationToken authorizationCodeAuthentication = (OAuth2LoginAuthenticationToken) authentication; // Section 3.1.2.1 Authentication Request - http://openid.net/specs/openid-connect-core-1_0.html#AuthRequest // scope // REQUIRED. OpenID Connect requests MUST contain the "openid" scope value. if (authorizationCodeAuthentication.getAuthorizationExchange() .getAuthorizationRequest().getScopes().contains(OidcScopes.OPENID)) { OAuth2Error oauth2Error = new OAuth2Error( "oidc_provider_not_configured", "An OpenID Connect Authentication Provider has not been configured. " + "Check to ensure you include the dependency 'spring-security-oauth2-jose'.", null); throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString()); } return null; }
assertThat(authenticationException.getError().getErrorCode()).isEqualTo("client_registration_not_found");