Example usage for org.springframework.security.core Authentication getPrincipal

List of usage examples for org.springframework.security.core Authentication getPrincipal

Introduction

In this page you can find the example usage for org.springframework.security.core Authentication getPrincipal.

Prototype

Object getPrincipal();

Source Link

Document

The identity of the principal being authenticated.

Usage

From source file:org.jasig.cas.audit.spi.TicketOrCredentialPrincipalResolver.java

protected String resolveFromInternal(final JoinPoint joinPoint) {
    final Object arg1 = joinPoint.getArgs()[0];
    if (arg1 instanceof Credentials) {
        return arg1.toString();
    } else if (arg1 instanceof String) {
        final Ticket ticket = this.ticketRegistry.getTicket((String) arg1);
        if (ticket instanceof ServiceTicket) {
            final ServiceTicket serviceTicket = (ServiceTicket) ticket;
            return serviceTicket.getGrantingTicket().getAuthentication().getPrincipal().getId();
        } else if (ticket instanceof TicketGrantingTicket) {
            final TicketGrantingTicket tgt = (TicketGrantingTicket) ticket;
            return tgt.getAuthentication().getPrincipal().getId();
        }//  ww  w  .j a  v a2 s .co  m
    } else {
        final SecurityContext securityContext = SecurityContextHolder.getContext();
        if (securityContext != null) {
            final Authentication authentication = securityContext.getAuthentication();

            if (authentication != null) {
                return ((UserDetails) authentication.getPrincipal()).getUsername();
            }
        }
    }
    return UNKNOWN_USER;
}

From source file:web.SecurityController.java

@RequestMapping(value = "/403", method = RequestMethod.GET)
public ModelAndView accesssDenied() {

    ModelAndView model = new ModelAndView();

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    if (!(auth instanceof AnonymousAuthenticationToken)) {
        UserDetails userDetail = (UserDetails) auth.getPrincipal();
        System.out.println(userDetail);

        model.addObject("username", userDetail.getUsername());
    }/*from   w ww .j  a  v  a 2  s  .  c om*/

    model.setViewName("403");
    return model;
}

From source file:controller.PresentatieController.java

@RequestMapping(value = { "/presentatie/inschrijven" }, method = RequestMethod.POST)
public @ResponseBody String register(@RequestBody Long id) throws JSONException {
    System.out.println(id);/*from w  w w .  jav a2s.c  o  m*/

    JSONObject output = new JSONObject();
    output.put("success", false);

    Presentation p = presentationRepository.findOne(id);
    if (p == null) {
        output.put("message", "Kan de presentatie niet vinden.");
        return output.toString();
    }

    //check for free spots
    if (p.getAttendees().size() == p.getLocation().getCapacity()) {
        output.put("message", "Er is geen plaats meer vrij");
        return output.toString();
    }

    //check if user is already attending presentation at this timeframe
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    User user = (User) auth.getPrincipal();

    if (!(user instanceof Student)) {
        output.put("message", "Enkel studenten kunnen zich inschrijven voor een presentatie");
        return output.toString();
    }

    Student student = (Student) user;
    HashMap<Date, List<TimeFrame>> timeframes = new HashMap<>();

    for (GuestRequest gr : student.getGuestRequests()) {
        Presentation pr = gr.getPresentation();
        if (!timeframes.containsKey(pr.getDate())) {
            timeframes.put(pr.getDate(), new ArrayList<TimeFrame>());
            timeframes.get(pr.getDate()).add(pr.getTimeFrame());
        }

        if (!timeframes.get(pr.getDate()).contains(pr.getTimeFrame())) {
            timeframes.get(pr.getDate()).add(pr.getTimeFrame());
        } else {
            output.put("message", "U heeft zich al ingeschreven voor een presentatie op hetzelfde tijdstip");
            return output.toString();
        }
    }

    GuestRequest n = new GuestRequest();
    n.setPresentation(p);
    n.setStudent(student);
    student.getGuestRequests().add(n);

    //p.getAttendees().add(student);        
    //presentationRepository.flush();

    guestRequestRepository.saveAndFlush(n);

    output.put("success", true);
    return output.toString();
}

From source file:nl.surfnet.spring.security.opensaml.SAMLResponseAuthenticationProvider.java

public Authentication authenticate(Authentication submitted) throws AuthenticationException {

    logger.debug("attempting to authenticate: {}", submitted);

    UserDetails user = assertionConsumer.consume((Response) submitted.getPrincipal());

    SAMLAuthenticationToken authenticated = new SAMLAuthenticationToken(user,
            (String) submitted.getCredentials(), user.getAuthorities());

    authenticated.setDetails(submitted.getDetails());

    logger.debug("Returning with authentication token of {}", authenticated);

    return authenticated;

}

From source file:edu.uiowa.icts.authentication.AuthHandle.java

/** {@inheritDoc} */
@Override//from w  w  w  .  ja  v a 2  s .  co m
public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse res, Authentication auth)
        throws IOException, ServletException {

    log.debug("successfully authenticated " + String.valueOf(auth.getPrincipal()));

    if (req.getSession().getAttribute("SPRING_SECURITY_LAST_EXCEPTION") != null) {
        req.getSession().removeAttribute("SPRING_SECURITY_LAST_EXCEPTION");
    }

    for (GrantedAuthority ga : auth.getAuthorities()) {
        log.debug(ga.getAuthority());
    }

    HttpSession session = req.getSession();
    String username = req.getParameter("j_username");
    session.setAttribute("username", username);

    AuditLogger.info(session.getId(), username, "logged in from", req.getRemoteHost());

    target.onAuthenticationSuccess(req, res, auth);

}

From source file:customer.springboot.controller.UserController.java

@RequestMapping(value = "/loggedin", method = RequestMethod.GET)
public User getUserLoggedIn() throws Exception {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth == null) {
        throw new Exception("Unauthenticated Request");
    }//from  w  w w  .  jav  a  2  s  .  co  m

    Object principal = auth.getPrincipal();
    if (principal == null) {
        throw new Exception("Invalid authentication object");
    }

    if (!org.springframework.security.core.userdetails.User.class.isAssignableFrom(principal.getClass())) {
        throw new Exception("Invalid authentication object" + principal.getClass().getName());
    }
    org.springframework.security.core.userdetails.User u = (org.springframework.security.core.userdetails.User) principal;
    return userDao.findByUsername(u.getUsername());
}

From source file:org.musicrecital.webapp.services.impl.SpringSecurityContext.java

public boolean isLoggedIn() {

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null && authentication.getPrincipal() != null) {
        if ("anonymousUser".equals(authentication.getName())) {
            return false;
        }//from   w  ww.  j  a v  a 2s  .c o m
        return authentication.isAuthenticated();
    }
    return false;
}

From source file:CRM.web.MishaSecurityController.java

@RequestMapping(value = "/403", method = RequestMethod.GET)
public ModelAndView accessDenied() {

    ModelAndView model = new ModelAndView();

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    if (!(auth instanceof AnonymousAuthenticationToken)) {
        UserDetails userDetail = (UserDetails) auth.getPrincipal();
        System.out.println(userDetail);

        model.addObject("username", userDetail.getUsername());
    }/*  w  w  w.j a v  a2s. c o  m*/

    model.setViewName("403");
    return model;
}

From source file:dicky.controlleradmin.MainController.java

@RequestMapping(value = "/403", method = RequestMethod.GET)
public String accessDenied(ModelMap modelMap) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (!(auth instanceof AnonymousAuthenticationToken)) {
        UserDetails userDetails = (UserDetails) auth.getPrincipal();
        modelMap.addAttribute("username", userDetails.getUsername());
    }/*w  w w . j av  a 2  s.co m*/
    return "admin.main.403";
}

From source file:org.mzd.shap.spring.web.AbstractControllerSupport.java

/**
 * Get the authenticated user from the SecurityContext.
 * /*from w  w w . j av  a  2 s . c o m*/
 * @return user
 * @throws NotFoundException
 */
protected User getSessionUser() throws NotFoundException {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth != null) {
        User user = (User) auth.getPrincipal();
        if (user == null) {
            throw new NotFoundException("Authentication principle was null");
        }
        logger.debug(user);
        return user;
    }
    throw new NotFoundException("SecurityContext contained no authentication instance");
}