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:com.jeanchampemont.notedown.security.AuthenticationService.java

public boolean isAuthenticated() {
    return (SecurityContextHolder.getContext().getAuthentication() != null);
}

From source file:de.chludwig.websec.saml2sp.springconfig.CurrentUserHandlerMethodArgumentResolver.java

public static ApplicationUser getCurrentUser() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    Authentication auth = (securityContext == null) ? null : securityContext.getAuthentication();
    if (auth == null || auth instanceof AnonymousAuthenticationToken) {
        return new AnonymousUser();
    } else {//  ww  w  . j  ava2 s.  com
        SAMLCredential samlCredential = getSamlCredential(auth);
        String userId = getUserId(auth, samlCredential);
        String userName = getUserName(auth, samlCredential);
        Set<RoleId> roles = getUserRoles(auth);
        AuthenticationStatus authenticationStatus = getAuthenticationStatus(samlCredential);
        return new LoggedInUser(userId, userName, roles, authenticationStatus);
    }
}

From source file:BusinessLayer.service.WithdrawService.java

public Compte depositinAccount(String accountnumber, String password, String amount) {
    CustomSecurityUser currentUser = (CustomSecurityUser) SecurityContextHolder.getContext().getAuthentication()
            .getPrincipal();/*from   w  w  w.  ja v  a  2  s  .  co  m*/
    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();
    }

    if (account.getSolde() - Double.parseDouble(amount) < 0) {
        throw new InsufficientBalanceException();
    }

    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:com.mycompany.doctorapp.services.PatientService.java

public void addSickness(Sickness sickness) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    String username = auth.getName();
    System.out.println(username);
    Patient authpatient = patientRepository.findByUsername(username);

    if (authpatient == null) {
        System.out.println("patient not found");
    }//from w  ww . j  av  a 2  s  .c  o m

    Doctor doctor = authpatient.getOwnDoctor();

    if (doctor == null) {
        System.out.println("No medic found");
    }
    //if no list of treated sicknesses exists for the patient already, create one
    if (authpatient.getSickness() == null) {
        List<Sickness> lista = new ArrayList<>();
        lista.add(sickness);
        authpatient.setSickness(lista);
    } else {
        authpatient.getSickness().add(sickness);
    }

    sickness.setTreatmentStatus(false);

    //if no list of treated sicknesses exists for the doctor already, create one
    if (doctor.getTreatedSicknesses() == null) {
        List<Sickness> lista = new ArrayList<>();
        lista.add(sickness);
        doctor.setTreatedSicknesses(lista);
    } else {
        doctor.getTreatedSicknesses().add(sickness);
    }

    sicknessRepository.save(sickness);
    patientRepository.save(authpatient);

    sickness.setPatient(authpatient);
    sickness.setDoctor((doctor));

    sicknessRepository.save(sickness);

}

From source file:org.vaadin.spring.security.internal.VaadinManagedSecurity.java

@Override
public Authentication login(Authentication authentication, boolean rememberMe) throws AuthenticationException {
    if (rememberMe) {
        throw new UnsupportedOperationException(
                "Remember Me is currently not supported when using managed security");
    }//from ww  w.  j  a va 2 s . co m
    SecurityContext context = SecurityContextHolder.getContext();
    logger.debug("Authenticating using {}, rememberMe = {}", authentication, rememberMe);
    final Authentication fullyAuthenticated = getAuthenticationManager().authenticate(authentication);
    logger.debug("Setting authentication of context {} to {}", context, fullyAuthenticated);
    context.setAuthentication(fullyAuthenticated);
    return fullyAuthenticated;
}

From source file:jp.pigumer.sso.Application.java

@RequestMapping(value = "/saml/idpSelection", method = RequestMethod.GET)
public String idpSelection(HttpServletRequest request, Model model) {
    if (!(SecurityContextHolder.getContext().getAuthentication() instanceof AnonymousAuthenticationToken)) {
        return "redirect:/landing";
    } else {//  www . ja va  2 s. c o  m
        if (isForwarded(request)) {
            Set<String> idps = metadata.getIDPEntityNames();
            model.addAttribute("idps", idps);
            return "saml/idpselection";
        } else {
            return "redirect:/";
        }
    }
}

From source file:nc.noumea.mairie.appock.services.impl.AuthHelperImpl.java

@Override
public boolean hasCurrentUserRole(Role role) {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication == null) {
        return false;
    }//from  w w w  . j  a  va 2  s  . c om
    for (GrantedAuthority ga : authentication.getAuthorities()) {
        if (ga.getAuthority().equals(role.name()))
            return true;
    }
    return false;
}

From source file:com.orange.clara.tool.controllers.AbstractDefaultController.java

protected User getCurrentUser() {
    SecurityContext securityContext = this.getSecurityContext();
    if (securityContext == null || securityContext.getAuthentication() == null
            || securityContext.getAuthentication().getPrincipal() == null) {
        return null;
    }/* ww w .  j av  a2 s .c  o  m*/
    Principal principal = (Principal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    return this.userRepo.findOne(principal.getName());
}

From source file:cz.cvut.fel.wpa.tracker.pres.bb.LoginBean.java

public String logout() {
    SecurityContextHolder.getContext().setAuthentication(null);
    FacesContext.getCurrentInstance().getExternalContext().getSessionMap().clear();
    FacesContext.getCurrentInstance().addMessage(null,
            new FacesMessage(FacesMessage.SEVERITY_INFO, "Loged out", null));
    return "login";
}

From source file:com.seyren.core.security.AuthenticationTokenFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (!seyrenConfig.isSecurityEnabled()) {
        SecurityContextHolder.getContext().setAuthentication(new SecurityDisabledAuthentication());
    } else {/*from  ww w  .  j  a  v a 2s  .  co  m*/
        HttpServletRequest httpRequest = this.getAsHttpRequest(request);

        String authToken = this.extractAuthTokenFromRequest(httpRequest);
        String userName = Token.getUserNameFromToken(authToken);

        if (userName != null) {
            UserDetails userDetails = this.userService.loadUserByUsername(userName);

            if (Token.validateToken(authToken, userDetails)) {

                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest));
                SecurityContextHolder.getContext().setAuthentication(authentication);

            }
        }
    }

    chain.doFilter(request, response);
}