List of usage examples for org.springframework.http HttpStatus FORBIDDEN
HttpStatus FORBIDDEN
To view the source code for org.springframework.http HttpStatus FORBIDDEN.
Click Source Link
From source file:org.alfresco.rest.workflow.api.tests.TaskWorkflowApiTest.java
@Test @SuppressWarnings("unchecked") public void testCompleteTask() throws Exception { RequestContext requestContext = initApiClientWithTestUser(); String user = requestContext.getRunAsUser(); String initiator = getOtherPersonInNetwork(requestContext.getRunAsUser(), requestContext.getNetworkId()) .getId();/*w w w .ja v a2s . co m*/ ProcessInstance processCompleteAsAssignee = startAdhocProcess(initiator, requestContext.getNetworkId(), null); ProcessInstance processCompleteAsOwner = startAdhocProcess(initiator, requestContext.getNetworkId(), null); ProcessInstance processCompleteAsInitiator = startAdhocProcess(initiator, requestContext.getNetworkId(), null); ProcessInstance processCompleteAsAdmin = startAdhocProcess(initiator, requestContext.getNetworkId(), null); ProcessInstance processCompleteWithVariables = startAdhocProcess(initiator, requestContext.getNetworkId(), null); try { Task asAssigneeTask = activitiProcessEngine.getTaskService().createTaskQuery() .processInstanceId(processCompleteAsAssignee.getId()).singleResult(); Task asOwnerTask = activitiProcessEngine.getTaskService().createTaskQuery() .processInstanceId(processCompleteAsOwner.getId()).singleResult(); Task asInitiatorTask = activitiProcessEngine.getTaskService().createTaskQuery() .processInstanceId(processCompleteAsInitiator.getId()).singleResult(); Task asAdminTask = activitiProcessEngine.getTaskService().createTaskQuery() .processInstanceId(processCompleteAsAdmin.getId()).singleResult(); Task withVariablesTask = activitiProcessEngine.getTaskService().createTaskQuery() .processInstanceId(processCompleteWithVariables.getId()).singleResult(); TasksClient tasksClient = publicApiClient.tasksClient(); // Unclaiming the task when NOT assignee, owner, initiator or admin results in error JSONObject taskBody = new JSONObject(); taskBody.put("state", "completed"); List<String> selectedFields = new ArrayList<String>(); selectedFields.addAll(Arrays.asList(new String[] { "state" })); try { tasksClient.updateTask(asAssigneeTask.getId(), taskBody, selectedFields); fail("Exception expected"); } catch (PublicApiException expected) { assertEquals(HttpStatus.FORBIDDEN.value(), expected.getHttpResponse().getStatusCode()); assertErrorSummary("Permission was denied", expected.getHttpResponse()); } // Completing as assignee initiator activitiProcessEngine.getTaskService().setAssignee(asAssigneeTask.getId(), user); JSONObject result = tasksClient.updateTask(asAssigneeTask.getId(), taskBody, selectedFields); assertEquals("completed", result.get("state")); assertNotNull(result.get("endedAt")); assertNull(activitiProcessEngine.getTaskService().createTaskQuery().taskId(asAssigneeTask.getId()) .singleResult()); // Completing as process initiator requestContext.setRunAsUser(initiator); activitiProcessEngine.getTaskService().setAssignee(asInitiatorTask.getId(), null); result = tasksClient.updateTask(asInitiatorTask.getId(), taskBody, selectedFields); assertEquals("completed", result.get("state")); assertNotNull(result.get("endedAt")); assertNull(activitiProcessEngine.getTaskService().createTaskQuery().taskId(asInitiatorTask.getId()) .singleResult()); // Completing as owner requestContext.setRunAsUser(user); asOwnerTask.setOwner(user); activitiProcessEngine.getTaskService().saveTask(asOwnerTask); result = tasksClient.updateTask(asOwnerTask.getId(), taskBody, selectedFields); assertEquals("completed", result.get("state")); assertNotNull(result.get("endedAt")); assertNull(activitiProcessEngine.getTaskService().createTaskQuery().taskId(asOwnerTask.getId()) .singleResult()); // Complete as admin String tenantAdmin = AuthenticationUtil.getAdminUserName() + "@" + requestContext.getNetworkId(); publicApiClient.setRequestContext(new RequestContext(TenantUtil.DEFAULT_TENANT, tenantAdmin)); asAdminTask.setOwner(null); activitiProcessEngine.getTaskService().saveTask(asAdminTask); result = tasksClient.updateTask(asAdminTask.getId(), taskBody, selectedFields); assertEquals("completed", result.get("state")); assertNotNull(result.get("endedAt")); assertNull(activitiProcessEngine.getTaskService().createTaskQuery().taskId(asAdminTask.getId()) .singleResult()); // Complete with variables requestContext.setRunAsUser(initiator); activitiProcessEngine.getTaskService().setAssignee(withVariablesTask.getId(), null); JSONArray variablesArray = new JSONArray(); JSONObject variableBody = new JSONObject(); variableBody.put("name", "newGlobalVariable"); variableBody.put("value", 1234); variableBody.put("scope", "global"); variablesArray.add(variableBody); variableBody = new JSONObject(); variableBody.put("name", "newLocalVariable"); variableBody.put("value", 5678); variableBody.put("scope", "local"); variablesArray.add(variableBody); taskBody.put("variables", variablesArray); selectedFields.add("variables"); result = tasksClient.updateTask(withVariablesTask.getId(), taskBody, selectedFields); assertEquals("completed", result.get("state")); assertNotNull(result.get("endedAt")); assertNull(activitiProcessEngine.getTaskService().createTaskQuery().taskId(withVariablesTask.getId()) .singleResult()); HistoricTaskInstance historyTask = activitiProcessEngine.getHistoryService() .createHistoricTaskInstanceQuery().taskId(withVariablesTask.getId()).includeProcessVariables() .includeTaskLocalVariables().singleResult(); assertEquals(1234, historyTask.getProcessVariables().get("newGlobalVariable")); assertEquals(5678, historyTask.getTaskLocalVariables().get("newLocalVariable")); assertNotNull("The outcome should not be null for completed task.", historyTask.getTaskLocalVariables().get("bpm_outcome")); JSONObject variables = tasksClient.findTaskVariables(withVariablesTask.getId()); assertNotNull(variables); JSONObject list = (JSONObject) variables.get("list"); assertNotNull(list); JSONArray entries = (JSONArray) list.get("entries"); assertNotNull(entries); boolean foundGlobal = false; boolean foundLocal = false; for (Object entry : entries) { JSONObject variableObject = (JSONObject) ((JSONObject) entry).get("entry"); if ("newGlobalVariable".equals(variableObject.get("name"))) { assertEquals(1234L, variableObject.get("value")); foundGlobal = true; } else if ("newLocalVariable".equals(variableObject.get("name"))) { assertEquals(5678L, variableObject.get("value")); foundLocal = true; } } assertTrue(foundGlobal); assertTrue(foundLocal); } finally { cleanupProcessInstance(processCompleteAsAssignee, processCompleteAsAdmin, processCompleteAsInitiator, processCompleteAsOwner, processCompleteWithVariables); } }
From source file:org.alfresco.rest.workflow.api.tests.TaskWorkflowApiTest.java
@Test @SuppressWarnings("unchecked") public void testDelegateTask() throws Exception { RequestContext requestContext = initApiClientWithTestUser(); String user = requestContext.getRunAsUser(); String initiator = getOtherPersonInNetwork(requestContext.getRunAsUser(), requestContext.getNetworkId()) .getId();/*from w w w .j ava 2s. co m*/ ProcessInstance processInstance = startAdhocProcess(initiator, requestContext.getNetworkId(), null); try { Task task = activitiProcessEngine.getTaskService().createTaskQuery() .processInstanceId(processInstance.getId()).singleResult(); TasksClient tasksClient = publicApiClient.tasksClient(); // Delegating as non-assignee/owner/initiator/admin should result in an error JSONObject taskBody = new JSONObject(); taskBody.put("state", "delegated"); taskBody.put("assignee", initiator); List<String> selectedFields = new ArrayList<String>(); selectedFields.addAll(Arrays.asList(new String[] { "state", "assignee" })); try { tasksClient.updateTask(task.getId(), taskBody, selectedFields); fail("Exception expected"); } catch (PublicApiException expected) { assertEquals(HttpStatus.FORBIDDEN.value(), expected.getHttpResponse().getStatusCode()); assertErrorSummary("Permission was denied", expected.getHttpResponse()); } // Delegating (as assignee) and not passing in an asisgnee should result in an error activitiProcessEngine.getTaskService().setAssignee(task.getId(), user); taskBody = new JSONObject(); taskBody.put("state", "delegated"); selectedFields = new ArrayList<String>(); selectedFields.addAll(Arrays.asList(new String[] { "state" })); try { tasksClient.updateTask(task.getId(), taskBody, selectedFields); fail("Exception expected"); } catch (PublicApiException expected) { assertEquals(HttpStatus.BAD_REQUEST.value(), expected.getHttpResponse().getStatusCode()); assertErrorSummary( "When delegating a task, assignee should be selected and provided in the request.", expected.getHttpResponse()); } // Delegating as assignee taskBody.put("state", "delegated"); taskBody.put("assignee", initiator); selectedFields = new ArrayList<String>(); selectedFields.addAll(Arrays.asList(new String[] { "state", "assignee" })); assertNull(task.getDelegationState()); JSONObject result = tasksClient.updateTask(task.getId(), taskBody, selectedFields); assertEquals("delegated", result.get("state")); assertEquals(initiator, result.get("assignee")); assertEquals(requestContext.getRunAsUser(), result.get("owner")); task = activitiProcessEngine.getTaskService().createTaskQuery() .processInstanceId(processInstance.getId()).singleResult(); assertEquals(DelegationState.PENDING, task.getDelegationState()); assertEquals(initiator, task.getAssignee()); assertEquals(requestContext.getRunAsUser(), task.getOwner()); // Delegating as owner task.setDelegationState(null); task.setOwner(requestContext.getRunAsUser()); task.setAssignee(null); activitiProcessEngine.getTaskService().saveTask(task); result = tasksClient.updateTask(task.getId(), taskBody, selectedFields); assertEquals("delegated", result.get("state")); assertEquals(initiator, result.get("assignee")); assertEquals(requestContext.getRunAsUser(), result.get("owner")); task = activitiProcessEngine.getTaskService().createTaskQuery() .processInstanceId(processInstance.getId()).singleResult(); assertEquals(DelegationState.PENDING, task.getDelegationState()); assertEquals(initiator, task.getAssignee()); assertEquals(requestContext.getRunAsUser(), task.getOwner()); // Delegating as process initiator task.setDelegationState(null); task.setOwner(null); task.setAssignee(null); activitiProcessEngine.getTaskService().saveTask(task); requestContext.setRunAsUser(initiator); taskBody.put("assignee", user); result = tasksClient.updateTask(task.getId(), taskBody, selectedFields); assertEquals("delegated", result.get("state")); assertEquals(user, result.get("assignee")); assertEquals(initiator, result.get("owner")); task = activitiProcessEngine.getTaskService().createTaskQuery() .processInstanceId(processInstance.getId()).singleResult(); assertEquals(DelegationState.PENDING, task.getDelegationState()); assertEquals(user, task.getAssignee()); assertEquals(initiator, task.getOwner()); // Delegating as administrator String tenantAdmin = AuthenticationUtil.getAdminUserName() + "@" + requestContext.getNetworkId(); task.setDelegationState(null); task.setOwner(null); task.setAssignee(null); activitiProcessEngine.getTaskService().saveTask(task); task = activitiProcessEngine.getTaskService().createTaskQuery() .processInstanceId(processInstance.getId()).singleResult(); requestContext.setRunAsUser(tenantAdmin); taskBody.put("assignee", user); result = tasksClient.updateTask(task.getId(), taskBody, selectedFields); assertEquals("delegated", result.get("state")); assertEquals(user, result.get("assignee")); assertEquals(tenantAdmin, result.get("owner")); task = activitiProcessEngine.getTaskService().createTaskQuery() .processInstanceId(processInstance.getId()).singleResult(); assertEquals(DelegationState.PENDING, task.getDelegationState()); assertEquals(user, task.getAssignee()); assertEquals(tenantAdmin, task.getOwner()); } finally { cleanupProcessInstance(processInstance); } }
From source file:org.alfresco.rest.workflow.api.tests.TaskWorkflowApiTest.java
@Test @SuppressWarnings("unchecked") public void testResolveTask() throws Exception { RequestContext requestContext = initApiClientWithTestUser(); String user = requestContext.getRunAsUser(); String initiator = getOtherPersonInNetwork(requestContext.getRunAsUser(), requestContext.getNetworkId()) .getId();/*from w w w . j a v a 2s. com*/ ProcessInstance processInstance = startAdhocProcess(initiator, requestContext.getNetworkId(), null); try { Task task = activitiProcessEngine.getTaskService().createTaskQuery() .processInstanceId(processInstance.getId()).singleResult(); TasksClient tasksClient = publicApiClient.tasksClient(); // Resolving as non-assignee/owner/initiator/admin should result in an error JSONObject taskBody = new JSONObject(); taskBody.put("state", "resolved"); taskBody.put("assignee", initiator); List<String> selectedFields = new ArrayList<String>(); selectedFields.addAll(Arrays.asList(new String[] { "state", "assignee" })); try { tasksClient.updateTask(task.getId(), taskBody, selectedFields); fail("Exception expected"); } catch (PublicApiException expected) { assertEquals(HttpStatus.FORBIDDEN.value(), expected.getHttpResponse().getStatusCode()); assertErrorSummary("Permission was denied", expected.getHttpResponse()); } // Resolving as assignee task.delegate(user); activitiProcessEngine.getTaskService().saveTask(task); taskBody.put("state", "resolved"); taskBody.put("assignee", initiator); selectedFields = new ArrayList<String>(); selectedFields.addAll(Arrays.asList(new String[] { "state", "assignee" })); JSONObject result = tasksClient.updateTask(task.getId(), taskBody, selectedFields); assertEquals("resolved", result.get("state")); assertEquals(initiator, result.get("assignee")); task = activitiProcessEngine.getTaskService().createTaskQuery() .processInstanceId(processInstance.getId()).singleResult(); assertEquals(DelegationState.RESOLVED, task.getDelegationState()); assertEquals(initiator, task.getAssignee()); HistoricTaskInstance historyTask = activitiProcessEngine.getHistoryService() .createHistoricTaskInstanceQuery().taskId(task.getId()).includeProcessVariables() .includeTaskLocalVariables().singleResult(); assertNotNull("The outcome should not be null for resolved task.", historyTask.getTaskLocalVariables().get("bpm_outcome")); // Resolving as owner task.setDelegationState(null); task.setOwner(requestContext.getRunAsUser()); task.setAssignee(null); activitiProcessEngine.getTaskService().saveTask(task); result = tasksClient.updateTask(task.getId(), taskBody, selectedFields); assertEquals("resolved", result.get("state")); assertEquals(user, result.get("assignee")); task = activitiProcessEngine.getTaskService().createTaskQuery() .processInstanceId(processInstance.getId()).singleResult(); assertEquals(DelegationState.RESOLVED, task.getDelegationState()); assertEquals(user, task.getAssignee()); // Resolving as process initiator task.setDelegationState(null); task.setOwner(null); task.setAssignee(null); activitiProcessEngine.getTaskService().saveTask(task); requestContext.setRunAsUser(initiator); taskBody.put("assignee", user); result = tasksClient.updateTask(task.getId(), taskBody, selectedFields); assertEquals("resolved", result.get("state")); task = activitiProcessEngine.getTaskService().createTaskQuery() .processInstanceId(processInstance.getId()).singleResult(); assertEquals(DelegationState.RESOLVED, task.getDelegationState()); // Resolving as administrator String tenantAdmin = AuthenticationUtil.getAdminUserName() + "@" + requestContext.getNetworkId(); task.setDelegationState(null); task.setOwner(initiator); task.setAssignee(null); activitiProcessEngine.getTaskService().saveTask(task); task = activitiProcessEngine.getTaskService().createTaskQuery() .processInstanceId(processInstance.getId()).singleResult(); requestContext.setRunAsUser(tenantAdmin); taskBody.put("assignee", user); result = tasksClient.updateTask(task.getId(), taskBody, selectedFields); assertEquals("resolved", result.get("state")); assertEquals(initiator, result.get("assignee")); task = activitiProcessEngine.getTaskService().createTaskQuery() .processInstanceId(processInstance.getId()).singleResult(); assertEquals(DelegationState.RESOLVED, task.getDelegationState()); assertEquals(initiator, task.getAssignee()); } finally { cleanupProcessInstance(processInstance); } }
From source file:org.alfresco.rest.workflow.api.tests.TaskWorkflowApiTest.java
@Test public void testGetTaskVariablesAuthentication() throws Exception { RequestContext requestContext = initApiClientWithTestUser(); String initiator = getOtherPersonInNetwork(requestContext.getRunAsUser(), requestContext.getNetworkId()) .getId();//from www.j a v a 2 s. c om // Start process by one user and try to access the task variables as the task assignee instead of the process // initiator to see if the assignee is authorized to get the task ProcessInstance processInstance = startAdhocProcess(initiator, requestContext.getNetworkId(), null); try { Task task = activitiProcessEngine.getTaskService().createTaskQuery() .processInstanceId(processInstance.getId()).singleResult(); assertNotNull(task); TasksClient tasksClient = publicApiClient.tasksClient(); // Try accessing task variables when NOT involved in the task try { tasksClient.findTaskVariables(task.getId()); fail("Exception expected"); } catch (PublicApiException expected) { assertEquals(HttpStatus.FORBIDDEN.value(), expected.getHttpResponse().getStatusCode()); assertErrorSummary("Permission was denied", expected.getHttpResponse()); } // Set assignee, task variables should be accessible now activitiProcessEngine.getTaskService().setAssignee(task.getId(), requestContext.getRunAsUser()); JSONObject jsonObject = tasksClient.findTaskVariables(task.getId()); assertNotNull(jsonObject); // Fetching task variables as admin should be possible String tenantAdmin = AuthenticationUtil.getAdminUserName() + "@" + requestContext.getNetworkId(); publicApiClient.setRequestContext(new RequestContext(TenantUtil.DEFAULT_TENANT, tenantAdmin)); jsonObject = tasksClient.findTaskVariables(task.getId()); assertNotNull(jsonObject); // Fetching the task variables as a admin from another tenant shouldn't be possible TestNetwork anotherNetwork = getOtherNetwork(requestContext.getNetworkId()); tenantAdmin = AuthenticationUtil.getAdminUserName() + "@" + anotherNetwork.getId(); publicApiClient.setRequestContext(new RequestContext(TenantUtil.DEFAULT_TENANT, tenantAdmin)); try { tasksClient.findTaskVariables(task.getId()); fail("Exception expected"); } catch (PublicApiException expected) { assertEquals(HttpStatus.FORBIDDEN.value(), expected.getHttpResponse().getStatusCode()); assertErrorSummary("Permission was denied", expected.getHttpResponse()); } } finally { cleanupProcessInstance(processInstance); } }
From source file:org.alfresco.rest.workflow.api.tests.TaskWorkflowApiTest.java
@Test @SuppressWarnings("unchecked") public void testUpdateTaskVariablesAuthentication() throws Exception { RequestContext requestContext = initApiClientWithTestUser(); String initiator = getOtherPersonInNetwork(requestContext.getRunAsUser(), requestContext.getNetworkId()) .getId();//from w ww.ja v a 2s .c om // Start process by one user and try to access the task variables as the task assignee instead of the process // initiator to see if the assignee is authorized to get the task ProcessInstance processInstance = startAdhocProcess(initiator, requestContext.getNetworkId(), null); try { JSONObject variableBody = new JSONObject(); variableBody.put("name", "newVariable"); variableBody.put("value", 1234); variableBody.put("scope", "global"); Task task = activitiProcessEngine.getTaskService().createTaskQuery() .processInstanceId(processInstance.getId()).singleResult(); assertNotNull(task); TasksClient tasksClient = publicApiClient.tasksClient(); // Try updating task variables when NOT involved in the task try { tasksClient.updateTaskVariable(task.getId(), "newVariable", variableBody); fail("Exception expected"); } catch (PublicApiException expected) { assertEquals(HttpStatus.FORBIDDEN.value(), expected.getHttpResponse().getStatusCode()); assertErrorSummary("Permission was denied", expected.getHttpResponse()); } // Set assignee, task variables should be updatable now activitiProcessEngine.getTaskService().setAssignee(task.getId(), requestContext.getRunAsUser()); JSONObject jsonObject = tasksClient.updateTaskVariable(task.getId(), "newVariable", variableBody); assertNotNull(jsonObject); // Updating task variables as admin should be possible String tenantAdmin = AuthenticationUtil.getAdminUserName() + "@" + requestContext.getNetworkId(); publicApiClient.setRequestContext(new RequestContext(TenantUtil.DEFAULT_TENANT, tenantAdmin)); jsonObject = tasksClient.updateTaskVariable(task.getId(), "newVariable", variableBody); assertNotNull(jsonObject); // Updating the task variables as a admin from another tenant shouldn't be possible TestNetwork anotherNetwork = getOtherNetwork(requestContext.getNetworkId()); tenantAdmin = AuthenticationUtil.getAdminUserName() + "@" + anotherNetwork.getId(); publicApiClient.setRequestContext(new RequestContext(TenantUtil.DEFAULT_TENANT, tenantAdmin)); try { jsonObject = tasksClient.updateTaskVariable(task.getId(), "newVariable", variableBody); fail("Exception expected"); } catch (PublicApiException expected) { assertEquals(HttpStatus.FORBIDDEN.value(), expected.getHttpResponse().getStatusCode()); assertErrorSummary("Permission was denied", expected.getHttpResponse()); } } finally { cleanupProcessInstance(processInstance); } }
From source file:org.alfresco.rest.workflow.api.tests.TaskWorkflowApiTest.java
@Test public void testDeleteTaskVariableAuthentication() throws Exception { RequestContext requestContext = initApiClientWithTestUser(); String initiator = getOtherPersonInNetwork(requestContext.getRunAsUser(), requestContext.getNetworkId()) .getId();//from w w w . ja v a 2s.c om // Start process by one user and try to access the task variables as the task assignee instead of the process // initiator to see if the assignee is authorized to get the task ProcessInstance processInstance = startAdhocProcess(initiator, requestContext.getNetworkId(), null); try { Task task = activitiProcessEngine.getTaskService().createTaskQuery() .processInstanceId(processInstance.getId()).singleResult(); assertNotNull(task); TasksClient tasksClient = publicApiClient.tasksClient(); activitiProcessEngine.getTaskService().setVariableLocal(task.getId(), "existingVariable", "Value"); // Try updating task variables when NOT involved in the task try { tasksClient.deleteTaskVariable(task.getId(), "existingVariable"); fail("Exception expected"); } catch (PublicApiException expected) { assertEquals(HttpStatus.FORBIDDEN.value(), expected.getHttpResponse().getStatusCode()); assertErrorSummary("Permission was denied", expected.getHttpResponse()); } assertTrue(activitiProcessEngine.getTaskService().hasVariableLocal(task.getId(), "existingVariable")); // Set assignee, task variables should be updatable now activitiProcessEngine.getTaskService().setAssignee(task.getId(), requestContext.getRunAsUser()); tasksClient.deleteTaskVariable(task.getId(), "existingVariable"); assertFalse(activitiProcessEngine.getTaskService().hasVariableLocal(task.getId(), "existingVariable")); activitiProcessEngine.getTaskService().setVariableLocal(task.getId(), "existingVariable", "Value"); // Updating task variables as admin should be possible String tenantAdmin = AuthenticationUtil.getAdminUserName() + "@" + requestContext.getNetworkId(); publicApiClient.setRequestContext(new RequestContext(TenantUtil.DEFAULT_TENANT, tenantAdmin)); tasksClient.deleteTaskVariable(task.getId(), "existingVariable"); assertFalse(activitiProcessEngine.getTaskService().hasVariableLocal(task.getId(), "existingVariable")); activitiProcessEngine.getTaskService().setVariableLocal(task.getId(), "existingVariable", "Value"); // Updating the task variables as a admin from another tenant shouldn't be possible TestNetwork anotherNetwork = getOtherNetwork(requestContext.getNetworkId()); tenantAdmin = AuthenticationUtil.getAdminUserName() + "@" + anotherNetwork.getId(); publicApiClient.setRequestContext(new RequestContext(TenantUtil.DEFAULT_TENANT, tenantAdmin)); try { tasksClient.deleteTaskVariable(task.getId(), "existingVariable"); fail("Exception expected"); } catch (PublicApiException expected) { assertEquals(HttpStatus.FORBIDDEN.value(), expected.getHttpResponse().getStatusCode()); assertErrorSummary("Permission was denied", expected.getHttpResponse()); } } finally { cleanupProcessInstance(processInstance); } }
From source file:org.apache.kylin.rest.controller.BasicController.java
@ResponseStatus(HttpStatus.FORBIDDEN) @ExceptionHandler(ForbiddenException.class) @ResponseBody//from w ww . j a va2 s . c o m ErrorResponse handleForbidden(HttpServletRequest req, Exception ex) { return new ErrorResponse(req.getRequestURL().toString(), ex); }
From source file:org.apereo.portal.rest.oauth.OidcUserInfoController.java
/** * Obtain an OIDC Id token for the specified <code>client_id</code>. At least one bean of type * {@link OAuthClient} is required to use this endpoint. * * <p>This token strategy supports Spring's <code>OAuth2RestTemplate</code> for accessing * uPortal REST APIs from external systems. Use a <code>ClientCredentialsResourceDetails</code> * with <code>clientAuthenticationScheme=AuthenticationScheme.form</code>, together with a * <code>ClientCredentialsAccessTokenProvider</code>. * * @since 5.5/*from w w w .j a va2 s . c o m*/ */ @PostMapping(value = TOKEN_ENDPOINT_URI, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity oauthToken(@RequestParam(value = "client_id") String clientId, @RequestParam(value = "client_secret") String clientSecret, @RequestParam(value = "grant_type", required = false, defaultValue = "client_credentials") String grantType, @RequestParam(value = "scope", required = false, defaultValue = "/all") String scope, @RequestParam(value = "claims", required = false) String claims, @RequestParam(value = "groups", required = false) String groups) { /* * NB: Several of this method's parameters are not consumed (yet) in any way. They are * defined to match a two-legged OAuth strategy and for future use. */ final String msg = "Processing request for OAuth access token; client_id='{}', client_secret='{}', " + "grant_type='{}', scope='{}', claims='{}', groups='{}'"; logger.debug(msg, clientId, StringUtils.repeat("*", clientSecret.length()), grantType, scope, claims, groups); // STEP 1: identify the client final OAuthClient oAuthClient = clientMap.get(clientId); if (oAuthClient == null) { return ResponseEntity.status(HttpStatus.FORBIDDEN) .body(Collections.singletonMap("message", "client_id not found")); } logger.debug("Selected known OAuthClient with client_id='{}' for access token request", oAuthClient.getClientId()); // STEP 2: validate the client_secret if (!oAuthClient.getClientSecret().equals(clientSecret)) { return ResponseEntity.status(HttpStatus.FORBIDDEN) .body(Collections.singletonMap("message", "authentication failed")); } // STEP 3: obtain the specified user final IPerson person = personService.getPerson(oAuthClient.getPortalUserAccount()); if (person == null) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Collections.singletonMap("message", "portal user account not found: " + oAuthClient.getPortalUserAccount())); } logger.debug("Selected portal Person with username='{}' for client_id='{}'", person.getUserName(), oAuthClient.getClientId()); // STEP 4: build a standard OAuth2 access token response final String token = createToken(person, claims, groups); final Map<String, Object> rslt = new HashMap<>(); rslt.put("access_token", token); rslt.put("token_type", "bearer"); rslt.put("expires_in", timeoutSeconds > 2 ? timeoutSeconds - 2L /* fudge factor */ : timeoutSeconds); rslt.put("scope", scope); logger.debug("Produced the following access token for client_id='{}': {}", oAuthClient.getClientId(), rslt); return ResponseEntity.ok(rslt); }
From source file:org.cloudfoundry.identity.uaa.authentication.login.RemoteAuthenticationEndpoint.java
@RequestMapping(value = { "/authenticate" }, method = RequestMethod.POST) @ResponseBody//from ww w. j a v a 2 s.c o m public HttpEntity<Map<String, String>> authenticate(HttpServletRequest request, @RequestParam(value = "username", required = true) String username, @RequestParam(value = "password", required = true) String password) { Map<String, String> responseBody = new HashMap<>(); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password); token.setDetails(new UaaAuthenticationDetails(request)); HttpStatus status = HttpStatus.UNAUTHORIZED; try { Authentication a = authenticationManager.authenticate(token); responseBody.put("username", a.getName()); if (a.getPrincipal() != null && a.getPrincipal() instanceof UaaPrincipal) { responseBody.put("email", ((UaaPrincipal) a.getPrincipal()).getEmail()); } processAdditionalInformation(responseBody, a); status = HttpStatus.OK; } catch (AccountNotVerifiedException e) { responseBody.put("error", "account not verified"); status = HttpStatus.FORBIDDEN; } catch (AuthenticationException e) { responseBody.put("error", "authentication failed"); } catch (Exception e) { logger.debug("Failed to authenticate user ", e); responseBody.put("error", "error"); status = HttpStatus.INTERNAL_SERVER_ERROR; } return new ResponseEntity<>(responseBody, status); }
From source file:org.cloudfoundry.identity.uaa.authentication.RemoteAuthenticationEndpoint.java
@RequestMapping(value = { "/authenticate" }, method = RequestMethod.POST) @ResponseBody/*from w w w . jav a 2 s .c om*/ public HttpEntity<AuthenticationResponse> authenticate(HttpServletRequest request, @RequestParam(value = "username", required = true) String username, @RequestParam(value = "password", required = true) String password) { AuthenticationResponse response = new AuthenticationResponse(); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password); token.setDetails(new UaaAuthenticationDetails(request)); HttpStatus status = HttpStatus.UNAUTHORIZED; try { Authentication a = authenticationManager.authenticate(token); response.setUsername(a.getName()); if (a.getPrincipal() != null && a.getPrincipal() instanceof UaaPrincipal) { response.setEmail(((UaaPrincipal) a.getPrincipal()).getEmail()); } processAdditionalInformation(response, a); status = HttpStatus.OK; } catch (AccountNotVerifiedException e) { response.setError("account not verified"); status = HttpStatus.FORBIDDEN; } catch (AuthenticationException e) { response.setError("authentication failed"); } catch (Exception e) { logger.debug("Failed to authenticate user ", e); response.setError("error"); status = HttpStatus.INTERNAL_SERVER_ERROR; } return new ResponseEntity<>(response, status); }