use of org.springframework.web.bind.support.SimpleSessionStatus in project ORCID-Source by ORCID.
the class OauthAuthorizeController method authorize.
@RequestMapping(value = { "/oauth/custom/authorize.json" }, method = RequestMethod.POST)
@ResponseBody
public RequestInfoForm authorize(HttpServletRequest request, HttpServletResponse response, @RequestBody OauthAuthorizeForm form) {
RequestInfoForm requestInfoForm = (RequestInfoForm) request.getSession().getAttribute(REQUEST_INFO_FORM);
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
AuthorizationRequest authorizationRequest = (AuthorizationRequest) request.getSession().getAttribute("authorizationRequest");
Map<String, String> requestParams = new HashMap<String, String>(authorizationRequest.getRequestParameters());
Map<String, String> approvalParams = new HashMap<String, String>();
// Add the persistent token information
if (form.getApproved()) {
requestParams.put(OAuth2Utils.USER_OAUTH_APPROVAL, "true");
approvalParams.put(OAuth2Utils.USER_OAUTH_APPROVAL, "true");
} else {
requestParams.put(OAuth2Utils.USER_OAUTH_APPROVAL, "false");
approvalParams.put(OAuth2Utils.USER_OAUTH_APPROVAL, "false");
}
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
if (form.getPersistentTokenEnabled())
requestParams.put(OrcidOauth2Constants.GRANT_PERSISTENT_TOKEN, "true");
// strip /email/read-private scope if user has not consented
if (requestInfoForm.containsEmailReadPrivateScope() && !form.isEmailAccessAllowed()) {
requestInfoForm.removeEmailReadPrivateScope();
requestParams.put(OrcidOauth2Constants.SCOPE_PARAM, requestInfoForm.getScopesAsString());
}
// 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
RedirectView view = (RedirectView) authorizationEndpoint.approveOrDeny(approvalParams, model, status, auth);
requestInfoForm.setRedirectUrl(view.getUrl());
if (new HttpSessionRequestCache().getRequest(request, response) != null)
new HttpSessionRequestCache().removeRequest(request, response);
LOGGER.info("OauthConfirmAccessController form.getRedirectUri being sent to client browser: " + requestInfoForm.getRedirectUrl());
return requestInfoForm;
}
use of org.springframework.web.bind.support.SimpleSessionStatus 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, requestInfoForm.getResponseType());
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. max_age is in seconds.
// is also on the entity.
java.util.Date authTime = profileEntityManager.getLastLogin(orcid);
try {
long max = Long.parseLong(maxAge);
if (authTime == null || ((authTime.getTime() + (max * 1000)) < (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);
boolean hasPersistent = hasPersistenTokensEnabled(requestInfoForm.getClientId());
// Don't let non persistent clients persist
if (!hasPersistent && "true".equals(requestParams.get(OrcidOauth2Constants.GRANT_PERSISTENT_TOKEN))) {
requestParams.put(OrcidOauth2Constants.GRANT_PERSISTENT_TOKEN, "false");
}
// default to client default if not set
if (requestParams.get(OrcidOauth2Constants.GRANT_PERSISTENT_TOKEN) == null) {
if (hasPersistent)
requestParams.put(OrcidOauth2Constants.GRANT_PERSISTENT_TOKEN, "true");
else
requestParams.put(OrcidOauth2Constants.GRANT_PERSISTENT_TOKEN, "false");
}
// 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;
}
}
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=interaction_required";
RedirectView rView = new RedirectView(redirectUriWithParams);
ModelAndView error = new ModelAndView();
error.setView(rView);
return error;
}
}
mav.addObject("hideUserVoiceScript", true);
mav.addObject("originalOauth2Process", true);
mav.setViewName("confirm-oauth-access");
return mav;
}
use of org.springframework.web.bind.support.SimpleSessionStatus in project ORCID-Source by ORCID.
the class OauthLoginController method authenticateAndAuthorize.
@RequestMapping(value = { "/oauth/custom/signin.json", "/oauth/custom/login.json" }, method = RequestMethod.POST)
@ResponseBody
public OauthAuthorizeForm authenticateAndAuthorize(HttpServletRequest request, HttpServletResponse response, @RequestBody OauthAuthorizeForm form) {
// Clean form errors
form.setErrors(new ArrayList<String>());
RequestInfoForm requestInfoForm = (RequestInfoForm) request.getSession().getAttribute(REQUEST_INFO_FORM);
boolean willBeRedirected = false;
if (form.getApproved()) {
// Validate name and password
validateUserNameAndPassword(form);
if (form.getErrors().isEmpty()) {
try {
// Authenticate user
copy2FAFields(form, request);
Authentication auth = authenticateUser(request, form.getUserName().getValue(), form.getPassword().getValue());
profileEntityManager.updateLastLoginDetails(auth.getName(), OrcidRequestUtil.getIpAddress(request));
// Create authorization params
SimpleSessionStatus status = new SimpleSessionStatus();
Map<String, Object> model = new HashMap<String, Object>();
Map<String, String> params = new HashMap<String, String>();
Map<String, String> approvalParams = new HashMap<String, String>();
fillOauthParams(requestInfoForm, params, approvalParams, form.getPersistentTokenEnabled(), form.isEmailAccessAllowed());
// Authorize
try {
authorizationEndpoint.authorize(model, params, status, auth);
} catch (RedirectMismatchException rUriError) {
String redirectUri = this.getBaseUri() + REDIRECT_URI_ERROR;
// Set the client id
redirectUri = redirectUri.replace("{0}", requestInfoForm.getClientId());
// Set the response type if needed
if (!PojoUtil.isEmpty(requestInfoForm.getResponseType()))
redirectUri += "&response_type=" + requestInfoForm.getResponseType();
// Set the redirect uri
if (!PojoUtil.isEmpty(requestInfoForm.getRedirectUrl()))
redirectUri += "&redirect_uri=" + requestInfoForm.getRedirectUrl();
// Set the scope param
if (!PojoUtil.isEmpty(requestInfoForm.getScopesAsString()))
redirectUri += "&scope=" + requestInfoForm.getScopesAsString();
// Copy the state param if present
if (!PojoUtil.isEmpty(requestInfoForm.getStateParam()))
redirectUri += "&state=" + requestInfoForm.getStateParam();
form.setRedirectUrl(redirectUri);
LOGGER.info("OauthLoginController being sent to client browser: " + form.getRedirectUrl());
return form;
}
// Approve
RedirectView view = (RedirectView) authorizationEndpoint.approveOrDeny(approvalParams, model, status, auth);
form.setRedirectUrl(view.getUrl());
willBeRedirected = true;
} catch (AuthenticationException ae) {
if (ae.getCause() instanceof DisabledException) {
// Handle this message in angular to allow AJAX action
form.getErrors().add("orcid.frontend.security.orcid_deactivated");
} else if (ae.getCause() instanceof UnclaimedProfileExistsException) {
String email = PojoUtil.isEmpty(form.getUserName()) ? null : form.getUserName().getValue();
String resendEmailUrl = createResendClaimUrl(email, request);
String errorMessage = getMessage("orcid.frontend.security.unclaimed_exists_1");
errorMessage += "<a href=\"" + resendEmailUrl + "\">";
errorMessage += getMessage("orcid.frontend.security.unclaimed_exists_2");
errorMessage += "</a>" + getMessage("orcid.frontend.security.unclaimed_exists_3");
form.getErrors().add(errorMessage);
} else if (ae instanceof VerificationCodeFor2FARequiredException) {
form.setVerificationCodeRequired(true);
} else if (ae instanceof Bad2FAVerificationCodeException) {
form.getErrors().add(getMessage("orcid.frontend.security.2fa.bad_verification_code"));
} else if (ae instanceof Bad2FARecoveryCodeException) {
form.getErrors().add(getMessage("orcid.frontend.security.2fa.bad_recovery_code"));
} else {
form.getErrors().add(getMessage("orcid.frontend.security.bad_credentials"));
}
}
}
} else {
form.setRedirectUrl(buildDenyRedirectUri(requestInfoForm.getRedirectUrl(), requestInfoForm.getStateParam()));
willBeRedirected = true;
}
// not be redirected yet
if (willBeRedirected) {
if (new HttpSessionRequestCache().getRequest(request, response) != null)
new HttpSessionRequestCache().removeRequest(request, response);
LOGGER.info("OauthConfirmAccessController form.getRedirectUri being sent to client browser: " + requestInfoForm.getRedirectUrl());
}
return form;
}
use of org.springframework.web.bind.support.SimpleSessionStatus in project Gemma by PavlidisLab.
the class PubMedQueryControllerTest method testOnSubmitNotFound.
@Test
public final void testOnSubmitNotFound() throws Exception {
MockHttpServletRequest request = this.newPost("/pubMedSearch.html");
ModelAndView mv = controller.onSubmit(request, new PubMedSearchCommand("13133333314444"), new BeanPropertyBindingResult(new PubMedSearchCommand("13133333314444"), "searchCriteria"), new SimpleSessionStatus());
Errors errors = (Errors) mv.getModel().get(BindingResult.MODEL_KEY_PREFIX + "searchCriteria");
assertTrue("Expected an error", errors != null);
assertEquals("bibRefSearch", mv.getViewName());
}
use of org.springframework.web.bind.support.SimpleSessionStatus in project Gemma by PavlidisLab.
the class PubMedQueryControllerTest method testOnSubmit.
@Test
public final void testOnSubmit() throws Exception {
MockHttpServletRequest request = this.newPost("/pubMedSearch.html");
request.addParameter("accession", "134444");
try {
ModelAndView mv = controller.onSubmit(request, new PubMedSearchCommand("134444"), new BeanPropertyBindingResult(new PubMedSearchCommand("134444"), "searchCriteria"), new SimpleSessionStatus());
Errors errors = (Errors) mv.getModel().get(BindingResult.MODEL_KEY_PREFIX + "accession");
assertNull("Errors in model: " + errors, errors);
// verify that success messages are in the request
assertNotNull(mv.getModel().get("bibliographicReference"));
assertNotNull(request.getSession().getAttribute("messages"));
assertEquals("bibRefView", mv.getViewName());
} catch (Exception e) {
if (e.getCause() instanceof IOException && e.getCause().getMessage().contains("502")) {
log.warn("Error 502 from NCBI, skipping test");
return;
} else if (e.getCause() instanceof IOException && e.getCause().getMessage().contains("503")) {
log.warn("Error 503 from NCBI, skipping test");
return;
}
throw (e);
}
}
Aggregations