use of org.springframework.security.authentication.InsufficientAuthenticationException in project spring-security-oauth by spring-projects.
the class AccessTokenProviderChain method obtainAccessToken.
public OAuth2AccessToken obtainAccessToken(OAuth2ProtectedResourceDetails resource, AccessTokenRequest request) throws UserRedirectRequiredException, AccessDeniedException {
OAuth2AccessToken accessToken = null;
OAuth2AccessToken existingToken = null;
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth instanceof AnonymousAuthenticationToken) {
if (!resource.isClientOnly()) {
throw new InsufficientAuthenticationException("Authentication is required to obtain an access token (anonymous not allowed)");
}
}
if (resource.isClientOnly() || (auth != null && auth.isAuthenticated())) {
existingToken = request.getExistingToken();
if (existingToken == null && clientTokenServices != null) {
existingToken = clientTokenServices.getAccessToken(resource, auth);
}
if (existingToken != null) {
if (existingToken.isExpired()) {
if (clientTokenServices != null) {
clientTokenServices.removeAccessToken(resource, auth);
}
OAuth2RefreshToken refreshToken = existingToken.getRefreshToken();
if (refreshToken != null) {
accessToken = refreshAccessToken(resource, refreshToken, request);
}
} else {
accessToken = existingToken;
}
}
}
if (accessToken == null) {
// looks like we need to try to obtain a new token.
accessToken = obtainNewAccessTokenInternal(resource, request);
if (accessToken == null) {
throw new IllegalStateException("An OAuth 2 access token must be obtained or an exception thrown.");
}
}
if (clientTokenServices != null && (resource.isClientOnly() || auth != null && auth.isAuthenticated())) {
clientTokenServices.saveAccessToken(resource, auth, accessToken);
}
return accessToken;
}
use of org.springframework.security.authentication.InsufficientAuthenticationException in project spring-security-oauth by spring-projects.
the class OAuthUserAuthorizationProcessingFilterTests method testAttemptAuthentication.
/**
* tests the attempt to authenticate.
*/
@Test
public void testAttemptAuthentication() throws Exception {
UserAuthorizationProcessingFilter filter = new UserAuthorizationProcessingFilter("/");
OAuthVerifierServices vs = mock(OAuthVerifierServices.class);
filter.setVerifierServices(vs);
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
Authentication authentication = mock(Authentication.class);
OAuthProviderTokenServices tokenServices = mock(OAuthProviderTokenServices.class);
filter.setTokenServices(tokenServices);
SecurityContextHolder.getContext().setAuthentication(authentication);
when(request.getParameter("requestToken")).thenReturn("tok");
OAuthProviderTokenImpl token = new OAuthProviderTokenImpl();
token.setCallbackUrl("callback");
when(tokenServices.getToken("tok")).thenReturn(token);
when(authentication.isAuthenticated()).thenReturn(false);
try {
filter.attemptAuthentication(request, response);
fail();
} catch (InsufficientAuthenticationException e) {
}
verify(request).setAttribute(UserAuthorizationProcessingFilter.CALLBACK_ATTRIBUTE, "callback");
reset(request);
when(authentication.isAuthenticated()).thenReturn(true);
when(request.getParameter("requestToken")).thenReturn("tok");
when(tokenServices.getToken("tok")).thenReturn(token);
when(vs.createVerifier()).thenReturn("verifier");
tokenServices.authorizeRequestToken("tok", "verifier", authentication);
filter.setTokenServices(tokenServices);
filter.attemptAuthentication(request, response);
verify(request).setAttribute(UserAuthorizationProcessingFilter.CALLBACK_ATTRIBUTE, "callback");
verify(request).setAttribute(UserAuthorizationProcessingFilter.VERIFIER_ATTRIBUTE, "verifier");
SecurityContextHolder.getContext().setAuthentication(null);
}
use of org.springframework.security.authentication.InsufficientAuthenticationException in project spring-security-oauth by spring-projects.
the class UserAuthorizationProcessingFilter method attemptAuthentication.
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;
}
use of org.springframework.security.authentication.InsufficientAuthenticationException in project spring-security-oauth by spring-projects.
the class TokenEndpoint method getClientId.
/**
* @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;
}
use of org.springframework.security.authentication.InsufficientAuthenticationException in project spring-security-oauth by spring-projects.
the class TokenEndpoint method postAccessToken.
@RequestMapping(value = "/oauth/token", method = RequestMethod.POST)
public ResponseEntity<OAuth2AccessToken> postAccessToken(Principal principal, @RequestParam Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {
if (!(principal instanceof Authentication)) {
throw new InsufficientAuthenticationException("There is no client authentication. Try adding an appropriate authentication filter.");
}
String clientId = getClientId(principal);
ClientDetails authenticatedClient = getClientDetailsService().loadClientByClientId(clientId);
TokenRequest tokenRequest = getOAuth2RequestFactory().createTokenRequest(parameters, authenticatedClient);
if (clientId != null && !clientId.equals("")) {
// request.
if (!clientId.equals(tokenRequest.getClientId())) {
// authenticated client
throw new InvalidClientException("Given client ID does not match authenticated client");
}
}
if (authenticatedClient != null) {
oAuth2RequestValidator.validateScope(tokenRequest, authenticatedClient);
}
if (!StringUtils.hasText(tokenRequest.getGrantType())) {
throw new InvalidRequestException("Missing grant type");
}
if (tokenRequest.getGrantType().equals("implicit")) {
throw new InvalidGrantException("Implicit grant type not supported from token endpoint");
}
if (isAuthCodeRequest(parameters)) {
// The scope was requested or determined during the authorization step
if (!tokenRequest.getScope().isEmpty()) {
logger.debug("Clearing scope of incoming token request");
tokenRequest.setScope(Collections.<String>emptySet());
}
}
if (isRefreshTokenRequest(parameters)) {
// A refresh token has its own default scopes, so we should ignore any added by the factory here.
tokenRequest.setScope(OAuth2Utils.parseParameterList(parameters.get(OAuth2Utils.SCOPE)));
}
OAuth2AccessToken token = getTokenGranter().grant(tokenRequest.getGrantType(), tokenRequest);
if (token == null) {
throw new UnsupportedGrantTypeException("Unsupported grant type: " + tokenRequest.getGrantType());
}
return getResponse(token);
}
Aggregations