List of usage examples for org.springframework.security.core.context SecurityContext setAuthentication
void setAuthentication(Authentication authentication);
From source file:de.hybris.platform.assistedservicestorefront.security.impl.DefaultAssistedServiceAgentAuthoritiesManager.java
/** * Update the agent authentication token with new authorities. * * @param authorities/*from w w w. j av a 2 s . co m*/ * The new list of authorities. Be aware that existent authorities will be removed. */ protected void updateAuthentication(final Collection<? extends GrantedAuthority> authorities) { final SecurityContext context = SecurityContextHolder.getContext(); final AssistedServiceAuthenticationToken currentAuth = (AssistedServiceAuthenticationToken) context .getAuthentication(); final AssistedServiceAgentPrincipal principal = (AssistedServiceAgentPrincipal) currentAuth.getPrincipal(); final AssistedServiceAuthenticationToken updatedAuth = new AssistedServiceAuthenticationToken(principal, authorities); updatedAuth.setDetails(currentAuth.getDetails()); updatedAuth.setEmulating(currentAuth.isEmulating()); context.setAuthentication(updatedAuth); }
From source file:org.alfresco.jive.community.ws.AlfrescoServiceImpl.java
@Override public EntityCollection<SpaceEntity> getSpaces(int offset, int limit, String user) { SecurityContext sc = SecurityContextHolder.getContext(); Authentication auth = sc.getAuthentication(); try {/* w w w .j a v a2s . co m*/ log.info("User " + user); User jiveUser = userManager.getUser(encrypter.decrypt(user)); log.info("User Jive" + jiveUser); sc.setAuthentication(new JiveUserAuthentication(jiveUser)); return EntityCollection.create(getSubSpaces(rootSpace, offset, limit)); } catch (CannotDecryptException e) { e.printStackTrace(); throw OpenClientErrorBuilder.forbidden("Cannot decrypt user value"); } catch (UserNotFoundException e) { e.printStackTrace(); throw OpenClientErrorBuilder.forbidden("No user specified or specified user does not exist"); } finally { sc.setAuthentication(auth); } }
From source file:org.alfresco.jive.community.ws.AlfrescoServiceImpl.java
@Override public Response updateDocument(String contentType, int size, String fileName, String cmisId, String user) { SecurityContext sc = SecurityContextHolder.getContext(); Authentication auth = sc.getAuthentication(); try {/* w w w.ja va2 s. com*/ User jiveUser = userManager.getUser(encrypter.decrypt(user)); sc = SecurityContextHolder.getContext(); sc.setAuthentication(new JiveUserAuthentication(jiveUser)); // Retrieve existing managed document long documentId = alfrescoNavigationManager.getJiveId(cmisId); Document document = documentManager.getDocument(documentId); document.setSubject(fileName); // Associate managed document with external content CmisDocument cmisDocument = (CmisDocument) ((DocumentProxy) document).getUnproxiedObject(); try { cmisDocument.setLinkedBinaryBody(cmisId, fileName, contentType, size); } catch (BinaryBodyException e) { switch (e.getErrorType()) { case BinaryBodyException.TOO_LARGE: { throw OpenClientErrorBuilder.conflict(BinaryBodyException.TOO_LARGE, "The document is too large or has a file name longer than 256 characters"); } case BinaryBodyException.BAD_CONTENT_TYPE: { throw OpenClientErrorBuilder .internalServerError("The content type of this document is not allowed"); } default: { throw OpenClientErrorBuilder.internalServerError("There was an error creating your document"); } } } cmisDocument.save(false, true); // Create response EntityReference<DocumentEntity> documentEntityReference = ObjectEntityReference.create(cmisDocument, createEntity(cmisDocument)); String documentUrl = JiveResourceResolver.getJiveObjectURL(cmisDocument, true); URI documentUri; try { documentUri = new URI(documentUrl); } catch (URISyntaxException e) { throw OpenClientErrorBuilder.internalServerError(OpenClientErrorBuilder.ERROR_CODE_UNKOWN, "URISyntaxException was thrown"); } return Response.created(documentUri).entity(documentEntityReference.getEntity()).build(); } catch (CannotDecryptException e) { throw OpenClientErrorBuilder.forbidden("Cannot decrypt user value"); } catch (UserNotFoundException e) { throw OpenClientErrorBuilder.forbidden("No user specified or specified user does not exist"); } catch (DocumentObjectNotFoundException e) { throw OpenClientErrorBuilder.internalServerError( OpenClientErrorBuilder.ERROR_CODE_OBJECT_TYPE_NOT_FOUND, "Document type for managed documents not found"); } catch (UnauthorizedException e) { throw OpenClientErrorBuilder.unauthorized(); } catch (DocumentAlreadyExistsException e) { throw OpenClientErrorBuilder.duplicateDocumentId(); } finally { sc.setAuthentication(auth); } }
From source file:de.iew.web.utils.WebAutoLogin.java
public void autoLogin(UserDetails userDetails, HttpServletRequest request) { SecurityContext securityContext = SecurityContextHolder.getContext(); HttpSession session = request.getSession(true); session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, securityContext); try {// w w w. j a v a 2 s .c om // @TODO Das funktioniert so nicht direkt. Habe es ohne Passwort Angabe nicht hinbekommen. UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( userDetails.getUsername(), "test", userDetails.getAuthorities()); token.setDetails(new WebAuthenticationDetails(request)); Authentication authentication = this.authenticationManager.authenticate(token); securityContext.setAuthentication(authentication); } catch (Exception e) { if (log.isInfoEnabled()) { log.info("Fehler whrend des Einlog-Versuchs.", e); } securityContext.setAuthentication(null); } }
From source file:fr.treeptik.cloudunit.snapshot.AbstractSnapshotControllerTestIT.java
@Before public void setup() { logger.info("setup"); this.mockMvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build(); User user = null;//ww w . java 2 s .co m try { user = userService.findByLogin("johndoe"); } catch (ServiceException e) { logger.error(e.getLocalizedMessage()); } Authentication authentication = new UsernamePasswordAuthenticationToken(user.getLogin(), user.getPassword()); Authentication result = authenticationManager.authenticate(authentication); SecurityContext securityContext = SecurityContextHolder.getContext(); securityContext.setAuthentication(result); session = new MockHttpSession(); session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, securityContext); }
From source file:org.alfresco.jive.community.ws.legacy.AlfrescoService.java
@POST @Path("/spaces/{id}/documents") public Response createDocument(@PathParam("id") long id, @FormParam(PARAM_MIME_TYPE) String contentType, @FormParam(PARAM_SIZE) int size, @FormParam(PARAM_FILENAME) String fileName, @FormParam(PARAM_CMIS_ID) String cmisId, @HeaderParam(PARAM_USER) String user) { SecurityContext sc = SecurityContextHolder.getContext(); Authentication auth = sc.getAuthentication(); try {// w w w . j av a 2 s . co m User jiveUser = userManager.getUser(encrypter.decrypt(user)); if (jiveUser == null || jiveUser.isAnonymous()) { throw OpenClientErrorBuilder.forbidden("No user specified or specified user does not exist"); } sc = SecurityContextHolder.getContext(); sc.setAuthentication(new JiveUserAuthentication(jiveUser)); // Create a managed document Document document = documentManager.createDocument(jiveUser, jiveContext.getDocumentTypeManager().getDocumentType(ConnectorConstants.MANAGED_TYPE), null, fileName, new String()); document.setDocumentState(DocumentState.PUBLISHED); documentManager.addDocument(getContainer(id), document, Collections.emptyMap()); // Associate managed document with external content CmisDocument cmisDocument = (CmisDocument) ((DocumentProxy) document).getUnproxiedObject(); try { cmisDocument.setLinkedBinaryBody(cmisId, fileName, contentType, size); } catch (BinaryBodyException e) { switch (e.getErrorType()) { case BinaryBodyException.TOO_LARGE: { throw OpenClientErrorBuilder.conflict(BinaryBodyException.TOO_LARGE, "The document is too large or has a file name longer than 256 characters"); } case BinaryBodyException.BAD_CONTENT_TYPE: { throw OpenClientErrorBuilder .internalServerError("The content type of this document is not allowed"); } default: { throw OpenClientErrorBuilder.internalServerError("There was an error creating your document"); } } } cmisDocument.save(false, true); // Create response EntityReference<DocumentEntity> documentEntityReference = ObjectEntityReference.create(cmisDocument, entityConverter.apply(cmisDocument)); URI documentUri = EntityHelper.getSelfLink(documentEntityReference.getEntity()); return Response.created(documentUri).entity(documentEntityReference.getEntity()).build(); } catch (CannotDecryptException e) { throw OpenClientErrorBuilder.forbidden("Cannot decrypt user value"); } catch (UserNotFoundException e) { throw OpenClientErrorBuilder.forbidden("No user specified or specified user does not exist"); } catch (UnauthorizedException e) { throw OpenClientErrorBuilder.unauthorized(); } catch (DuplicateIDException e) { throw OpenClientErrorBuilder.duplicateDocumentId(); } catch (DocumentObjectNotFoundException e) { throw OpenClientErrorBuilder.internalServerError( OpenClientErrorBuilder.ERROR_CODE_OBJECT_TYPE_NOT_FOUND, "Document type for managed documents not found"); } catch (RejectedException e) { throw OpenClientErrorBuilder.internalServerError(OpenClientErrorBuilder.ERROR_CODE_UNKOWN, "RejectedException was thrown"); } catch (DocumentAlreadyExistsException e) { throw OpenClientErrorBuilder.duplicateDocumentId(); } finally { sc.setAuthentication(auth); } }
From source file:org.geonode.security.GeoNodeAnonymousProcessingFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final SecurityContext securityContext = SecurityContextHolder.getContext(); final Authentication existingAuth = securityContext.getAuthentication(); final boolean authenticationRequired = existingAuth == null || !existingAuth.isAuthenticated(); if (authenticationRequired) { try {/*from ww w .j ava 2 s . c o m*/ Object principal = existingAuth == null ? null : existingAuth.getPrincipal(); Collection<? extends GrantedAuthority> authorities = existingAuth == null ? null : existingAuth.getAuthorities(); Authentication authRequest = new AnonymousGeoNodeAuthenticationToken(principal, authorities); final Authentication authResult = getSecurityManager().authenticate(authRequest); securityContext.setAuthentication(authResult); LOGGER.finer("GeoNode Anonymous filter kicked in."); } catch (AuthenticationException e) { // we just go ahead and fall back on basic authentication LOGGER.log(Level.WARNING, "Error connecting to the GeoNode server for authentication purposes", e); } } // move forward along the chain chain.doFilter(request, response); }
From source file:org.alfresco.jive.community.ws.AlfrescoServiceImpl.java
@Override public Response createDocument(long id, String contentType, int size, String fileName, String cmisId, String user) {//from www . ja v a 2s . co m SecurityContext sc = SecurityContextHolder.getContext(); Authentication auth = sc.getAuthentication(); try { User jiveUser = userManager.getUser(encrypter.decrypt(user)); if (jiveUser == null || jiveUser.isAnonymous()) { throw OpenClientErrorBuilder.forbidden("No user specified or specified user does not exist"); } sc = SecurityContextHolder.getContext(); sc.setAuthentication(new JiveUserAuthentication(jiveUser)); // Create a managed document Document document = documentManager .createDocument( jiveUser, JiveApplication.getEffectiveContext().getDocumentTypeManager() .getDocumentType(ConnectorConstants.MANAGED_TYPE), null, fileName, new String()); Community community = null; try { community = communityManager.getCommunity(id); } catch (CommunityNotFoundException e1) { throw OpenClientErrorBuilder.internalServerError("Community not found"); } // Associate managed document with external content CmisDocument cmisDocument = (CmisDocument) ((DocumentProxy) document).getUnproxiedObject(); try { cmisDocument.setLinkedBinaryBody(cmisId, fileName, contentType, size); } catch (BinaryBodyException e) { switch (e.getErrorType()) { case BinaryBodyException.TOO_LARGE: { throw OpenClientErrorBuilder.conflict(BinaryBodyException.TOO_LARGE, "The document is too large or has a file name longer than 256 characters"); } case BinaryBodyException.BAD_CONTENT_TYPE: { throw OpenClientErrorBuilder .internalServerError("The content type of this document is not allowed"); } default: { throw OpenClientErrorBuilder.internalServerError("There was an error creating your document"); } } } documentManager.addDocument(community, cmisDocument, Collections.emptyMap()); cmisDocument.setDocumentState(DocumentState.PUBLISHED); cmisDocument.save(false, true); // Create response EntityReference<DocumentEntity> documentEntityReference = ObjectEntityReference.create(cmisDocument, createEntity(cmisDocument)); //URI documentUri = EntityHelper.getSelfLink(documentEntityReference.getEntity()); String documentUrl = JiveResourceResolver.getJiveObjectURL(cmisDocument, true); URI documentUri = new URI(documentUrl); return Response.created(documentUri).entity(documentEntityReference.getEntity()).build(); } catch (CannotDecryptException e) { throw OpenClientErrorBuilder.forbidden("Cannot decrypt user value"); } catch (UserNotFoundException e) { throw OpenClientErrorBuilder.forbidden("No user specified or specified user does not exist"); } catch (UnauthorizedException e) { throw OpenClientErrorBuilder.unauthorized(); } catch (DuplicateIDException e) { throw OpenClientErrorBuilder.duplicateDocumentId(); } catch (DocumentObjectNotFoundException e) { throw OpenClientErrorBuilder.internalServerError( OpenClientErrorBuilder.ERROR_CODE_OBJECT_TYPE_NOT_FOUND, "Document type for managed documents not found"); } catch (RejectedException e) { throw OpenClientErrorBuilder.internalServerError(OpenClientErrorBuilder.ERROR_CODE_UNKOWN, "RejectedException was thrown"); } catch (DocumentAlreadyExistsException e) { throw OpenClientErrorBuilder.duplicateDocumentId(); } catch (URISyntaxException e) { throw OpenClientErrorBuilder.internalServerError(OpenClientErrorBuilder.ERROR_CODE_UNKOWN, "URISyntaxException was thrown"); } finally { sc.setAuthentication(auth); } }
From source file:cz.muni.fi.editor.test.service.support.other.TestSecurityContextFactory.java
@Override @Transactional(readOnly = true)// www.ja v a 2 s. co m public SecurityContext createSecurityContext(WithEditorUser withEditorUser) { SecurityContext context = SecurityContextHolder.createEmptyContext(); UserDTO user = new UserDTO(); user.setId(withEditorUser.id()); User dao = new User(); dao.setId(withEditorUser.id()); List<OrganizationDTO> member = organizationDAO.getOrganizationForUser(dao, true).stream().map(o -> { OrganizationDTO dto = new OrganizationDTO(); dto.setId(o.getId()); return dto; }).collect(Collectors.toList()); List<OrganizationDTO> owner = organizationDAO.ownedBy(dao).stream().map(o -> { OrganizationDTO dto = new OrganizationDTO(); dto.setId(o.getId()); return dto; }).collect(Collectors.toList()); user.init(owner, member); Authentication auth = new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities()); context.setAuthentication(auth); return context; }