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:ru.mystamps.web.support.spring.security.CustomUserDetailsArgumentResolver.java

@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
        NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {

    SecurityContext ctx = SecurityContextHolder.getContext();
    Validate.validState(ctx != null, "Security context must be non null");

    Authentication auth = ctx.getAuthentication();
    if (auth == null) {
        return null;
    }//  www  . j  a v  a  2 s.  c  o m

    Object principal = auth.getPrincipal();
    if (principal == null) {
        return null;
    }

    if (isSupportedType(principal.getClass())) {
        return principal;
    }

    return null;
}

From source file:com.devicehive.auth.rest.providers.BasicAuthenticationProvider.java

@SuppressWarnings("unchecked")
@Override//w  w w  . j a v  a  2  s.  c o m
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String key = (String) authentication.getPrincipal();
    String pass = (String) authentication.getCredentials();
    logger.debug("Basic authentication requested for username {}", key);

    UserVO user = null;
    try {
        user = userService.authenticate(key, pass);
    } catch (HiveException e) {
        logger.error("User auth failed", e);
    }
    if (user != null && user.getStatus() == UserStatus.ACTIVE) {
        String role = user.isAdmin() ? HiveRoles.ADMIN : HiveRoles.CLIENT;
        logger.info("User {} authenticated with role {}", key, role);

        HivePrincipal principal = new HivePrincipal(user);

        if (user.isAdmin()) {
            Set<String> allActions = AvailableActions.getAllActions();
            Set<HiveAction> allowedActions = new HashSet<>();
            allActions.forEach(action -> allowedActions.add(HiveAction.fromString(action)));
            principal.setActions(allowedActions);
        } else {
            String[] actions = AvailableActions.getClientActions();
            Set<HiveAction> allowedActions = new HashSet<>();
            for (String action : actions)
                allowedActions.add(HiveAction.fromString(action));
            principal.setActions(allowedActions);
        }

        return new HiveAuthentication(principal, AuthorityUtils.createAuthorityList(role));

    }
    logger.warn("Basic auth for {} failed", key);
    throw new BadCredentialsException("Invalid credentials");
}

From source file:com.hp.autonomy.frontend.find.idol.authentication.IdolPreAuthenticatedAuthenticationProvider.java

@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
    final Object principal = authentication.getPrincipal();

    if (principal == null) {
        throw new BadCredentialsException("Principal not supplied");
    }/*from  w w  w.j ava 2s . co  m*/

    final String username = principal.toString().toLowerCase();

    UserRoles user;

    try {
        user = userService.getUser(username);
    } catch (final AciErrorException e) {
        log.debug("Failed to fetch the user", e);

        if (USER_NOT_FOUND_ERROR_ID.equals(e.getErrorId())) {
            // use empty password so that auto created users cannot be authenticated against
            this.userService.addUser(username, "", UserConfiguration.IDOL_USER_ROLE);

            user = userService.getUser(username);
        } else {
            throw e;
        }
    }

    final Collection<SimpleGrantedAuthority> grantedAuthorities = new HashSet<>();

    for (final String role : user.getRoles()) {
        grantedAuthorities.add(new SimpleGrantedAuthority(role));
    }

    return new UsernamePasswordAuthenticationToken(
            new CommunityPrincipal(user.getUid(), username, user.getSecurityInfo()), null,
            authoritiesMapper.mapAuthorities(grantedAuthorities));
}

From source file:com.klm.workshop.controller.HomeController.java

/**
 * Redirects the client to the right page, based on their current action
 * // w w  w  . java2s  .  c o  m
 * @return The redirect URL
 */
@RequestMapping(value = "/", method = RequestMethod.GET)
public String redirect() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    CustomUserDetails userDetails = (CustomUserDetails) auth.getPrincipal();

    switch (userDetails.getUser().getAction()) {
    case User.ACTION_HOST:
        return "redirect:/host/manage/dashboard/index";
    case User.ACTION_PARTICIPATE:
        return "redirect:/participant/dashboard/index";
    default:
        return "redirect:/auth/logout";
    }
}

From source file:architecture.user.security.authentication.impl.DefaultAuthenticationProvider.java

private boolean isGranted(String role) {

    Authentication auth = getAuthentication();
    if ((auth == null) || (auth.getPrincipal() == null)) {
        return false;
    }//from w ww. ja v a  2s.co  m
    Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();
    if (authorities == null) {
        return false;
    }
    for (GrantedAuthority grantedAuthority : authorities) {
        if (role.equals(grantedAuthority.getAuthority())) {
            return true;
        }
    }
    return false;
}

From source file:ch.wisv.areafiftylan.users.controller.CurrentUserRestController.java

/**
 * Get the seats of the current user/*from   w ww  .  j  av  a2 s. c  om*/
 *
 * @param auth Currently logged in user
 *
 * @return Returns a list of reserved seats by the user
 */
@RequestMapping(value = "/seat", method = RequestMethod.GET)
public List<Seat> getCurrentUserSeat(Authentication auth) {
    User user = (User) auth.getPrincipal();

    return seatService.getSeatsByUsername(user.getUsername());
}

From source file:com.restfiddle.controller.AppController.java

@RequestMapping("/")
public String home(Map<String, Object> model) {
    model.put("time", new Date());
    model.put("message", this.message);
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    model.put("currentUser", (authentication == null) ? null : (UserDetails) authentication.getPrincipal());
    return "home";
}

From source file:org.openmrs.contrib.metadatarepository.service.UserSecurityAdvice.java

private User getCurrentUser(Authentication auth) {
    User currentUser;//from   w w w.j a va 2 s.  co  m
    if (auth.getPrincipal() instanceof UserDetails) {
        currentUser = (User) auth.getPrincipal();
    } else if (auth.getDetails() instanceof UserDetails) {
        currentUser = (User) auth.getDetails();
    } else {
        throw new AccessDeniedException("User not properly authenticated.");
    }
    return currentUser;
}

From source file:com.javiermoreno.springboot.modelo.GestionPersonasServiceImpl.java

@Transactional
@Override// ww  w. j  a va  2s  .c  om
public Persona registrarNuevaPersona(Persona persona) {
    em.persist(persona);
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null) {
        Object principal = authentication.getPrincipal();
        String username;
        if (principal instanceof UserDetails) {
            username = ((UserDetails) principal).getUsername();
        } else {
            username = principal.toString();
        }
        System.out.format("Nueva persona registrada por {0}.", username);
    }
    return persona;
}

From source file:nz.net.orcon.kanban.controllers.HomeController.java

/**
 * Selects the home page and populates the model with a message
 *//*  ww  w  .  ja va2s.c om*/
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Model model) {
    log.info("Home Sweet Home");
    log.info(springSecurityFilterChain.getClass().getName());

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth != null) {
        String principle = (String) auth.getPrincipal();
        log.info(principle);
    }

    model.addAttribute("message", "Hello");
    return "home";
}