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:com.solxiom.social.config.ExplicitSocialConfig.java

@Bean
@Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)
public ConnectionRepository connectionRepository() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication == null) {
        throw new IllegalStateException("Unable to get a ConnectionRepository: no user signed in");
    }// w w w  . j ava 2  s.  co  m
    return usersConnectionRepository().createConnectionRepository(authentication.getName());
}

From source file:no.dusken.aranea.admin.control.ImageUploadController.java

@RequestMapping(value = "/imageUpload/handleFiles.do", method = RequestMethod.GET)
public String handleUploadedFiles(Model model, @RequestParam(required = false) Long pageID) {
    String[] files = workDir.list();
    model.addAttribute("numberOfFiles", files.length);
    model.addAttribute("tags", tagService.getTags());
    model.addAttribute("persons", personService.getPersons());
    if (files.length > 0) {
        model.addAttribute("filename", files[0]);
        model.addAttribute("encodedImage", getEncodedImage(workDir.listFiles()[0]));
    }//from w  w  w  .j a va  2s. c om
    if (pageID != null) {
        model.addAttribute("page", pageService.getEntity(pageID));
    }
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null) {
        String username = authentication.getName();
        Person p = personService.getPersonByUsername(username);
        if (p != null) {
            model.addAttribute("loggedInUser", p);
        }
    }
    return "no/dusken/aranea/base/admin/image/imageUpload";
}

From source file:com.formkiq.core.equifax.service.EquifaxServiceImpl.java

@Override
public EquifaxCreditCheck sendCreditCheck(final FormJSON form, final String request) {

    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DAY_OF_MONTH, -1 * getRequestCache(form));

    EquifaxCreditCheck resp = getCachedResponse(request, calendar.getTime());

    if (resp == null) {

        EquifaxCreditCheckRequestType status = NEW;
        String url = getCreditCheckUrl(form);

        resp = new EquifaxCreditCheck();
        resp.setRequest(request);/*from  w  ww.ja  v a  2s . com*/
        resp.setUrl(url);

        try {
            String response = sendToEquifax(url, request);
            resp.setResponse(response);
        } catch (Exception e) {
            resp.setResponse(e.getMessage());
            status = ERROR;
        }

        resp.setRequesttype(status);

    } else {
        resp.setRequesttype(CACHED);
    }

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    resp.setRequester(auth.getName());
    resp.setRequest(request);
    resp.setInserteddate(new Date());
    resp.setCreditcheckid(UUID.randomUUID().toString());

    saveResponse(resp);

    return resp;
}

From source file:org.cloudfoundry.identity.uaa.security.DefaultSecurityContextAccessor.java

@Override
public String getAuthenticationInfo() {
    Authentication a = SecurityContextHolder.getContext().getAuthentication();

    if (a instanceof OAuth2Authentication) {
        OAuth2Authentication oauth = ((OAuth2Authentication) a);

        String info = getClientId();
        if (!oauth.isClientOnly()) {
            info = info + "; " + a.getName() + "; " + getUserId();
        }/* w w  w  .  j a  va  2s . com*/

        return info;
    } else {
        return a.getName();
    }
}

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

@RequestMapping(value = "/{rsid}", method = RequestMethod.GET, produces = MimeTypeUtils.APPLICATION_JSON_VALUE)
public String getClaimsForResourceSet(@PathVariable(value = "rsid") Long rsid, Model m, Authentication auth) {

    ResourceSet rs = resourceSetService.getById(rsid);

    if (rs == null) {
        m.addAttribute(HttpCodeView.CODE, HttpStatus.NOT_FOUND);
        return HttpCodeView.VIEWNAME;
    }//from   w w  w  .j a va 2 s .  c  o  m

    if (!rs.getOwner().equals(auth.getName())) {
        // authenticated user didn't match the owner of the resource set
        m.addAttribute(HttpCodeView.CODE, HttpStatus.FORBIDDEN);
        return HttpCodeView.VIEWNAME;
    }

    m.addAttribute(JsonEntityView.ENTITY, rs.getClaimsRequired());

    return JsonEntityView.VIEWNAME;
}

From source file:psiprobe.controllers.deploy.UploadWarController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    if (FileUploadBase.isMultipartContent(new ServletRequestContext(request))) {

        File tmpWar = null;/*ww w  .  j ava 2 s. co m*/
        String contextName = null;
        boolean update = false;
        boolean compile = false;
        boolean discard = false;

        // parse multipart request and extract the file
        FileItemFactory factory = new DiskFileItemFactory(1048000,
                new File(System.getProperty("java.io.tmpdir")));
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(-1);
        upload.setHeaderEncoding(StandardCharsets.UTF_8.name());
        try {
            List<FileItem> fileItems = upload.parseRequest(request);
            for (FileItem fi : fileItems) {
                if (!fi.isFormField()) {
                    if (fi.getName() != null && fi.getName().length() > 0) {
                        tmpWar = new File(System.getProperty("java.io.tmpdir"),
                                FilenameUtils.getName(fi.getName()));
                        fi.write(tmpWar);
                    }
                } else if ("context".equals(fi.getFieldName())) {
                    contextName = fi.getString();
                } else if ("update".equals(fi.getFieldName()) && "yes".equals(fi.getString())) {
                    update = true;
                } else if ("compile".equals(fi.getFieldName()) && "yes".equals(fi.getString())) {
                    compile = true;
                } else if ("discard".equals(fi.getFieldName()) && "yes".equals(fi.getString())) {
                    discard = true;
                }
            }
        } catch (Exception e) {
            logger.error("Could not process file upload", e);
            request.setAttribute("errorMessage", getMessageSourceAccessor()
                    .getMessage("probe.src.deploy.war.uploadfailure", new Object[] { e.getMessage() }));
            if (tmpWar != null && tmpWar.exists() && !tmpWar.delete()) {
                logger.error("Unable to delete temp war file");
            }
            tmpWar = null;
        }

        String errMsg = null;

        if (tmpWar != null) {
            try {
                if (tmpWar.getName().endsWith(".war")) {

                    if (contextName == null || contextName.length() == 0) {
                        String warFileName = tmpWar.getName().replaceAll("\\.war$", "");
                        contextName = "/" + warFileName;
                    }

                    contextName = getContainerWrapper().getTomcatContainer().formatContextName(contextName);

                    /*
                     * pass the name of the newly deployed context to the presentation layer using this name
                     * the presentation layer can render a url to view compilation details
                     */
                    String visibleContextName = "".equals(contextName) ? "/" : contextName;
                    request.setAttribute("contextName", visibleContextName);

                    if (update && getContainerWrapper().getTomcatContainer().findContext(contextName) != null) {

                        logger.debug("updating {}: removing the old copy", contextName);
                        getContainerWrapper().getTomcatContainer().remove(contextName);
                    }

                    if (getContainerWrapper().getTomcatContainer().findContext(contextName) == null) {
                        // move the .war to tomcat application base dir
                        String destWarFilename = getContainerWrapper().getTomcatContainer()
                                .formatContextFilename(contextName);
                        File destWar = new File(getContainerWrapper().getTomcatContainer().getAppBase(),
                                destWarFilename + ".war");

                        FileUtils.moveFile(tmpWar, destWar);

                        // let Tomcat know that the file is there
                        getContainerWrapper().getTomcatContainer().installWar(contextName,
                                new URL("jar:" + destWar.toURI().toURL().toString() + "!/"));

                        Context ctx = getContainerWrapper().getTomcatContainer().findContext(contextName);
                        if (ctx == null) {
                            errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.notinstalled",
                                    new Object[] { visibleContextName });
                        } else {
                            request.setAttribute("success", Boolean.TRUE);
                            // Logging action
                            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
                            String name = auth.getName(); // get username logger
                            logger.info(getMessageSourceAccessor().getMessage("probe.src.log.deploywar"), name,
                                    contextName);
                            if (discard) {
                                getContainerWrapper().getTomcatContainer().discardWorkDir(ctx);
                                logger.info(getMessageSourceAccessor().getMessage("probe.src.log.discardwork"),
                                        name, contextName);
                            }
                            if (compile) {
                                Summary summary = new Summary();
                                summary.setName(ctx.getName());
                                getContainerWrapper().getTomcatContainer().listContextJsps(ctx, summary, true);
                                request.getSession(false).setAttribute(DisplayJspController.SUMMARY_ATTRIBUTE,
                                        summary);
                                request.setAttribute("compileSuccess", Boolean.TRUE);
                            }
                        }

                    } else {
                        errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.alreadyExists",
                                new Object[] { visibleContextName });
                    }
                } else {
                    errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.notWar.failure");
                }
            } catch (Exception e) {
                errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.failure",
                        new Object[] { e.getMessage() });
                logger.error("Tomcat throw an exception when trying to deploy", e);
            } finally {
                if (errMsg != null) {
                    request.setAttribute("errorMessage", errMsg);
                }
                if (tmpWar.exists() && !tmpWar.delete()) {
                    logger.error("Unable to delete temp war file");
                }
            }
        }
    }
    return new ModelAndView(new InternalResourceView(getViewName()));
}

From source file:org.shaigor.rest.retro.client.oauth.OAuthPostAuthListener.java

@Override
public void onApplicationEvent(AbstractAuthenticationEvent event) {
    Authentication authentication = event.getAuthentication();

    if (event instanceof AuthenticationSuccessEvent) {
        ResourceOwnerPasswordResourceDetails resource = getResourceOwnerPasswordResourceDetails();
        resource.setScope(Arrays.asList("words"));
        resource.setUsername(authentication.getName());
        resource.setPassword(authentication.getCredentials().toString());

        try {//from   w  w  w  . j  av a  2s  . co  m
            OAuth2AccessToken accessToken = accessTokenProvider.obtainAccessToken(resource,
                    new DefaultAccessTokenRequest());
            log.debug("Access token request succeeded for user: '{}', new token is '{}'",
                    resource.getUsername(), accessToken.getValue());
            if (authentication instanceof AbstractAuthenticationToken
                    && authentication.getDetails() instanceof CustomAuthenticationDetails) {
                ((CustomAuthenticationDetails) ((AbstractAuthenticationToken) authentication).getDetails())
                        .setBearer(accessToken.getValue());
                log.debug("Access token was added to authentication as details");
            } else if (log.isDebugEnabled()) {
                log.debug("Access token could not be added to authentication as details");
            }
        } catch (Exception e) {
            log.error("Access token request failed for user: '" + resource.getUsername() + "'", e);
        }
    }
    if (authentication instanceof CredentialsContainer) {
        // Authentication is complete. Remove credentials and other secret data from authentication
        ((CredentialsContainer) authentication).eraseCredentials();
    }

}

From source file:org.sharetask.security.WorkspaceMemberOrOwnerPermission.java

@Override
public boolean isAllowed(final Authentication authentication, final Object targetDomainObject) {
    boolean result;
    Assert.isTrue(isAuthenticated(authentication), "UserAuthentication is not authenticated!");
    Assert.isTrue(targetDomainObject instanceof Long);
    final Long workspaceId = (Long) targetDomainObject;
    final String userName = authentication.getName();
    final Workspace workspace = workspaceRepository.read(workspaceId);
    if (isWorkspaceOwner(workspace, userName)) {
        result = true;//w w  w .j  ava 2  s . c  o  m
    } else if (isWorkspaceMember(workspace, userName)) {
        result = true;
    } else {
        result = false;
    }
    return result;
}

From source file:cherry.sqlman.tool.statement.SqlStatementControllerImpl.java

@Override
public ModelAndView create(SqlStatementForm form, BindingResult binding, Authentication auth, Locale locale,
        SitePreference sitePref, NativeWebRequest request) {

    if (hasErrors(form, binding)) {
        return withViewname(viewnameOfStart).build();
    }/*from   w ww.  j a  v  a  2  s  .co m*/

    int id = statementService.create(form, auth.getName());
    return redirect(redirectOnCreate(id)).build();
}