use of org.springframework.security.oauth2.common.exceptions.InvalidGrantException 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);
}
use of org.springframework.security.oauth2.common.exceptions.InvalidGrantException in project spring-security-oauth by spring-projects.
the class DefaultRedirectResolver method resolveRedirect.
public String resolveRedirect(String requestedRedirect, ClientDetails client) throws OAuth2Exception {
Set<String> authorizedGrantTypes = client.getAuthorizedGrantTypes();
if (authorizedGrantTypes.isEmpty()) {
throw new InvalidGrantException("A client must have at least one authorized grant type.");
}
if (!containsRedirectGrantType(authorizedGrantTypes)) {
throw new InvalidGrantException("A redirect_uri can only be used by implicit or authorization_code grant types.");
}
Set<String> redirectUris = client.getRegisteredRedirectUri();
if (redirectUris != null && !redirectUris.isEmpty()) {
return obtainMatchingRedirect(redirectUris, requestedRedirect);
} else if (StringUtils.hasText(requestedRedirect)) {
return requestedRedirect;
} else {
throw new InvalidRequestException("A redirect_uri must be supplied.");
}
}
use of org.springframework.security.oauth2.common.exceptions.InvalidGrantException in project spring-security-oauth by spring-projects.
the class AuthorizationCodeTokenGranter method getOAuth2Authentication.
@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
Map<String, String> parameters = tokenRequest.getRequestParameters();
String authorizationCode = parameters.get("code");
String redirectUri = parameters.get(OAuth2Utils.REDIRECT_URI);
if (authorizationCode == null) {
throw new InvalidRequestException("An authorization code must be supplied.");
}
OAuth2Authentication storedAuth = authorizationCodeServices.consumeAuthorizationCode(authorizationCode);
if (storedAuth == null) {
throw new InvalidGrantException("Invalid authorization code: " + authorizationCode);
}
OAuth2Request pendingOAuth2Request = storedAuth.getOAuth2Request();
// https://jira.springsource.org/browse/SECOAUTH-333
// This might be null, if the authorization was done without the redirect_uri parameter
String redirectUriApprovalParameter = pendingOAuth2Request.getRequestParameters().get(OAuth2Utils.REDIRECT_URI);
if ((redirectUri != null || redirectUriApprovalParameter != null) && !pendingOAuth2Request.getRedirectUri().equals(redirectUri)) {
throw new RedirectMismatchException("Redirect URI mismatch.");
}
String pendingClientId = pendingOAuth2Request.getClientId();
String clientId = tokenRequest.getClientId();
if (clientId != null && !clientId.equals(pendingClientId)) {
// just a sanity check.
throw new InvalidClientException("Client ID mismatch");
}
// Secret is not required in the authorization request, so it won't be available
// in the pendingAuthorizationRequest. We do want to check that a secret is provided
// in the token request, but that happens elsewhere.
Map<String, String> combinedParameters = new HashMap<String, String>(pendingOAuth2Request.getRequestParameters());
// Combine the parameters adding the new ones last so they override if there are any clashes
combinedParameters.putAll(parameters);
// Make a new stored request with the combined parameters
OAuth2Request finalStoredOAuth2Request = pendingOAuth2Request.createOAuth2Request(combinedParameters);
Authentication userAuth = storedAuth.getUserAuthentication();
return new OAuth2Authentication(finalStoredOAuth2Request, userAuth);
}
use of org.springframework.security.oauth2.common.exceptions.InvalidGrantException in project spring-security-oauth by spring-projects.
the class DefaultTokenServices method refreshAccessToken.
@Transactional(noRollbackFor = { InvalidTokenException.class, InvalidGrantException.class })
public OAuth2AccessToken refreshAccessToken(String refreshTokenValue, TokenRequest tokenRequest) throws AuthenticationException {
if (!supportRefreshToken) {
throw new InvalidGrantException("Invalid refresh token: " + refreshTokenValue);
}
OAuth2RefreshToken refreshToken = tokenStore.readRefreshToken(refreshTokenValue);
if (refreshToken == null) {
throw new InvalidGrantException("Invalid refresh token: " + refreshTokenValue);
}
OAuth2Authentication authentication = tokenStore.readAuthenticationForRefreshToken(refreshToken);
if (this.authenticationManager != null && !authentication.isClientOnly()) {
// The client has already been authenticated, but the user authentication might be old now, so give it a
// chance to re-authenticate.
Authentication user = new PreAuthenticatedAuthenticationToken(authentication.getUserAuthentication(), "", authentication.getAuthorities());
user = authenticationManager.authenticate(user);
Object details = authentication.getDetails();
authentication = new OAuth2Authentication(authentication.getOAuth2Request(), user);
authentication.setDetails(details);
}
String clientId = authentication.getOAuth2Request().getClientId();
if (clientId == null || !clientId.equals(tokenRequest.getClientId())) {
throw new InvalidGrantException("Wrong client for this refresh token: " + refreshTokenValue);
}
// clear out any access tokens already associated with the refresh
// token.
tokenStore.removeAccessTokenUsingRefreshToken(refreshToken);
if (isExpired(refreshToken)) {
tokenStore.removeRefreshToken(refreshToken);
throw new InvalidTokenException("Invalid refresh token (expired): " + refreshToken);
}
authentication = createRefreshedAuthentication(authentication, tokenRequest);
if (!reuseRefreshToken) {
tokenStore.removeRefreshToken(refreshToken);
refreshToken = createRefreshToken(authentication);
}
OAuth2AccessToken accessToken = createAccessToken(authentication, refreshToken);
tokenStore.storeAccessToken(accessToken, authentication);
if (!reuseRefreshToken) {
tokenStore.storeRefreshToken(accessToken.getRefreshToken(), authentication);
}
return accessToken;
}
use of org.springframework.security.oauth2.common.exceptions.InvalidGrantException in project cuba by cuba-platform.
the class CubaUserAuthenticationProvider method authenticate.
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String ipAddress = request.getRemoteAddr();
if (authentication instanceof UsernamePasswordAuthenticationToken) {
RestApiConfig config = configuration.getConfig(RestApiConfig.class);
if (!config.getStandardAuthenticationEnabled()) {
log.debug("Standard authentication is disabled. Property cuba.rest.standardAuthenticationEnabled is false");
throw new InvalidGrantException("Authentication disabled");
}
UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
String login = (String) token.getPrincipal();
UserSession session;
try {
String passwordHash = passwordEncryption.getPlainHash((String) token.getCredentials());
LoginPasswordCredentials credentials = new LoginPasswordCredentials(login, passwordHash);
credentials.setIpAddress(ipAddress);
credentials.setClientType(ClientType.REST_API);
credentials.setClientInfo(makeClientInfo(request.getHeader(HttpHeaders.USER_AGENT)));
// if the locale value is explicitly passed in the Accept-Language header then set its value to the
// credentials. Otherwise, the locale of the user should be used
Locale locale = restAuthUtils.extractLocaleFromRequestHeader(request);
if (locale != null) {
credentials.setLocale(locale);
credentials.setOverrideLocale(true);
} else {
credentials.setOverrideLocale(false);
}
session = authenticationService.login(credentials).getSession();
} catch (AccountLockedException le) {
log.info("Blocked user login attempt: login={}, ip={}", login, ipAddress);
throw new LockedException("User temporarily blocked");
} catch (RestApiAccessDeniedException ex) {
log.info("User is not allowed to use the REST API {}", login);
throw new BadCredentialsException("User is not allowed to use the REST API");
} catch (LoginException e) {
log.info("REST API authentication failed: {} {}", login, ipAddress);
throw new BadCredentialsException("Bad credentials");
}
AppContext.setSecurityContext(new SecurityContext(session));
UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), getRoleUserAuthorities(authentication));
@SuppressWarnings("unchecked") Map<String, String> details = (Map<String, String>) authentication.getDetails();
details.put(SESSION_ID_DETAILS_ATTRIBUTE, session.getId().toString());
result.setDetails(details);
return result;
}
return null;
}
Aggregations