use of org.springframework.security.oauth2.common.exceptions.InvalidScopeException in project spring-security-oauth by spring-projects.
the class AuthorizationEndpointTests method testAuthorizationCodeError.
@Test
public void testAuthorizationCodeError() throws Exception {
endpoint.setUserApprovalHandler(new DefaultUserApprovalHandler() {
public AuthorizationRequest checkForPreApproval(AuthorizationRequest authorizationRequest, Authentication userAuthentication) {
return authorizationRequest;
}
public AuthorizationRequest updateAfterApproval(AuthorizationRequest authorizationRequest, Authentication userAuthentication) {
return authorizationRequest;
}
public boolean isApproved(AuthorizationRequest authorizationRequest, Authentication userAuthentication) {
return true;
}
});
endpoint.setAuthorizationCodeServices(new StubAuthorizationCodeServices() {
@Override
public String createAuthorizationCode(OAuth2Authentication authentication) {
throw new InvalidScopeException("FOO");
}
});
ModelAndView result = endpoint.authorize(model, getAuthorizationRequest("foo", "http://anywhere.com", "mystate", "myscope", Collections.singleton("code")).getRequestParameters(), sessionStatus, principal);
String url = ((RedirectView) result.getView()).getUrl();
assertTrue("Wrong view: " + result, url.startsWith("http://anywhere.com"));
assertTrue("No error: " + result, url.contains("?error="));
assertTrue("Wrong state: " + result, url.contains("&state=mystate"));
}
use of org.springframework.security.oauth2.common.exceptions.InvalidScopeException in project ORCID-Source by ORCID.
the class OrcidRefreshTokenChecker method validateRequest.
public void validateRequest(String grantType, TokenRequest tokenRequest, Long requestTimeInMillis) {
String authorization = tokenRequest.getRequestParameters().get(OrcidOauth2Constants.AUTHORIZATION);
String clientId = tokenRequest.getClientId();
String scopes = tokenRequest.getRequestParameters().get(OAuth2Utils.SCOPE);
Long expireIn = tokenRequest.getRequestParameters().containsKey(OrcidOauth2Constants.EXPIRES_IN) ? Long.valueOf(tokenRequest.getRequestParameters().get(OrcidOauth2Constants.EXPIRES_IN)) : 0L;
String refreshToken = tokenRequest.getRequestParameters().get(OrcidOauth2Constants.REFRESH_TOKEN);
OrcidOauth2TokenDetail token = orcidOauth2TokenDetailDao.findByTokenValue(authorization);
// Verify the token belongs to this client
if (!clientId.equals(token.getClientDetailsId())) {
throw new IllegalArgumentException("This token doesnt belong to the given client");
}
// Verify client is enabled
ClientDetailsEntity clientDetails = clientDetailsEntityCacheManager.retrieve(clientId);
orcidOAuth2RequestValidator.validateClientIsEnabled(clientDetails);
// Verify the token is not expired
if (token.getTokenExpiration() != null) {
if (token.getTokenExpiration().before(new Date())) {
throw new InvalidTokenException("Access token expired: " + authorization);
}
}
// Verify access token and refresh token are linked
if (!refreshToken.equals(token.getRefreshTokenValue())) {
throw new InvalidTokenException("Token and refresh token does not match");
}
// Verify the token is not disabled
if (token.getTokenDisabled() != null && token.getTokenDisabled()) {
throw new InvalidTokenException("Parent token is disabled");
}
// Verify scopes are not wider than the token scopes
if (PojoUtil.isEmpty(scopes)) {
scopes = token.getScope();
} else {
Set<ScopePathType> requiredScopes = ScopePathType.getScopesFromSpaceSeparatedString(scopes);
Set<ScopePathType> simpleTokenScopes = ScopePathType.getScopesFromSpaceSeparatedString(token.getScope());
// This collection contains all tokens that should be allowed given
// the scopes that the parent token contains
Set<ScopePathType> combinedTokenScopes = new HashSet<ScopePathType>();
for (ScopePathType scope : simpleTokenScopes) {
combinedTokenScopes.addAll(scope.combined());
}
// combinedTokenScopes
for (ScopePathType scope : requiredScopes) {
if (!combinedTokenScopes.contains(scope)) {
throw new InvalidScopeException("The given scope '" + scope.value() + "' is not allowed for the parent token");
}
}
}
// Validate the expiration for the new token is no later than the parent
// token expiration.
long parentTokenExpiration = token.getTokenExpiration() == null ? System.currentTimeMillis() : token.getTokenExpiration().getTime();
if (expireIn > parentTokenExpiration) {
throw new IllegalArgumentException("Token expiration can't be after " + token.getTokenExpiration());
}
}
use of org.springframework.security.oauth2.common.exceptions.InvalidScopeException in project ORCID-Source by ORCID.
the class OauthLoginController method loginGetHandler.
@RequestMapping(value = { "/oauth/signin", "/oauth/login" }, method = RequestMethod.GET)
public ModelAndView loginGetHandler(HttpServletRequest request, HttpServletResponse response, ModelAndView mav) throws UnsupportedEncodingException {
String url = request.getQueryString();
// default to Reg
boolean showLogin = showLoginDefault;
// Get and save the request information form
RequestInfoForm requestInfoForm = generateRequestInfoForm(url);
request.getSession().setAttribute(REQUEST_INFO_FORM, requestInfoForm);
if (url.toLowerCase().contains("show_login=true"))
showLogin = true;
else if (url.toLowerCase().contains("show_login=false"))
showLogin = false;
//Check if userId is set so we should show the login screen
if (!PojoUtil.isEmpty(requestInfoForm.getUserId())) {
showLogin = true;
}
// Check that the client have the required permissions
// Get client name
ClientDetailsEntity clientDetails = clientDetailsEntityCacheManager.retrieve(requestInfoForm.getClientId());
// validate client scopes
try {
authorizationEndpoint.validateScope(requestInfoForm.getScopesAsString(), clientDetails);
orcidOAuth2RequestValidator.validateClientIsEnabled(clientDetails);
} catch (InvalidScopeException | LockedException e) {
String redirectUriWithParams = requestInfoForm.getRedirectUrl();
if (e instanceof InvalidScopeException) {
redirectUriWithParams += "?error=invalid_scope&error_description=" + e.getMessage();
} else {
redirectUriWithParams += "?error=client_locked&error_description=" + e.getMessage();
}
RedirectView rView = new RedirectView(redirectUriWithParams);
ModelAndView error = new ModelAndView();
error.setView(rView);
return error;
}
//handle openID behaviour
if (!PojoUtil.isEmpty(requestInfoForm.getScopesAsString()) && ScopePathType.getScopesFromSpaceSeparatedString(requestInfoForm.getScopesAsString()).contains(ScopePathType.OPENID)) {
String prompt = request.getParameter(OrcidOauth2Constants.PROMPT);
if (prompt != null && prompt.equals(OrcidOauth2Constants.PROMPT_NONE)) {
String redirectUriWithParams = requestInfoForm.getRedirectUrl();
redirectUriWithParams += "?error=login_required";
RedirectView rView = new RedirectView(redirectUriWithParams);
ModelAndView error = new ModelAndView();
error.setView(rView);
return error;
}
}
mav.addObject("hideUserVoiceScript", true);
mav.addObject("showLogin", String.valueOf(showLogin));
mav.setViewName("oauth_login");
return mav;
}
use of org.springframework.security.oauth2.common.exceptions.InvalidScopeException in project ORCID-Source by ORCID.
the class OauthAuthorizeController method loginGetHandler.
/** This is called if user is already logged in.
* Checks permissions have been granted to client and generates access code.
*
* @param request
* @param response
* @param mav
* @return
* @throws UnsupportedEncodingException
*/
@RequestMapping(value = "/oauth/confirm_access", method = RequestMethod.GET)
public ModelAndView loginGetHandler(HttpServletRequest request, HttpServletResponse response, ModelAndView mav) throws UnsupportedEncodingException {
//Get and save the request information form
RequestInfoForm requestInfoForm = generateRequestInfoForm(request);
request.getSession().setAttribute(REQUEST_INFO_FORM, requestInfoForm);
Boolean justRegistered = (Boolean) request.getSession().getAttribute(OrcidOauth2Constants.JUST_REGISTERED);
if (justRegistered != null) {
request.getSession().removeAttribute(OrcidOauth2Constants.JUST_REGISTERED);
mav.addObject(OrcidOauth2Constants.JUST_REGISTERED, justRegistered);
}
boolean usePersistentTokens = false;
ClientDetailsEntity clientDetails = clientDetailsEntityCacheManager.retrieve(requestInfoForm.getClientId());
// validate client scopes
try {
authorizationEndpoint.validateScope(requestInfoForm.getScopesAsString(), clientDetails);
orcidOAuth2RequestValidator.validateClientIsEnabled(clientDetails);
} catch (InvalidScopeException | LockedException e) {
String redirectUriWithParams = requestInfoForm.getRedirectUrl();
if (e instanceof InvalidScopeException) {
redirectUriWithParams += "?error=invalid_scope&error_description=" + e.getMessage();
} else {
redirectUriWithParams += "?error=client_locked&error_description=" + e.getMessage();
}
RedirectView rView = new RedirectView(redirectUriWithParams);
ModelAndView error = new ModelAndView();
error.setView(rView);
return error;
}
//Add check for prompt=login and max_age here. This is a MUST in the openid spec.
//Add check for prompt=confirm here. This is a SHOULD in the openid spec.
boolean forceConfirm = false;
if (!PojoUtil.isEmpty(requestInfoForm.getScopesAsString()) && ScopePathType.getScopesFromSpaceSeparatedString(requestInfoForm.getScopesAsString()).contains(ScopePathType.OPENID)) {
String prompt = request.getParameter(OrcidOauth2Constants.PROMPT);
String maxAge = request.getParameter(OrcidOauth2Constants.MAX_AGE);
String orcid = getEffectiveUserOrcid();
if (maxAge != null) {
//if maxAge+lastlogin > now, force login
//is also on the entity.
java.util.Date authTime = profileEntityManager.getLastLogin(orcid);
try {
long max = Long.parseLong(maxAge);
if (authTime == null || ((authTime.getTime() + max) < (new java.util.Date()).getTime())) {
return oauthLoginController.loginGetHandler(request, response, new ModelAndView());
}
} catch (NumberFormatException e) {
//ignore
}
}
if (prompt != null && prompt.equals(OrcidOauth2Constants.PROMPT_CONFIRM)) {
forceConfirm = true;
} else if (prompt != null && prompt.equals(OrcidOauth2Constants.PROMPT_LOGIN)) {
request.getParameterMap().remove(OrcidOauth2Constants.PROMPT);
return oauthLoginController.loginGetHandler(request, response, new ModelAndView());
}
}
// Check if the client has persistent tokens enabled
if (clientDetails.isPersistentTokensEnabled()) {
usePersistentTokens = true;
}
if (!forceConfirm && usePersistentTokens) {
boolean tokenLongLifeAlreadyExists = tokenServices.longLifeTokenExist(requestInfoForm.getClientId(), getEffectiveUserOrcid(), OAuth2Utils.parseParameterList(requestInfoForm.getScopesAsString()));
if (tokenLongLifeAlreadyExists) {
AuthorizationRequest authorizationRequest = (AuthorizationRequest) request.getSession().getAttribute("authorizationRequest");
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Map<String, String> requestParams = new HashMap<String, String>();
copyRequestParameters(request, requestParams);
Map<String, String> approvalParams = new HashMap<String, String>();
requestParams.put(OAuth2Utils.USER_OAUTH_APPROVAL, "true");
approvalParams.put(OAuth2Utils.USER_OAUTH_APPROVAL, "true");
requestParams.put(OrcidOauth2Constants.TOKEN_VERSION, OrcidOauth2Constants.PERSISTENT_TOKEN);
// Check if the client have persistent tokens enabled
requestParams.put(OrcidOauth2Constants.GRANT_PERSISTENT_TOKEN, "false");
if (hasPersistenTokensEnabled(requestInfoForm.getClientId())) {
// Then check if the client granted the persistent token
requestParams.put(OrcidOauth2Constants.GRANT_PERSISTENT_TOKEN, "true");
}
// Session status
SimpleSessionStatus status = new SimpleSessionStatus();
authorizationRequest.setRequestParameters(requestParams);
// Authorization request model
Map<String, Object> model = new HashMap<String, Object>();
model.put("authorizationRequest", authorizationRequest);
// Approve using the spring authorization endpoint code.
//note this will also handle generting implicit tokens via getTokenGranter().grant("implicit",new ImplicitTokenRequest(tokenRequest, storedOAuth2Request));
RedirectView view = (RedirectView) authorizationEndpoint.approveOrDeny(approvalParams, model, status, auth);
ModelAndView authCodeView = new ModelAndView();
authCodeView.setView(view);
return authCodeView;
}
}
mav.addObject("hideUserVoiceScript", true);
mav.setViewName("confirm-oauth-access");
return mav;
}
use of org.springframework.security.oauth2.common.exceptions.InvalidScopeException in project ORCID-Source by ORCID.
the class LoginController method handleOauthSignIn.
private ModelAndView handleOauthSignIn(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
String queryString = request.getQueryString();
String redirectUri = null;
// Get and save the request information form
RequestInfoForm requestInfoForm = generateRequestInfoForm(queryString);
request.getSession().setAttribute(REQUEST_INFO_FORM, requestInfoForm);
// Save also the original query string
request.getSession().setAttribute("queryString", queryString);
// Save a flag to indicate this is a request from the new
request.getSession().setAttribute("OAUTH_2SCREENS", true);
// Redirect URI
redirectUri = requestInfoForm.getRedirectUrl();
// Check that the client have the required permissions
// Get client name
String clientId = requestInfoForm.getClientId();
if (PojoUtil.isEmpty(clientId)) {
String redirectUriWithParams = redirectUri + "?error=invalid_client&error_description=invalid client_id";
return new ModelAndView(new RedirectView(redirectUriWithParams));
}
// Validate client details
ClientDetailsEntity clientDetails = clientDetailsEntityCacheManager.retrieve(clientId);
try {
orcidOAuth2RequestValidator.validateClientIsEnabled(clientDetails);
} catch (LockedException e) {
String redirectUriWithParams = redirectUri + "?error=client_locked&error_description=" + e.getMessage();
return new ModelAndView(new RedirectView(redirectUriWithParams));
}
// validate client scopes
try {
authorizationEndpoint.validateScope(requestInfoForm.getScopesAsString(), clientDetails);
} catch (InvalidScopeException e) {
String redirectUriWithParams = redirectUri + "?error=invalid_scope&error_description=" + e.getMessage();
return new ModelAndView(new RedirectView(redirectUriWithParams));
}
ModelAndView mav = new ModelAndView("login");
mav.addObject("hideUserVoiceScript", true);
mav.addObject("oauth2Screens", true);
return mav;
}
Aggregations