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:de.itsvs.cwtrpc.security.AbstractRpcAuthenticationProcessingFilter.java

protected void successfulAuthenticationEnd(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws IOException, ServletException {
    if (log.isDebugEnabled()) {
        log.debug("Successful authentication of '" + authentication.getName() + "' ended");
    }//from  w  ww. ja v  a 2 s. co m

    getAuthenticationSuccessHandler().onAuthenticationSuccess(request, response, authentication);
}

From source file:nl.ctrlaltdev.harbinger.evidence.Evidence.java

public Evidence(Evidence src, Authentication auth) {
    this(src);//w  ww .ja v a 2 s .co m
    Object principal = auth.getPrincipal();
    if (principal instanceof UserDetails) {
        user = ((UserDetails) principal).getUsername();
    } else {
        user = auth.getName();
    }
}

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

@RequestMapping(method = RequestMethod.GET, produces = MimeTypeUtils.APPLICATION_JSON_VALUE)
public String listResourceSets(Model m, Authentication auth) {
    ensureOAuthScope(auth, SystemScopeService.UMA_PROTECTION_SCOPE);

    String owner = auth.getName();

    Collection<ResourceSet> resourceSets = Collections.emptySet();
    if (auth instanceof OAuth2Authentication) {
        // if it's an OAuth mediated call, it's on behalf of a client, so look that up too
        OAuth2Authentication o2a = (OAuth2Authentication) auth;
        resourceSets = resourceSetService.getAllForOwnerAndClient(owner, o2a.getOAuth2Request().getClientId());
    } else {//from w  w w .j  av a2s . c om
        // otherwise get everything for the current user
        resourceSets = resourceSetService.getAllForOwner(owner);
    }

    // build the entity here and send to the display

    Set<String> ids = new HashSet<>();
    for (ResourceSet resourceSet : resourceSets) {
        ids.add(resourceSet.getId().toString()); // add them all as strings so that gson renders them properly
    }

    m.addAttribute(JsonEntityView.ENTITY, ids);
    return JsonEntityView.VIEWNAME;
}

From source file:de.thm.arsnova.security.CustomBindAuthenticator.java

public DirContextOperations authenticate(Authentication authentication) {
    DirContextOperations user = null;/*  ww  w . j  av a  2 s  .  c o m*/
    Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication,
            "Can only process UsernamePasswordAuthenticationToken objects");

    String username = authentication.getName();
    String password = (String) authentication.getCredentials();

    if (!StringUtils.hasLength(password)) {
        logger.debug("Rejecting empty password for user " + username);
        throw new BadCredentialsException(
                messages.getMessage("BindAuthenticator.emptyPassword", "Empty Password"));
    }

    // If DN patterns are configured, try authenticating with them directly
    for (String dn : getUserDns(username)) {
        user = bindWithDn(dn, username, password);

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

    // Otherwise use the configured search object to find the user and authenticate
    // with the returned DN.
    if (user == null && getUserSearch() != null) {
        DirContextOperations userFromSearch = getUserSearch().searchForUser(username);
        user = bindWithDn(userFromSearch.getDn().toString(), username, password);
    }

    if (user == null) {
        throw new BadCredentialsException(
                messages.getMessage("BindAuthenticator.badCredentials", "Bad credentials"));
    }

    return user;
}

From source file:de.itsvs.cwtrpc.security.AbstractRpcAuthenticationProcessingFilter.java

protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws IOException, ServletException {
    if (log.isDebugEnabled()) {
        log.debug("Successful authentication of '" + authentication.getName() + "'");
    }//from ww w.  ja  v  a2  s .  c  o m

    SecurityContextHolder.getContext().setAuthentication(authentication);

    getRememberMeServices().loginSuccess(request, response, authentication);
    if (getApplicationEventPublisher() != null) {
        getApplicationEventPublisher()
                .publishEvent(new InteractiveAuthenticationSuccessEvent(authentication, getClass()));
    }
}

From source file:org.opendatakit.security.spring.UserServiceImpl.java

@Override
public User getCurrentUser() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();

    return internalGetUser(auth.getName(), authorities);
}

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

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

    List<Context> apps;
    try {//  w  ww  .j  av a  2s  . c  o m
        apps = getContainerWrapper().getTomcatContainer().findContexts();
    } catch (NullPointerException ex) {
        throw new IllegalStateException(
                "No container found for your server: " + getServletContext().getServerInfo(), ex);
    }

    List<Map<String, String>> applications = new ArrayList<>();
    for (Context appContext : apps) {
        // check if this is not the ROOT webapp
        if (appContext.getName() != null && appContext.getName().trim().length() > 0) {
            Map<String, String> app = new HashMap<>();
            app.put("value", appContext.getName());
            app.put("label", appContext.getName());
            applications.add(app);
        }
    }
    request.setAttribute("apps", applications);

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

        File tmpFile = null;
        String contextName = null;
        String where = null;
        boolean reload = 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) {
                        tmpFile = new File(System.getProperty("java.io.tmpdir"),
                                FilenameUtils.getName(fi.getName()));
                        fi.write(tmpFile);
                    }
                } else if ("context".equals(fi.getFieldName())) {
                    contextName = fi.getString();
                } else if ("where".equals(fi.getFieldName())) {
                    where = fi.getString();
                } else if ("reload".equals(fi.getFieldName()) && "yes".equals(fi.getString())) {
                    reload = 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.file.uploadfailure", new Object[] { e.getMessage() }));
            if (tmpFile != null && tmpFile.exists() && !tmpFile.delete()) {
                logger.error("Unable to delete temp upload file");
            }
            tmpFile = null;
        }

        String errMsg = null;

        if (tmpFile != null) {
            try {
                if (tmpFile.getName() != null && tmpFile.getName().trim().length() > 0) {

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

                    String visibleContextName = "".equals(contextName) ? "/" : contextName;
                    request.setAttribute("contextName", visibleContextName);

                    // Check if context is already deployed
                    if (getContainerWrapper().getTomcatContainer().findContext(contextName) != null) {

                        File destFile = new File(getContainerWrapper().getTomcatContainer().getAppBase(),
                                contextName + where);
                        // Checks if the destination path exists

                        if (destFile.exists()) {
                            if (!destFile.getAbsolutePath().contains("..")) {
                                // Copy the file overwriting it if it
                                // already exists
                                FileUtils.copyFileToDirectory(tmpFile, destFile);

                                request.setAttribute("successFile", Boolean.TRUE);
                                // Logging action
                                Authentication auth = SecurityContextHolder.getContext().getAuthentication();
                                String name = auth.getName(); // get username
                                                              // logger
                                logger.info(getMessageSourceAccessor().getMessage("probe.src.log.copyfile"),
                                        name, contextName);
                                Context context = getContainerWrapper().getTomcatContainer()
                                        .findContext(contextName);
                                // Checks if DISCARD "work" directory is
                                // selected
                                if (discard) {
                                    getContainerWrapper().getTomcatContainer().discardWorkDir(context);
                                    logger.info(
                                            getMessageSourceAccessor().getMessage("probe.src.log.discardwork"),
                                            name, contextName);
                                }
                                // Checks if RELOAD option is selected
                                if (reload) {

                                    if (context != null) {
                                        context.reload();
                                        request.setAttribute("reloadContext", Boolean.TRUE);
                                        logger.info(
                                                getMessageSourceAccessor().getMessage("probe.src.log.reload"),
                                                name, contextName);
                                    }
                                }
                            } else {
                                errMsg = getMessageSourceAccessor()
                                        .getMessage("probe.src.deploy.file.pathNotValid");
                            }
                        } else {
                            errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.file.notPath");
                        }
                    } else {
                        errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.file.notExists",
                                new Object[] { visibleContextName });
                    }
                } else {
                    errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.file.notFile.failure");
                }
            } catch (Exception e) {
                errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.file.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 (!tmpFile.delete()) {
                    logger.error("Unable to delete temp upload file");
                }
            }
        }
    }
    return new ModelAndView(new InternalResourceView(getViewName()));
}

From source file:ve.gob.mercal.app.controllers.suscriptorController.java

@RequestMapping(value = { "/SuscriptorPrincipal" }, method = { RequestMethod.GET })
public ModelAndView getsuscriptorprincipal() {
    ModelAndView model = new ModelAndView();
    String s = "NULL";
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    String name = auth.getName(); //get logged in username
    try {// w w w  .j  av a  2  s  .  c o  m
        s = wsQuery
                .getConsulta("SELECT  t.tienda\n" + "  FROM public.tiendas as t\n" + "  WHERE t.activo=true ;");
    } catch (ExcepcionServicio e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    JsonParser parser = new JsonParser();
    JsonElement elementObject;
    s = s.substring(1, s.length() - 1);
    StringTokenizer st = new StringTokenizer(s, ",");
    while (st.hasMoreTokens()) {
        s = st.nextToken();
        elementObject = parser.parse(s);
        if (existeCampo.existeCampo(s, "tienda")) {
            this.tienda = elementObject.getAsJsonObject().get("tienda").getAsString();
        }
        listString.add("<option value=\"" + this.tienda + "\"type=\"submit\">" + this.tienda + "</option>");
    }
    model.addObject("tienda", listString);
    model.setViewName("SuscriptorPrincipal");
    return model;
}

From source file:ve.gob.mercal.app.controllers.suscriptorController.java

@RequestMapping(value = { "/Suscriptor" }, method = { RequestMethod.GET })
public ModelAndView getTienda() {
    ModelAndView model = new ModelAndView();
    String s = "NULL";
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    String name = auth.getName(); //get logged in username
    try {/*  w  w w  . jav a2s . c  om*/
        s = wsQuery.getConsulta("SELECT t.tienda FROM public.susc_tiendas as st"
                + ", public.tiendas as t, public.usuarios as u WHERE st.activo=TRUE and "
                + "t.id_tienda=st.id_tienda and st.id_usuario=u.id_usuario and " + "u.usuario='" + name + "';");
    } catch (ExcepcionServicio e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    JsonParser parser = new JsonParser();
    JsonElement elementObject;
    s = s.substring(1, s.length() - 1);
    StringTokenizer st = new StringTokenizer(s, ",");
    while (st.hasMoreTokens()) {
        s = st.nextToken();
        elementObject = parser.parse(s);
        if (existeCampo.existeCampo(s, "tienda")) {
            this.tienda = elementObject.getAsJsonObject().get("tienda").getAsString();
        }
        listString.add("<option value=\"" + this.tienda + "\" type=\"submit\">" + this.tienda + "</option>");
    }
    model.addObject("tienda", listString);
    model.setViewName("Suscriptor");
    return model;
}