public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { ClientDetails clientDetails; try { clientDetails = clientDetailsService.loadClientByClientId(username); } catch (NoSuchClientException e) { throw new UsernameNotFoundException(e.getMessage(), e); } String clientSecret = clientDetails.getClientSecret(); if (clientSecret== null || clientSecret.trim().length()==0) { clientSecret = emptyPassword; } return new User(username, clientSecret, clientDetails.getAuthorities()); }
public OAuth2AccessToken grant(String grantType, TokenRequest tokenRequest) { if (!this.grantType.equals(grantType)) { return null; } String clientId = tokenRequest.getClientId(); ClientDetails client = clientDetailsService.loadClientByClientId(clientId); validateGrantType(grantType, client); if (logger.isDebugEnabled()) { logger.debug("Getting access token for: " + clientId); } return getAccessToken(client, tokenRequest); }
/** * Is a refresh token supported for this client (or the global setting if * {@link #setClientDetailsService(ClientDetailsService) clientDetailsService} is not set. * * @param clientAuth the current authorization request * @return boolean to indicate if refresh token is supported */ protected boolean isSupportRefreshToken(OAuth2Request clientAuth) { if (clientDetailsService != null) { ClientDetails client = clientDetailsService.loadClientByClientId(clientAuth.getClientId()); return client.getAuthorizedGrantTypes().contains("refresh_token"); } return this.supportRefreshToken; }
public AuthorizationRequest createAuthorizationRequest(Map<String, String> authorizationParameters) { String clientId = authorizationParameters.get(OAuth2Utils.CLIENT_ID); String state = authorizationParameters.get(OAuth2Utils.STATE); String redirectUri = authorizationParameters.get(OAuth2Utils.REDIRECT_URI); Set<String> responseTypes = OAuth2Utils.parseParameterList(authorizationParameters .get(OAuth2Utils.RESPONSE_TYPE)); Set<String> scopes = extractScopes(authorizationParameters, clientId); AuthorizationRequest request = new AuthorizationRequest(authorizationParameters, Collections.<String, String> emptyMap(), clientId, scopes, null, null, false, state, redirectUri, responseTypes); ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId); request.setResourceIdsAndAuthoritiesFromClientDetails(clientDetails); return request; }
private Set<String> extractScopes(Map<String, String> requestParameters, String clientId) { Set<String> scopes = OAuth2Utils.parseParameterList(requestParameters.get(OAuth2Utils.SCOPE)); ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId); if ((scopes == null || scopes.isEmpty())) { // If no scopes are specified in the incoming data, use the default values registered with the client // (the spec allows us to choose between this option and rejecting the request completely, so we'll take the // least obnoxious choice as a default). scopes = clientDetails.getScope(); } if (checkUserScopes) { scopes = checkUserScopes(scopes, clientDetails); } return scopes; }
/** * The access token validity period in seconds * * @param clientAuth the current authorization request * @return the access token validity period in seconds */ protected int getAccessTokenValiditySeconds(OAuth2Request clientAuth) { if (clientDetailsService != null) { ClientDetails client = clientDetailsService.loadClientByClientId(clientAuth.getClientId()); Integer validity = client.getAccessTokenValiditySeconds(); if (validity != null) { return validity; } } return accessTokenValiditySeconds; }
/** * The refresh token validity period in seconds * * @param clientAuth the current authorization request * @return the refresh token validity period in seconds */ protected int getRefreshTokenValiditySeconds(OAuth2Request clientAuth) { if (clientDetailsService != null) { ClientDetails client = clientDetailsService.loadClientByClientId(clientAuth.getClientId()); Integer validity = client.getRefreshTokenValiditySeconds(); if (validity != null) { return validity; } } return refreshTokenValiditySeconds; }
private ModelAndView handleException(Exception e, ServletWebRequest webRequest) throws Exception { ResponseEntity<OAuth2Exception> translate = getExceptionTranslator().translate(e); webRequest.getResponse().setStatus(translate.getStatusCode().value()); if (e instanceof ClientAuthenticationException || e instanceof RedirectMismatchException) { return new ModelAndView(errorPage, Collections.singletonMap("error", translate.getBody())); } AuthorizationRequest authorizationRequest = null; try { authorizationRequest = getAuthorizationRequestForError(webRequest); String requestedRedirectParam = authorizationRequest.getRequestParameters().get(OAuth2Utils.REDIRECT_URI); String requestedRedirect = redirectResolver.resolveRedirect(requestedRedirectParam, getClientDetailsService().loadClientByClientId(authorizationRequest.getClientId())); authorizationRequest.setRedirectUri(requestedRedirect); String redirect = getUnsuccessfulRedirect(authorizationRequest, translate.getBody(), authorizationRequest .getResponseTypes().contains("token")); return new ModelAndView(new RedirectView(redirect, false, true, false)); } catch (OAuth2Exception ex) { // If an AuthorizationRequest cannot be created from the incoming parameters it must be // an error. OAuth2Exception can be handled this way. Other exceptions will generate a standard 500 // response. return new ModelAndView(errorPage, Collections.singletonMap("error", translate.getBody())); } }
ClientDetails client = clientDetailsService.loadClientByClientId(clientId); for (String scope : requestedScopes) { if (client.isAutoApprove(scope)) {
if (clientDetailsService!=null) { try { ClientDetails client = clientDetailsService.loadClientByClientId(clientId); approved = true; for (String scope : scopes) {
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { try{ String header = request.getHeader("Authorization"); if (header == null || !header.startsWith("Basic ")) { chain.doFilter(request, response); return; } String[] decodedHeader = extractAndDecodeHeader(header, request); //Validate against client lockout policy String clientId = decodedHeader[0]; //Validate against client secret expiration in the zone configured client secret policy Timestamp lastModified = (Timestamp) clientDetailsService.loadClientByClientId(clientId).getAdditionalInformation().get(ClientConstants.LAST_MODIFIED); } catch(BadCredentialsException e) { super.getAuthenticationEntryPoint().commence(request, response, e); return; } catch(ClientRegistrationException e) { logger.debug(e.getMessage()); } //call parent class to authenticate super.doFilterInternal(request, response, chain); }
ClientDetails client = clientDetailsService.loadClientByClientId(clientId);
private void checkClientDetails(OAuth2Authentication auth) { if (clientDetailsService != null) { ClientDetails client; try { client = clientDetailsService.loadClientByClientId(auth.getOAuth2Request().getClientId()); } catch (ClientRegistrationException e) { throw new OAuth2AccessDeniedException("Invalid token contains invalid client id"); } Set<String> allowed = client.getScope(); for (String scope : auth.getOAuth2Request().getScope()) { if (!allowed.contains(scope)) { throw new OAuth2AccessDeniedException( "Invalid token contains disallowed scope (" + scope + ") for this client"); } } } }
@Override protected void setUp() throws Exception { super.setUp(); authenticationManager = new ScopeAuthenticationManager(); authenticationManager.setThrowOnNotAuthenticated(true); authenticationManager.setRequiredScopes(Collections.singletonList("oauth.login")); clientCredentials = new HashMap<>(); clientCredentials.put("client_id","login"); clientCredentials.put("grant_type","client_credentials"); clientCredentials.put("scope","oauth.login oauth.approval"); ClientDetails loginClient = mock(ClientDetails.class); when(loginClient.getScope()).thenReturn(new HashSet<>(Arrays.asList("oauth.login","oauth.approval"))); ClientDetailsService service = mock(ClientDetailsService.class); when(service.loadClientByClientId("login")).thenReturn(loginClient); AuthorizationRequest authorizationRequest = new DefaultOAuth2RequestFactory(service).createAuthorizationRequest(clientCredentials); authorizationRequest.setApproved(true); request = authorizationRequest.createOAuth2Request(); }
@Test public void doesContinueWithFilterChain_EvenIfClientSecretExpired() throws IOException, ServletException, ParseException { BaseClientDetails clientDetails = new BaseClientDetails("client-1", "none", "uaa.none", "client_credentials", "http://localhost:5000/uaadb" ); Calendar expiredDate = Calendar.getInstance(); expiredDate.set(2016, 1, 1); clientDetails.setAdditionalInformation(createTestAdditionalInformation(expiredDate)); when(clientDetailsService.loadClientByClientId(Mockito.matches("app"))).thenReturn(clientDetails); MockFilterChain chain = mock(MockFilterChain.class); MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Authorization", "Basic " + CREDENTIALS_HEADER_STRING); MockHttpServletResponse response = new MockHttpServletResponse(); filter.doFilter(request, response, chain); verify(clientAuthenticationManager).authenticate(any(Authentication.class)); }
ClientDetails authenticatedClient = getClientDetailsService().loadClientByClientId(clientId);
ClientDetails client = getClientDetailsService().loadClientByClientId(authorizationRequest.getClientId());
@Test public void doesContinueWithFilterChain_IfClientSecretNotExpired() throws IOException, ServletException, ParseException { BaseClientDetails clientDetails = new BaseClientDetails("client-1", "none", "uaa.none", "client_credentials", "http://localhost:5000/uaadb" ); Calendar previousDay = Calendar.getInstance(); previousDay.roll(Calendar.DATE, -1); clientDetails.setAdditionalInformation(createTestAdditionalInformation(previousDay)); when(clientDetailsService.loadClientByClientId(Mockito.matches("app"))).thenReturn(clientDetails); UsernamePasswordAuthentication authResult = new UsernamePasswordAuthentication("app","appclientsecret"); authResult.setAuthenticated(true); when(clientAuthenticationManager.authenticate(any())).thenReturn(authResult); MockFilterChain chain = mock(MockFilterChain.class); MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Authorization", "Basic " + CREDENTIALS_HEADER_STRING); MockHttpServletResponse response = new MockHttpServletResponse(); filter.doFilter(request, response, chain); verify(clientAuthenticationManager).authenticate(any(Authentication.class)); }
ClientDetails client = clientDetailsService.loadClientByClientId(clientAuthentication.getClientId()); Set<String> scopes = clientAuthentication.getScope(); if (oauth2Authentication.isClientOnly() && clientAuthoritiesAreScopes) {
public OAuth2Authentication loadAuthentication(String accessTokenValue) throws AuthenticationException, InvalidTokenException { OAuth2AccessToken accessToken = tokenStore.readAccessToken(accessTokenValue); if (accessToken == null) { throw new InvalidTokenException("Invalid access token: " + accessTokenValue); } else if (accessToken.isExpired()) { tokenStore.removeAccessToken(accessToken); throw new InvalidTokenException("Access token expired: " + accessTokenValue); } OAuth2Authentication result = tokenStore.readAuthentication(accessToken); if (result == null) { // in case of race condition throw new InvalidTokenException("Invalid access token: " + accessTokenValue); } if (clientDetailsService != null) { String clientId = result.getOAuth2Request().getClientId(); try { clientDetailsService.loadClientByClientId(clientId); } catch (ClientRegistrationException e) { throw new InvalidTokenException("Client not valid: " + clientId, e); } } return result; }