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.apps.AjaxReloadContextController.java

@Override
protected ModelAndView handleContext(String contextName, Context context, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    if (!request.getContextPath().equals(contextName) && context != null) {
        try {/*from ww w.j  a  va 2  s . c  o  m*/
            logger.info("{} requested RELOAD of {}", request.getRemoteAddr(), contextName);
            context.reload();
            // Logging action
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            String name = auth.getName(); // get username logger
            logger.info(getMessageSourceAccessor().getMessage("probe.src.log.reload"), name, contextName);
        } catch (Exception e) {
            logger.error("Error during ajax request to RELOAD of '{}'", contextName, e);
        }
    }
    return new ModelAndView(getViewName(), "available",
            context != null && getContainerWrapper().getTomcatContainer().getAvailable(context));
}

From source file:de.tudarmstadt.ukp.clarin.webanno.webapp.WebAnnoLoggingFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
        throws IOException, ServletException {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null) {
        setLoggingUsername(authentication.getName());
    }/*from   w  w  w. java 2  s  .c  om*/
    try {
        chain.doFilter(req, resp);
    } finally {
        if (authentication != null) {
            clearLoggingUsername();
        }
    }
}

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

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

From source file:org.springmodules.jcr.jackrabbit.SpringSecurityTests.java

protected void onSetUpBeforeTransaction() throws Exception {
    SecurityContextHolder.getContext().setAuthentication(
            new TestingAuthenticationToken(new Object(), new Object(), new GrantedAuthority[] {}));

}

From source file:org.appverse.web.framework.backend.security.xs.SecurityHelper.java

/**
 * Retrieves the authenticated principal from security context
 * @return the principal name//from   ww  w  .  j  av a 2 s  .  c  o  m
 */
public static String getPrincipal() {
    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    return authentication.getName();
}

From source file:fi.vm.sade.organisaatio.resource.OrganisaatioDevResource.java

/**
 * Hakee autentikoituneen kyttjn roolit//ww  w  .  j  a  va2  s. co  m
 * @return Operaatio palauttaa samat kuin /cas/myroles. HUOM! Testikyttn tarkoitettu.
 */
@GET
@Path("/myroles")
@Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8")
@PreAuthorize("hasRole('ROLE_APP_ORGANISAATIOHALLINTA')")
public String getRoles() {
    StringBuilder ret = new StringBuilder("[");

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    ret.append("\"");
    ret.append(auth.getName());
    ret.append("\",");

    for (GrantedAuthority ga : auth.getAuthorities()) {
        ret.append("\"");
        ret.append(ga.getAuthority().replace("ROLE_", ""));
        ret.append("\",");
    }
    ret.setCharAt(ret.length() - 1, ']');
    return ret.toString();
}

From source file:com.devnexus.ting.repository.jpa.ScheduleItemRepositoryImpl.java

/** {@inheritDoc} */
@Override//from   w  w w  . j  a v a  2 s .  co m
public List<ScheduleItem> getScheduleForEvent(Long eventId) {

    final Session session = (Session) this.entityManager.getDelegate();
    Filter filter = session.enableFilter("userFilter");

    if (!(SecurityContextHolder.getContext().getAuthentication() instanceof AnonymousAuthenticationToken)) {
        final User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        filter.setParameter("userId", user.getId());
    } else {
        filter.setParameter("userId", -1L);
    }

    return this.entityManager
            .createQuery("select si from ScheduleItem si " + "where si.event.id = :eventId "
                    + "order by si.fromTime ASC, si.room.roomOrder ASC", ScheduleItem.class)
            .setParameter("eventId", eventId).getResultList();
}

From source file:org.apache.cxf.fediz.service.idp.beans.CacheTokenForWauthAction.java

public void submit(RequestContext context) {

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    Assert.isInstanceOf(STSUserDetails.class, auth.getDetails());
    final STSUserDetails stsUserDetails = (STSUserDetails) auth.getDetails();
    SecurityToken securityToken = stsUserDetails.getSecurityToken();

    Idp idpConfig = (Idp) WebUtils.getAttributeFromFlowScope(context, IDP_CONFIG);

    WebUtils.putAttributeInExternalContext(context, idpConfig.getRealm(), securityToken);
    LOG.info("Token [IDP_TOKEN=" + securityToken.getId() + "] for realm [" + idpConfig.getRealm()
            + "] successfully cached.");
}

From source file:BusinessLayer.service.AddAccountService.java

public void addAccount(Compte compte, String password) {

    CustomSecurityUser currentUser = (CustomSecurityUser) SecurityContextHolder.getContext().getAuthentication()
            .getPrincipal();//  w  w w .  j a va2s . 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.setUtilisateur(utilisateur);
    List comptes = accountDAO.getAllUserAccounts();

    CompteId compteid = new CompteId(comptes.size() + 1, currentUser.getId());
    compte.setId(compteid);

    accountDAO.addAccount(compte);

    List alltransaction = transactionDAO.getAllUserAccountTransactions();

    TransactionId transactionid = new TransactionId(alltransaction.size() + 1,
            (int) compte.getId().getIdCompte(), (int) currentUser.getId());

    Transaction transaction = new Transaction(transactionid, compte, new Date(), "+" + compte.getSolde());

    transactionDAO.saveTransaction(transaction);

}

From source file:org.zalando.stups.oauth2.spring.client.AccessTokenUtilsTest.java

@Test
public void testNonOAuth2Authentication() throws Exception {
    SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("foo", "bar"));
    assertThat(getAccessTokenFromSecurityContext().isPresent()).isFalse();
}