Example usage for org.springframework.security.core.context SecurityContext getAuthentication

List of usage examples for org.springframework.security.core.context SecurityContext getAuthentication

Introduction

In this page you can find the example usage for org.springframework.security.core.context SecurityContext getAuthentication.

Prototype

Authentication getAuthentication();

Source Link

Document

Obtains the currently authenticated principal, or an authentication request token.

Usage

From source file:org.jasig.springframework.security.portlet.context.PortletSessionSecurityContextRepository.java

@Override
public void saveContext(SecurityContext context, PortletRequestResponseHolder requestResponseHolder) {
    final Authentication authentication = context.getAuthentication();
    final PortletRequest request = requestResponseHolder.getRequest();
    PortletSession portletSession = request.getPortletSession(false);

    // See SEC-776
    if (authentication == null || authenticationTrustResolver.isAnonymous(authentication)) {
        if (logger.isDebugEnabled()) {
            logger.debug(//from w w w.  java  2  s .c o m
                    "SecurityContext is empty or contents are anonymous - context will not be stored in PortletSession.");
        }

        if (portletSession != null) {
            // SEC-1587 A non-anonymous context may still be in the session
            portletSession.removeAttribute(springSecurityContextKey, this.sessionScope);
        }
        return;
    }

    if (portletSession == null) {
        portletSession = createNewSessionIfAllowed(context, requestResponseHolder);
    }

    // If PortletSession exists, store current SecurityContext but only if it has
    // actually changed in this thread (see SEC-37, SEC-1307, SEC-1528)
    if (portletSession != null) {
        // We may have a new session, so check also whether the context attribute is set SEC-1561
        if (contextChanged(context, requestResponseHolder)
                || portletSession.getAttribute(springSecurityContextKey, this.sessionScope) == null) {
            portletSession.setAttribute(springSecurityContextKey, context, this.sessionScope);

            if (logger.isDebugEnabled()) {
                logger.debug("SecurityContext stored to PortletSession: '" + context + "'");
            }
        }
    }
}

From source file:com.devnexus.ting.web.controller.admin.AdminController.java

@RequestMapping("/s/logout")
public String logout(RedirectAttributes redirectAttributes) {

    final SecurityContext context = SecurityContextHolder.getContext();

    if (context.getAuthentication() != null) {
        LOGGER.info("Logging out user..." + context.getAuthentication().getName());
    } else {//from   ww  w .j  av a2s .c om
        LOGGER.warn("User not logged in.");
    }

    context.setAuthentication(null);
    redirectAttributes.addFlashAttribute("succesMessage", "You logged out successfully.");

    return "/s/index";
}

From source file:org.jasig.springframework.security.portlet.context.PortletSessionSecurityContextRepository.java

private boolean contextChanged(SecurityContext context, PortletRequestResponseHolder requestResponseHolder) {
    return context != requestResponseHolder.getContextBeforeExecution()
            || context.getAuthentication() != requestResponseHolder.getAuthBeforeExecution();
}

From source file:edu.zipcloud.cloudstreetmarket.core.services.CommunityServiceImpl.java

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

    User user = userRepository.findOne(username);
    Authentication auth;//from w  ww.  j av  a  2 s  .c o m

    if (user != null) {
        return user;
    }

    SecurityContext securityContext = SecurityContextHolder.getContext();
    if (securityContext != null) {
        auth = securityContext.getAuthentication();
        if (auth != null) {
            Object principal = auth.getPrincipal();
            if (principal instanceof User) {
                return (User) principal;
            }
        }
    }

    //fallback
    throw new ResourceAccessException("No found user for username: " + username);
}

From source file:org.alfresco.jive.community.ws.legacy.AlfrescoService.java

@PUT
@Path("/documents")
public Response updateDocument(@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 {// ww  w  .  ja v a  2s.  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,
                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 (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:net.shibboleth.idp.oidc.flow.PreAuthorizeUserApprovalAction.java

/**
 * Gets user info claims for scopes./* w w  w  .  java 2 s . co  m*/
 *
 * @param sortedScopes the sorted scopes
 * @return the user info claims for scopes
 */
private Map<String, Map<String, String>> getUserInfoClaimsForScopes(final Set<SystemScope> sortedScopes) {

    final SecurityContext securityContext = SecurityContextHolder.getContext();
    final Authentication authentication = securityContext.getAuthentication();
    final SubjectContext context = (SubjectContext) authentication.getPrincipal();

    final UserInfo user = userInfoService.getByUsername(context.getPrincipalName());
    log.debug("Located UserInfo object from principal name {}", context.getPrincipalName());

    final Map<String, Map<String, String>> claimsForScopes = new HashMap<>();
    if (user != null) {
        final JsonObject userJson = user.toJson();
        log.debug("UserInfo translated to JSON is:\n{}", userJson);

        for (final SystemScope systemScope : sortedScopes) {
            final Map<String, String> claimValues = new HashMap<>();

            final Set<String> claims = scopeClaimTranslationService.getClaimsForScope(systemScope.getValue());
            log.debug("Processing system scope {} for the following claims: {}", systemScope.getValue(),
                    claims);
            for (final String claim : claims) {
                final JsonElement element = userJson.get(claim);
                if (userJson.has(claim) && element.isJsonPrimitive()) {
                    claimValues.put(claim, element.getAsString());
                    log.debug("Added claim {} with value {}", claim, element.getAsString());
                }
            }
            log.debug("Final claims for system scope {} are", systemScope.getValue(), claimValues);
            claimsForScopes.put(systemScope.getValue(), claimValues);
        }
    }
    return claimsForScopes;
}

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 {// ww w. ja va  2 s .c  o  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.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  a 2s .  c o  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 EntityCollection<SpaceEntity> getSubSpaces(long id, int offset, int limit, String user) {
    SecurityContext sc = SecurityContextHolder.getContext();
    Authentication auth = sc.getAuthentication();

    try {// w  w  w .ja v a  2s  . c o  m
        User jiveUser = userManager.getUser(encrypter.decrypt(user));
        sc.setAuthentication(new JiveUserAuthentication(jiveUser));

        Community parentSpace = communityManager.getCommunity(id);

        return EntityCollection.create(getSubSpaces(parentSpace, offset, limit));

    } 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 (CommunityNotFoundException e) {
        throw OpenClientErrorBuilder.notFound(-1, "Community with id " + id + " not found");
    } catch (UnauthorizedException e) {
        OpenClientErrorBuilder.unauthorized();
    } finally {
        sc.setAuthentication(auth);
    }
    return EntityCollection.create(Collections.EMPTY_LIST);
}

From source file:alpha.portal.webapp.controller.UserFormController.java

/**
 * Show form./*from w w  w  .  j a  v a 2  s .  c om*/
 * 
 * @param request
 *            the request
 * @param response
 *            the response
 * @return the model and view
 * @throws Exception
 *             the exception
 */
@ModelAttribute
@RequestMapping(method = { RequestMethod.GET, RequestMethod.POST })
protected ModelAndView showForm(final HttpServletRequest request, final HttpServletResponse response)
        throws Exception {

    final ModelAndView model = new ModelAndView();
    User user;

    // If not an administrator, make sure user is not trying to add or edit
    // another user
    if (!request.isUserInRole(Constants.ADMIN_ROLE) && !this.isFormSubmission(request)) {
        if (this.isAdd(request) || (request.getParameter("id") != null)) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            this.log.warn("User '" + request.getRemoteUser() + "' is trying to edit user with id '"
                    + request.getParameter("id") + "'");

            throw new AccessDeniedException("You do not have permission to modify other users.");
        }
    }

    if (!this.isFormSubmission(request)) {
        final String userId = request.getParameter("id");

        // if user logged in with remember me, display a warning that they
        // can't change passwords
        this.log.debug("checking for remember me login...");

        final AuthenticationTrustResolver resolver = new AuthenticationTrustResolverImpl();
        final SecurityContext ctx = SecurityContextHolder.getContext();

        if (ctx.getAuthentication() != null) {
            final Authentication auth = ctx.getAuthentication();

            if (resolver.isRememberMe(auth)) {
                request.getSession().setAttribute("cookieLogin", "true");

                // add warning message
                this.saveMessage(request, this.getText("userProfile.cookieLogin", request.getLocale()));
            }
        }

        if ((userId == null) && !this.isAdd(request)) {
            user = this.getUserManager().getUserByUsername(request.getRemoteUser());
        } else if (!StringUtils.isBlank(userId) && !"".equals(request.getParameter("version"))) {
            user = this.getUserManager().getUser(userId);
        } else {
            user = new User();
            user.addRole(new Role(Constants.USER_ROLE));
        }

        user.setConfirmPassword(user.getPassword());

        UserExtension userExtension;
        final Long uId = user.getId();
        if ((uId != null) && this.userExtensionManager.exists(uId)) {
            userExtension = this.userExtensionManager.get(uId);
        } else {
            userExtension = new UserExtension(user);
        }

        model.addObject("userExtension", userExtension);
        model.addObject("contributorRoles", this.contributorRoleManager.getAll());

    } else {
        // populate user object from database, so all fields don't need to
        // be hidden fields in form
        user = this.getUserManager().getUser(request.getParameter("id"));
    }

    model.addObject("user", user);

    return model;
}