Example usage for org.springframework.security.core Authentication getName

List of usage examples for org.springframework.security.core Authentication getName

Introduction

In this page you can find the example usage for org.springframework.security.core Authentication getName.

Prototype

public String getName();

Source Link

Document

Returns the name of this principal.

Usage

From source file:org.jasig.portlet.blackboardvcportlet.security.ConferenceUserPreAuthenticatedGrantedAuthoritiesUserDetailsService.java

@Override
protected UserDetails createuserDetails(Authentication token,
        Collection<? extends GrantedAuthority> authorities) {
    final PortletAuthenticationDetails authenticationDetails = (PortletAuthenticationDetails) token
            .getDetails();/*from   www  .  j a va  2  s .  c  om*/

    final ConferenceUser conferenceUser = this.setupConferenceUser(authenticationDetails);

    return new ConferenceSecurityUser(token.getName(), conferenceUser, authorities);
}

From source file:com.amediamanager.controller.VideoController.java

@RequestMapping(value = "/tags/{tagId}", method = RequestMethod.GET)
public String tags(ModelMap model, @PathVariable String tagId) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    List<Video> videos = new ArrayList<Video>();
    List<TagCount> tags = new ArrayList<TagCount>();
    try {// w w w .  java 2  s. co m
        // Get user's videos and tags
        videos = tagService.getVideosForUserByTag(auth.getName(), tagId);
        tags = tagService.getTagsForUser(auth.getName());

        // Add expiring URLs (1 hour)
        videos = videoService.generateExpiringUrls(videos, 1000 * 60 * 60);
    } catch (Exception e) {
        return "redirect:/config";
    }
    model.addAttribute("selectedTag", tagId);
    model.addAttribute("tags", tags);
    model.addAttribute("videos", videos);
    model.addAttribute("templateName", "only_videos");
    return "base";
}

From source file:org.cloudfoundry.identity.uaa.authentication.manager.LoginAuthenticationFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {

    final boolean debug = logger.isDebugEnabled();
    final HttpServletRequest request = (HttpServletRequest) req;
    final HttpServletResponse response = (HttpServletResponse) res;

    try {//from  w  w w .j a  v  a 2s  . c  o m
        Authentication credentials = extractCredentials(request);

        if (credentials != null) {

            if (debug) {
                logger.debug("Authentication credentials found for '" + credentials.getName() + "'");
            }

            Authentication authResult = authenticationManager.authenticate(credentials);

            if (debug) {
                logger.debug("Authentication success: " + authResult.getName());
            }

            Authentication requestingPrincipal = SecurityContextHolder.getContext().getAuthentication();
            if (requestingPrincipal == null) {
                throw new BadCredentialsException(
                        "No client authentication found. Remember to put a filter upstream of the LoginAuthenticationFilter.");
            }

            String clientId = request.getParameter("client_id");
            if (null == clientId) {
                logger.error("No client_id in the request");
                throw new BadCredentialsException("No client_id in the request");
            }

            // Check that the client exists
            ClientDetails authenticatingClient = clientDetailsService.loadClientByClientId(clientId);
            if (authenticatingClient == null) {
                throw new BadCredentialsException("No client " + clientId + " found");
            }

            DefaultAuthorizationRequest authorizationRequest = new DefaultAuthorizationRequest(
                    getSingleValueMap(request), null, authenticatingClient.getClientId(), getScope(request));
            if (requestingPrincipal.isAuthenticated()) {
                // Ensure the OAuth2Authentication is authenticated
                authorizationRequest.setApproved(true);
            }

            SecurityContextHolder.getContext()
                    .setAuthentication(new OAuth2Authentication(authorizationRequest, authResult));

            onSuccessfulAuthentication(request, response, authResult);

        }

    } catch (AuthenticationException failed) {
        SecurityContextHolder.clearContext();

        if (debug) {
            logger.debug("Authentication request for failed: " + failed);
        }

        onUnsuccessfulAuthentication(request, response, failed);

        authenticationEntryPoint.commence(request, response, failed);

        return;
    }

    chain.doFilter(request, response);
}

From source file:org.mitre.openid.connect.token.TofuUserApprovalHandler.java

/**
 * Check if the user has already stored a positive approval decision for this site; or if the
 * site is whitelisted, approve it automatically.
 * // www. jav  a 2s. c o  m
 * Otherwise the user will be directed to the approval page and can make their own decision.
 * 
 * @param authorizationRequest   the incoming authorization request
 * @param userAuthentication   the Principal representing the currently-logged-in user
 * 
 * @return                   the updated AuthorizationRequest
 */
@Override
public AuthorizationRequest checkForPreApproval(AuthorizationRequest authorizationRequest,
        Authentication userAuthentication) {

    //First, check database to see if the user identified by the userAuthentication has stored an approval decision

    String userId = userAuthentication.getName();
    String clientId = authorizationRequest.getClientId();

    //lookup ApprovedSites by userId and clientId
    boolean alreadyApproved = false;

    // find out if we're supposed to force a prompt on the user or not
    String prompt = (String) authorizationRequest.getExtensions().get(PROMPT);
    List<String> prompts = Splitter.on(PROMPT_SEPARATOR).splitToList(Strings.nullToEmpty(prompt));
    if (!prompts.contains(PROMPT_CONSENT)) {
        // if the prompt parameter is set to "consent" then we can't use approved sites or whitelisted sites
        // otherwise, we need to check them below

        Collection<ApprovedSite> aps = approvedSiteService.getByClientIdAndUserId(clientId, userId);
        for (ApprovedSite ap : aps) {

            if (!ap.isExpired()) {

                // if we find one that fits...
                if (systemScopes.scopesMatch(ap.getAllowedScopes(), authorizationRequest.getScope())) {

                    //We have a match; update the access date on the AP entry and return true.
                    ap.setAccessDate(new Date());
                    approvedSiteService.save(ap);

                    String apId = ap.getId().toString();
                    authorizationRequest.getExtensions().put(APPROVED_SITE, apId);
                    authorizationRequest.setApproved(true);
                    alreadyApproved = true;

                    setAuthTime(authorizationRequest);
                }
            }
        }

        if (!alreadyApproved) {
            WhitelistedSite ws = whitelistedSiteService.getByClientId(clientId);
            if (ws != null
                    && systemScopes.scopesMatch(ws.getAllowedScopes(), authorizationRequest.getScope())) {
                authorizationRequest.setApproved(true);

                setAuthTime(authorizationRequest);
            }
        }
    }

    return authorizationRequest;

}

From source file:org.mitre.uma.web.PolicyAPI.java

/**
 * List all resource sets for the current user
 * @param m/*from w  w  w  .j a v  a  2 s .  c o  m*/
 * @param auth
 * @return
 */
@RequestMapping(value = "", method = RequestMethod.GET, produces = MimeTypeUtils.APPLICATION_JSON_VALUE)
public String getResourceSetsForCurrentUser(Model m, Authentication auth) {

    Collection<ResourceSet> resourceSets = resourceSetService.getAllForOwner(auth.getName());

    m.addAttribute(JsonEntityView.ENTITY, resourceSets);

    return JsonEntityView.VIEWNAME;
}

From source file:com.blackducksoftware.tools.appedit.web.controller.naiaudit.EditNaiAuditDetailsController.java

private String getUser() {
    final Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    final String currentUser = auth.getName();
    logger.info("User: " + currentUser);
    return currentUser;
}

From source file:org.smartplatforms.openid.connect.token.SmartTofuUserApprovalHandler.java

/**
 * Check if the user has already stored a positive approval decision for this site; or if the
 * site is whitelisted, approve it automatically.
 * /*w  w  w  .  j  a v  a 2s.  c  o m*/
 * Otherwise the user will be directed to the approval page and can make their own decision.
 * 
 * @param authorizationRequest   the incoming authorization request
 * @param userAuthentication   the Principal representing the currently-logged-in user
 * 
 * @return                   the updated AuthorizationRequest
 */
@Override
public AuthorizationRequest checkForPreApproval(AuthorizationRequest authorizationRequest,
        Authentication userAuthentication) {

    //First, check database to see if the user identified by the userAuthentication has stored an approval decision

    String userId = userAuthentication.getName();
    String clientId = authorizationRequest.getClientId();

    //lookup ApprovedSites by userId and clientId
    boolean alreadyApproved = false;

    // find out if we're supposed to force a prompt on the user or not
    String prompt = (String) authorizationRequest.getExtensions().get(PROMPT);
    List<String> prompts = Splitter.on(PROMPT_SEPARATOR).splitToList(Strings.nullToEmpty(prompt));
    if (!prompts.contains(PROMPT_SEPARATOR)) {
        // if the prompt parameter is set to "consent" then we can't use approved sites or whitelisted sites
        // otherwise, we need to check them below

        Collection<ApprovedSite> aps = approvedSiteService.getByClientIdAndUserId(clientId, userId);
        for (ApprovedSite ap : aps) {

            if (!ap.isExpired()) {

                // if we find one that fits...
                if (systemScopes.scopesMatch(ap.getAllowedScopes(), authorizationRequest.getScope())) {

                    //We have a match; update the access date on the AP entry and return true.
                    ap.setAccessDate(new Date());
                    approvedSiteService.save(ap);

                    String apId = ap.getId().toString();
                    authorizationRequest.getExtensions().put(APPROVED_SITE, apId);
                    authorizationRequest.setApproved(true);
                    alreadyApproved = true;

                    setAuthTime(authorizationRequest);
                }
            }
        }

        if (!alreadyApproved) {
            WhitelistedSite ws = whitelistedSiteService.getByClientId(clientId);
            if (ws != null
                    && systemScopes.scopesMatch(ws.getAllowedScopes(), authorizationRequest.getScope())) {
                authorizationRequest.setApproved(true);

                setAuthTime(authorizationRequest);
            }
        }
    }

    return authorizationRequest;

}

From source file:fr.mcc.ginco.rest.services.ThesaurusTermRestService.java

/**
 * Public method used to create or update
 * {@link fr.mcc.ginco.extjs.view.pojo.ThesaurusTermView} -
 * thesaurus term JSON object send by extjs
 *
 * @return {@link fr.mcc.ginco.extjs.view.pojo.ThesaurusTermView} updated object
 * in JSON format or {@code null} if not found
 *///from  www .ja v  a 2s .  co m
@POST
@Path("/updateTerm")
@Consumes({ MediaType.APPLICATION_JSON })
@PreAuthorize("hasPermission(#thesaurusViewJAXBElement, '0') or hasPermission(#thesaurusViewJAXBElement, '1')")
public ThesaurusTermView updateTerm(ThesaurusTermView thesaurusViewJAXBElement) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    String username = auth.getName();

    if (userRoleService.hasRole(username, thesaurusViewJAXBElement.getThesaurusId(), Role.EXPERT)) {

        try {
            ThesaurusTerm existingTerm = thesaurusTermService
                    .getThesaurusTermById(thesaurusViewJAXBElement.getIdentifier());
            if (existingTerm != null) {
                ThesaurusConcept attachedConcept = existingTerm.getConcept();
                if (attachedConcept == null) {
                    if (thesaurusViewJAXBElement.getStatus() != TermStatusEnum.CANDIDATE.getStatus()) {
                        throw new AccessDeniedException("You can save only candidate terms");
                    }
                    if (existingTerm.getStatus() != TermStatusEnum.CANDIDATE.getStatus()) {
                        throw new AccessDeniedException("You can save only candidate terms");
                    }
                } else {
                    if (attachedConcept.getStatus() != ConceptStatusEnum.CANDIDATE.getStatus()) {
                        throw new AccessDeniedException(
                                "You can save only terms attached to candidate concepts");
                    }
                }
            } else {
                if (thesaurusViewJAXBElement.getStatus() != TermStatusEnum.CANDIDATE.getStatus()) {
                    throw new AccessDeniedException("You can save only candidate terms");
                }
            }
        } catch (BusinessException be) {
            //Do nothing, term just doen't exist
            logger.debug("Case of term creation detected");
        }
    }
    ThesaurusTerm object = termViewConverter.convert(thesaurusViewJAXBElement, false);

    if (object != null) {
        ThesaurusTerm result = thesaurusTermService.updateThesaurusTerm(object);
        if (result != null) {
            termIndexerService.addTerm(object);
            if (result.getConcept() != null && result.getPrefered()) {
                conceptIndexerService.addConcept(result.getConcept());
            }
            return termViewConverter.convert(result, true);
        } else {
            logger.error("Failed to update thesaurus term");
            return null;
        }
    }
    return null;
}

From source file:com.qpark.eip.core.spring.security.EipRoleVoter.java

private void traceRoleSettings(final Authentication authentication, final String channelName,
        final Collection<ConfigAttribute> attributes) {
    this.logger.trace(" vote {} {}: required  [{}]", channelName, authentication.getName(),
            this.getRequiredRoles(attributes));
    this.logger.trace(" vote {} {}: userroles [{}]", channelName, authentication.getName(),
            this.getGrantedRoles(authentication));
}

From source file:fr.univrouen.poste.web.membre.PosteAPourvoirController.java

@RequestMapping(produces = "text/html")
@PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_MANAGER') or hasRole('ROLE_MEMBRE')")
public String list(@RequestParam(value = "page", required = false) Integer page,
        @RequestParam(value = "size", required = false) Integer size,
        @RequestParam(value = "sortFieldName", required = false) String sortFieldName,
        @RequestParam(value = "sortOrder", required = false) String sortOrder, Model uiModel) {

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    boolean isMembre = auth.getAuthorities().contains(new GrantedAuthorityImpl("ROLE_MEMBRE"));

    if (isMembre) {
        String emailAddress = auth.getName();
        User user = User.findUsersByEmailAddress(emailAddress, null, null).getSingleResult();
        List<PosteAPourvoir> posteapourvoirs = PosteAPourvoir.findPosteAPourvoirsByMembre(user);
        uiModel.addAttribute("posteapourvoirs", posteapourvoirs);
    } else if (page != null || size != null) {
        int sizeNo = size == null ? 10 : size.intValue();
        final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
        uiModel.addAttribute("posteapourvoirs",
                PosteAPourvoir.findPosteAPourvoirEntries(firstResult, sizeNo, sortFieldName, sortOrder));
        float nrOfPages = (float) PosteAPourvoir.countPosteAPourvoirs() / sizeNo;
        uiModel.addAttribute("maxPages",
                (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
    } else {/*w  w  w  .  ja  v a 2 s . c  o m*/
        uiModel.addAttribute("posteapourvoirs",
                PosteAPourvoir.findAllPosteAPourvoirs(sortFieldName, sortOrder));
    }
    addDateTimeFormatPatterns(uiModel);
    return "posteapourvoirs/list";
}