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:fr.xebia.audit.AuditAspect.java

protected String buildMessage(String template, Object invokedObject, Object[] args, Object returned,
        Throwable throwned, long durationInNanos) {
    try {//from  ww  w. ja  v a  2  s .  co m
        Expression expression = expressionCache.get(template);
        if (expression == null) {
            expression = expressionParser.parseExpression(template, parserContext);
            expressionCache.put(template, expression);
        }

        String evaluatedMessage = expression.getValue(new RootObject(invokedObject, args, returned, throwned),
                String.class);

        StringBuilder msg = new StringBuilder();

        SimpleDateFormat simpleDateFormat = (SimpleDateFormat) dateFormatPrototype.clone();
        msg.append(simpleDateFormat.format(new Date()));

        msg.append(" ").append(evaluatedMessage);

        if (throwned != null) {
            msg.append(" threw '");
            appendThrowableCauses(throwned, ", ", msg);
            msg.append("'");
        }
        msg.append(" by ");
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            msg.append("anonymous");
        } else {
            msg.append(authentication.getName());
            if (authentication.getDetails() instanceof WebAuthenticationDetails) {
                WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails();
                msg.append(" coming from " + details.getRemoteAddress());
            }
        }
        msg.append(" in ").append(TimeUnit.MILLISECONDS.convert(durationInNanos, TimeUnit.NANOSECONDS))
                .append(" ms");
        return msg.toString();
    } catch (RuntimeException e) {
        StringBuilder msg = new StringBuilder("Exception evaluating template '" + template + "': ");
        appendThrowableCauses(e, ", ", msg);
        return msg.toString();
    }
}

From source file:org.modeshape.example.springsecurity.web.RepositoryController.java

@RequestMapping(value = { "/", "/modeshape-spring-security-example/" }, method = {
        RequestMethod.GET }, produces = "text/html; charset=utf-8")
public @ResponseBody String jcrLogin(Authentication auth) {
    String html = "";
    try {//from  ww w.  java2 s .co  m
        Session session = repository.login(new SpringSecurityCredentials(auth));

        String repoName = session.getRepository()
                .getDescriptor(org.modeshape.jcr.api.Repository.REPOSITORY_NAME);
        String wsName = session.getWorkspace().getName();

        html = "<html>" + "<body>" + "<h3>Welcome " + (auth.getName()) + "!</h3>"
                + "<p>You have successfully logged in to [" + (repoName + "." + wsName) + "]</p>"
                + "<p>You have granted " + auth.getAuthorities().toString() + " roles.</p>"
                + "<p><a href='/login?logout'>logout</a></p>" + "</body>" + "</html>";
    } catch (RepositoryException e) {
        e.printStackTrace();
    }
    return html;
}

From source file:controller.ViewPackageController.java

@RequestMapping(value = "/pickPackage/{id}", method = RequestMethod.GET)
public String pickPackage(ModelMap mm, Authentication authen, @PathVariable(value = "id") int id) {
    try {//  w  w  w  .j a  v  a 2s.c om
        List<Distributor> listDis = disModel.getAll();
        Packages pack = packModel.getByID(id);
        mm.put("listDistributor", listDis);
        Customer cus = cusModel.find(authen.getName(), "username", false).get(0);
        mm.addAttribute("requirement", new Requirement(null, cus, null, Double.NaN));
        mm.put("type", pack.getType());
        mm.put("packid", pack.getPackageId());
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return "pickPackage";

}

From source file:org.georchestra.security.LdapUserDetailsRequestHeaderProvider.java

@SuppressWarnings("unchecked")
@Override/*from w  w w .  j  a  v  a  2  s  . c o  m*/
protected Collection<Header> getCustomRequestHeaders(HttpSession session, HttpServletRequest originalRequest) {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication instanceof AnonymousAuthenticationToken) {
        return Collections.emptyList();
    }
    String username = authentication.getName();
    DirContextOperations userData;

    Collection<Header> headers = Collections.emptyList();

    synchronized (session) {

        if (session.getAttribute("security-proxy-cached-attrs") != null) {
            try {
                headers = (Collection<Header>) session.getAttribute("security-proxy-cached-attrs");
                String expectedUsername = (String) session.getAttribute("security-proxy-cached-username");

                if (username.equals(expectedUsername)) {
                    return headers;
                }
            } catch (Exception e) {
                logger.info("Unable to lookup cached user's attributes for user :" + username, e);
            }
        } else {
            try {
                userData = _userSearch.searchForUser(username);
            } catch (Exception e) {
                logger.info("Unable to lookup user:" + username, e);
                return Collections.emptyList();
            }
            headers = new ArrayList<Header>();
            for (Map.Entry<String, String> entry : _headerMapping.entrySet()) {
                try {
                    Attribute attributes = userData.getAttributes().get(entry.getValue());
                    if (attributes != null) {
                        NamingEnumeration<?> all = attributes.getAll();
                        StringBuilder value = new StringBuilder();
                        while (all.hasMore()) {
                            if (value.length() > 0) {
                                value.append(',');
                            }
                            value.append(all.next());
                        }
                        headers.add(new BasicHeader(entry.getKey(), value.toString()));
                    }
                } catch (javax.naming.NamingException e) {
                    logger.error("problem adding headers for request:" + entry.getKey(), e);
                }
            }

            // Add user organization
            try {
                // Retreive memberOf attributes
                String[] attrs = { "memberOf" };
                ((FilterBasedLdapUserSearch) this._userSearch).setReturningAttributes(attrs);
                userData = _userSearch.searchForUser(username);
                Attribute attributes = userData.getAttributes().get("memberOf");
                if (attributes != null) {
                    NamingEnumeration<?> all = attributes.getAll();

                    while (all.hasMore()) {
                        String memberOf = all.next().toString();
                        Matcher m = this.pattern.matcher(memberOf);
                        if (m.matches()) {
                            headers.add(new BasicHeader("sec-org", m.group(2)));
                            break;
                        }
                    }
                }
            } catch (javax.naming.NamingException e) {
                logger.error("problem adding headers for request: organization", e);
            } finally {
                // restore standard attribute list
                ((FilterBasedLdapUserSearch) this._userSearch).setReturningAttributes(null);
            }

            logger.info("Storing attributes into session for user :" + username);
            session.setAttribute("security-proxy-cached-username", username);
            session.setAttribute("security-proxy-cached-attrs", headers);
        }
    }

    return headers;
}

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

@RequestMapping(value = { "/SuscriptorPrincipal" }, method = { RequestMethod.POST })
public ModelAndView postsuscriptorprincipal(
        @RequestParam(value = "listString", required = false) String nameTienda) {
    ModelAndView model = new ModelAndView();
    model = getsuscriptorprincipal();//  w ww . j  a  va2 s.c  o  m
    String s = "NULL";
    String s2 = "NULL";
    String s3 = "NULL";
    int result = -999;
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    String name = auth.getName(); //get logged in username
    JsonParser parser = new JsonParser();
    JsonElement elementObject;
    try {
        s = wsQuery.getConsulta("SELECT id_tienda FROM tiendas\n" + "  WHERE tienda='" + nameTienda + "';");
        s = s.substring(1, s.length() - 1);
        elementObject = parser.parse(s);
        if (existeCampo.existeCampo(s, "tienda")) {
            s = elementObject.getAsJsonObject().get("id_tienda").getAsString();
        }
        s3 = wsQuery.getConsulta(
                "SELECT id_usuario FROM usuarios " + "WHERE usuario='" + name + "' and activo=TRUE;");
        s3 = s3.substring(1, s3.length() - 1);
        elementObject = parser.parse(s3);
        if (existeCampo.existeCampo(s3, "id_usuario")) {
            s3 = elementObject.getAsJsonObject().get("id_usuario").getAsString();
        }
        s2 = wsQuery.getConsulta("SELECT id_usuario, id_tienda\n" + "  FROM public.susc_tiendas\n"
                + "  WHERE activo=true and id_usuario='" + s3 + "' and id_tienda='" + s + "';");
    } catch (ExcepcionServicio e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    if (s2 == "[]") {
        try {
            result = wsFuncionApp.getConsulta("public.insert_susc_tiendas(" + s3 + ", " + s + ", " + s3 + ");");
        } catch (ExcepcionServicio e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (result > 0) {
            model.addObject("exite", "Exito al suscribirse a la tienda");
        } else {
            model.addObject("exite", "Error al suscribirse a la tienda");
        }
    } else {
        model.addObject("exite", "Usted ya se encuentra suscrito a la tienda");
    }
    model.setViewName("SuscriptorPrincipal");
    return model;
}

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

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

    ResourceSet rs = resourceSetService.getById(id);

    if (rs == null) {
        m.addAttribute(HttpCodeView.CODE, HttpStatus.NOT_FOUND);
        m.addAttribute(JsonErrorView.ERROR, "not_found");
        return JsonErrorView.VIEWNAME;
    } else {//from w  w  w  . j  a va 2 s .  co  m
        if (!auth.getName().equals(rs.getOwner())) {

            logger.warn("Unauthorized resource set request from bad user; expected " + rs.getOwner() + " got "
                    + auth.getName());

            // it wasn't issued to this user
            m.addAttribute(HttpCodeView.CODE, HttpStatus.FORBIDDEN);
            return JsonErrorView.VIEWNAME;
        } else {

            resourceSetService.remove(rs);

            m.addAttribute(HttpCodeView.CODE, HttpStatus.NO_CONTENT);
            return HttpCodeView.VIEWNAME;
        }

    }
}

From source file:org.socialsignin.springsocial.security.signin.SpringSocialSecurityAuthenticationFactory.java

public Authentication updateAuthenticationForNewProviders(Authentication existingAuthentication,
        Set<String> providerIds) {
    List<GrantedAuthority> newAuthorities = new ArrayList<GrantedAuthority>();
    for (String providerId : providerIds) {
        newAuthorities.add(userAuthoritiesService.getProviderAuthority(providerId));
    }/*  w w w . j ava2 s. co m*/
    return createNewAuthentication(existingAuthentication.getName(),
            existingAuthentication.getCredentials() == null ? null
                    : existingAuthentication.getCredentials().toString(),
            addAuthorities(existingAuthentication, newAuthorities));
}

From source file:cherry.sqlapp.controller.sqltool.load.SqltoolLoadControllerImpl.java

@Override
public ModelAndView execute(SqltoolLoadForm form, BindingResult binding, Authentication auth, Locale locale,
        SitePreference sitePref, HttpServletRequest request, RedirectAttributes redirAttr) {

    if (binding.hasErrors()) {
        ModelAndView mav = new ModelAndView(PathDef.VIEW_SQLTOOL_LOAD_INIT);
        return mav;
    }//from w w  w. j  ava  2 s.  co m

    long asyncId = asyncProcessFacade.launchFileProcess(auth.getName(), "SqltoolLoadController", form.getFile(),
            "execLoadFileProcessHandler", form.getDatabaseName(), form.getSql());

    redirAttr.addFlashAttribute(ASYNC_PARAM, asyncId);

    UriComponents uc = fromMethodCall(on(SqltoolLoadController.class).finish(auth, locale, sitePref, request))
            .build();

    ModelAndView mav = new ModelAndView();
    mav.setView(new RedirectView(uc.toUriString(), true));
    return mav;
}

From source file:com.epam.ta.reportportal.auth.permissions.BaseProjectPermission.java

/**
 * Validates project exists and user assigned to project. After that
 * delegates permission check to subclass
 *//*w ww.jav a2 s  . co m*/
@Override
public boolean isAllowed(Authentication authentication, Object projectName) {
    if (!authentication.isAuthenticated()) {
        return false;
    }

    String project = (String) projectName;
    Project p = projectRepository.get().findOne(project);
    BusinessRule.expect(p, Predicates.notNull()).verify(ErrorType.PROJECT_NOT_FOUND, project);

    BusinessRule.expect(p.getUsers(), Preconditions.containsKey(authentication.getName()))
            .verify(ErrorType.ACCESS_DENIED);
    return checkAllowed(authentication, p);
}

From source file:nl.surfnet.coin.api.oauth.ClientMetaDataPreAuthenticatedGrantedAuthoritiesUserDetailsService.java

@Override
protected UserDetails createuserDetails(Authentication token,
        Collection<? extends GrantedAuthority> authorities) {
    if (token instanceof PreAuthenticatedAuthenticationToken) {
        PreAuthenticatedAuthenticationToken preToken = (PreAuthenticatedAuthenticationToken) token;
        Object principal = preToken.getPrincipal();
        if (principal instanceof ClientMetaDataPrincipal) {
            return new ClientMetaDataUser(token.getName(), "N/A", true, true, true, true, authorities,
                    ((ClientMetaDataPrincipal) principal).getClientMetaData());
        } else {/*from  w  ww  . j av  a 2 s .  c om*/
            throw new RuntimeException(
                    "The principal on the PreAuthenticatedAuthenticationToken is of the type '"
                            + (principal != null ? principal.getClass() : "null")
                            + "'. Required is a (sub)class of ClientMetaDataPrincipal");
        }

    } else {
        throw new RuntimeException("The token is of the type '" + (token != null ? token.getClass() : "null")
                + "'. Required is a (sub)class of PreAuthenticatedAuthenticationToken");
    }

}