Example usage for org.springframework.security.core.context SecurityContextHolder getContext

List of usage examples for org.springframework.security.core.context SecurityContextHolder getContext

Introduction

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

Prototype

public static SecurityContext getContext() 

Source Link

Document

Obtain the current SecurityContext.

Usage

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

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

    String contextName = ServletRequestUtils.getStringParameter(request, "context", null);

    if (contextName != null) {
        try {//from w w  w  .  ja va 2  s. c o  m
            if (getContainerWrapper().getTomcatContainer().installContext(contextName)) {
                request.setAttribute("successMessage", getMessageSourceAccessor()
                        .getMessage("probe.src.deploy.context.success", new Object[] { contextName }));
                // Logging action
                Authentication auth = SecurityContextHolder.getContext().getAuthentication();
                String name = auth.getName(); // get username logger
                logger.info(getMessageSourceAccessor().getMessage("probe.src.log.deploycontext"), name,
                        contextName);
            } else {
                request.setAttribute("errorMessage", getMessageSourceAccessor()
                        .getMessage("probe.src.deploy.context.failure", new Object[] { contextName }));
            }
        } catch (Exception e) {
            request.setAttribute("errorMessage", e.getMessage());
            logger.trace("", e);
        }
    }

    return new ModelAndView(new InternalResourceView(getViewName()));
}

From source file:com.tapas.evidence.repository.ResponsiblePersonRepositoryImpl.java

@Override
@SuppressWarnings("unchecked")
public List<ResponsiblePerson> findAll() {
    final Long tenantId = ((EvidenceUserDetails) SecurityContextHolder.getContext().getAuthentication()
            .getPrincipal()).getTenantId();
    Query query = this.entityManager.createNamedQuery(ResponsiblePerson.QUERY_NAME_FIND_ALL_BY_DELETED_FLAG);
    query.setParameter("deleted", Boolean.FALSE);
    query.setParameter("tenantId", tenantId);
    return query.getResultList();
}

From source file:org.zalando.example.zauth.controller.WebController.java

@RequestMapping(value = { "/", "/index" })
public String index(final Model model) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    auth.getPrincipal();//from w  w w.  j a  v  a 2  s  .  c  om

    String currentLogin = zAuth.getCurrentLogin();
    model.addAttribute("currentLogin", currentLogin);

    User user = zAuth.userOperations().getUserById(currentLogin);
    model.addAttribute("user", user);
    return "index";
}

From source file:org.malaguna.springsec.taglibs.SpringSecurityELLibrary.java

private static GrantedAuthority[] getUserAuthorities() {
    if (SecurityContextHolder.getContext() == null) {
        System.out.println("security context is empty, this seems to be a bug/misconfiguration!");
        return new GrantedAuthority[0];
    }//  www . j  a  v a2  s. c  om
    Authentication currentUser = SecurityContextHolder.getContext().getAuthentication();
    if (currentUser == null)
        return new GrantedAuthority[0];

    Collection<? extends GrantedAuthority> authorities = currentUser.getAuthorities();
    if (authorities == null)
        return new GrantedAuthority[0];

    return authorities.toArray(new GrantedAuthority[] {});
}

From source file:com.sapito.config.SecurityUtils.java

/**
 * Gets the username of logged user//from   w  ww .j a  v a  2  s  .c om
 * @return logged user's username
 */
public String getUsername() {
    return SecurityContextHolder.getContext().getAuthentication().getName();
}

From source file:org.shredzone.cilla.ws.client.RemoteLoginServiceImpl.java

@Override
public void login(String user, String password) {
    RemoteUserDetails userDetails = new RemoteUserDetails();
    userDetails.setUsername(user);//w  w w . j a  va 2 s . c  o m
    userDetails.setPassword(password);

    Authentication auth = new UsernamePasswordAuthenticationToken(userDetails, password);
    SecurityContextHolder.getContext().setAuthentication(auth);

    auth = authenticationManager.authenticate(auth);
    SecurityContextHolder.getContext().setAuthentication(auth);
}

From source file:ch.astina.hesperid.web.services.springsecurity.internal.LogoutServiceImpl.java

public final void logout() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    for (LogoutHandler handler : handlers) {
        handler.logout(requestGlobals.getHTTPServletRequest(), requestGlobals.getHTTPServletResponse(), auth);
    }//from  www .  j  a v  a2  s . co m
}

From source file:org.apereo.inspektr.audit.spi.support.SpringSecurityAuditablePrincipalResolver.java

private String getFromSecurityContext() {
    final SecurityContext securityContext = SecurityContextHolder.getContext();

    if (securityContext == null) {
        return UNKNOWN_USER;
    }/*from  ww  w  .j  a  v a  2  s  .  c  o m*/

    if (securityContext.getAuthentication() == null) {
        return UNKNOWN_USER;
    }

    final String subject = securityContext.getAuthentication().getName();
    if (subject == null) {
        return UNKNOWN_USER;
    }
    return subject;
}

From source file:BusinessLayer.service.DepositService.java

public Compte depositinAccount(String accountnumber, String password, String amount) {

    CustomSecurityUser currentUser = (CustomSecurityUser) SecurityContextHolder.getContext().getAuthentication()
            .getPrincipal();//from  ww  w.java  2 s . c  om
    System.out.println(currentUser.getId());

    Utilisateur utilisateur = userDAO.getUser(currentUser.getId());

    if (!utilisateur.getEnabled()) {
        throw new DisabledUserProfileException();
    }

    if (!(utilisateur.getPass().equals(password))) {
        throw new WrongPasswordException();
    }

    Compte account = accountDAO
            .getAccount(new CompteId((int) Integer.parseInt(accountnumber), (int) currentUser.getId()));

    if (account == null) {
        throw new AccountNONExistantException();
    }

    account.setSolde(account.getSolde() + Double.parseDouble(amount));

    accountDAO.saveAccount(account);

    List alltransaction = transactionDAO.getAllUserAccountTransactions();

    TransactionId transactionid = new TransactionId(alltransaction.size() + 1,
            (int) Integer.parseInt(accountnumber), (int) currentUser.getId());

    Transaction transaction = new Transaction(transactionid, account, new Date(), "+" + amount);

    transactionDAO.saveTransaction(transaction);

    return account;
}

From source file:uk.ac.ebi.emma.manager.AbstractManager.java

protected Session getCurrentSession() {
    if (username == null) {
        SecurityContext securityContext = SecurityContextHolder.getContext();
        if (securityContext == null)
            throw new RuntimeException("AbstractManager.getCurrentSession(): securityContext is null.");
        Authentication authentication = securityContext.getAuthentication();
        if (authentication == null)
            throw new RuntimeException("AbstractManager.getCurrentSession(): authentication is null.");
        String name = authentication.getName();
        if (name == null)
            throw new RuntimeException("AbstractManager.getCurrentSession(): name is null.");
        username = name;//w w  w  . j a  va2s .  c o  m
    }

    return sessionFactory.getCurrentSession();
}