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:com.gcrm.security.AuthenticationSuccessListener.java

public void attributeAdded(HttpSessionBindingEvent se) {
    String sessionName = se.getName();
    if (sessionName.equals("SPRING_SECURITY_CONTEXT")) {
        SecurityContext securityContext = (SecurityContext) se.getSession()
                .getAttribute("SPRING_SECURITY_CONTEXT");
        Authentication authentication = securityContext.getAuthentication();
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        se.getSession().setAttribute(LOGIN_USER, userDetails.getUser());
    }//w  ww.ja v  a  2 s.  c o m
}

From source file:com.gcrm.security.AuthenticationSuccessListener.java

public void attributeReplaced(HttpSessionBindingEvent se) {
    String sessionName = se.getName();
    if (sessionName.equals("SPRING_SECURITY_CONTEXT")) {
        SecurityContext securityContext = (SecurityContext) se.getSession()
                .getAttribute("SPRING_SECURITY_CONTEXT");
        Authentication authentication = securityContext.getAuthentication();
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        se.getSession().setAttribute(LOGIN_USER, userDetails.getUser());
    }/*from  w w  w  .j  a v a  2  s.  c o m*/
}

From source file:com.gs.config.ItemIdBasedAuthenticationSuccessHandler.java

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws IOException, ServletException {
    User user = (User) authentication.getPrincipal();
    request.getSession().setAttribute("TOOLS", obtenerHerrDptosByUser.getDptoByUsername(user.getUsername()));
    for (Iterator iterator = user.getAuthorities().iterator(); iterator.hasNext();) {
        String autority = iterator.next().toString();
        //Obtengo el contexto de la direccin IP y la agrego al objeto session
        request.getSession().setAttribute("ENVIRONMENT", request.getParameter("environment"));
        if (autority.equalsIgnoreCase("ROLE_COORDINADOR") || autority.equalsIgnoreCase("ROLE_TECNICO")) {
            //Agrego el nmero de mensajes nos ledos a un atributo sesin.
            String rol = (autority.equalsIgnoreCase("ROLE_COORDINADOR") ? "ROLE_COORDINADOR" : "ROLE_TECNICO");
            request.getSession().setAttribute("NUM_MSJ_N_L",
                    mensajesBandejaDaoImp.getMensajesNoLeidosUser(user.getUsername(), rol));
            break;
        }//from w  w  w  .j a  v  a 2  s  . co m
    }
    super.onAuthenticationSuccess(request, response, authentication);
    //            String redirectUrl = request.getContextPath() + "/";
    //            System.out.println("-----------------------------INICIO DE SESIN EXTITOSO-----------------------------");
    //            System.out.println("informacin: " + authentication.getDetails().toString());
    //            response.sendRedirect(redirectUrl);
}

From source file:org.shredzone.cilla.ws.cxf.SecurityContextCallback.java

@Override
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
    for (Callback callback : callbacks) {
        WSPasswordCallback pc = (WSPasswordCallback) callback;
        if (pc.getUsage() == WSPasswordCallback.USERNAME_TOKEN) {
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            if (auth != null && auth.getPrincipal() != null
                    && auth.getPrincipal() instanceof RemoteUserDetails) {
                RemoteUserDetails rud = (RemoteUserDetails) auth.getPrincipal();
                pc.setIdentifier(rud.getUsername());
                pc.setPassword(rud.getPassword());
                log.debug("Sent credentials for user {}", rud.getUsername());
            } else {
                log.error("No useable authentication found");
            }/*from   www  . j a va 2  s.c o  m*/
        }
    }
}

From source file:ch.wisv.areafiftylan.products.controller.TicketRestController.java

@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/tokens", method = RequestMethod.GET)
public ResponseEntity<?> getTicketTokensOpenForTransfer(Authentication auth) {
    UserDetails currentUser = (UserDetails) auth.getPrincipal();
    Collection<TicketTransferToken> tokens = ticketService
            .getValidTicketTransferTokensByUser(currentUser.getUsername());

    return createResponseEntity(HttpStatus.OK, "Ticket transfer tokens successfully retrieved.", tokens);
}

From source file:org.apigw.authserver.shibboleth.ShibbolethSamlUserDetailsService.java

@Override
public UserDetails loadUserDetails(Authentication token) throws UsernameNotFoundException {
    final Map<String, String> principal = (Map) token.getPrincipal(); //TODO: principal should be something better
    final String subjectSerialNumber = principal.get("subjectSerialNumber");
    final String subjectCommonName = principal.get("subjectCommonName");
    if (subjectSerialNumber != null && ssnPattern.matcher(subjectSerialNumber).matches()) {
        final User user = new User(subjectSerialNumber, grantedAuthorities);
        user.setFullName(subjectCommonName);
        user.setEnabled(true);//from ww  w . ja  va2  s  . co  m
        logger.debug("returning user");
        return user;
    }
    throw new UsernameNotFoundException("expected subjectSerialNumber but couldn't find it");
}

From source file:org.jtalks.poulpe.security.AclAwareDecisionVoter.java

/** @return user name from {@link Authentication} token credentials*/
private String usernameOf(Authentication authentication) {
    return ((UserDetails) authentication.getPrincipal()).getUsername();
}

From source file:authentication.jwt.JwtAuthenticationManager.java

/** {@inheritDoc} */
@Override/*  w  w w. j ava 2  s.  c om*/
public Authentication authenticate(final Authentication auth) throws AuthenticationException {
    final String token = String.valueOf(auth.getPrincipal()).substring(6).trim();
    final JWT jwt;
    final ReadOnlyJWTClaimsSet claims;

    try {
        jwt = JWTParser.parse(token);
        claims = jwt.getJWTClaimsSet();
    } catch (final ParseException exception) {
        throw new JwtTokenException("The given JWT could not be parsed.");
    }

    for (final JwtVerifier verifier : verifiersList) {
        verifier.verify(jwt);
    }

    final String username = claims.getSubject();
    return new PreAuthenticatedAuthentication(repository.getByUsername(username));
}

From source file:com.seyren.api.bean.UsermanagementBean.java

@Override
public Response getUser() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    Object principal = authentication.getPrincipal();
    if (principal instanceof String && principal.equals("anonymousUser")) {
        throw new WebApplicationException(401);
    }//  w w w . j  ava 2s. c o  m
    UserDetails userDetails = (UserDetails) principal;

    return Response.ok(userDetails).build();
}

From source file:org.watterssoft.appsupport.user.ui.AuthenicatedUserController.java

@RequestMapping(value = "/retrieve", method = RequestMethod.GET, produces = "application/json")
public @ResponseBody UserRoles authenticatedUser() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    if (authentication == null || !(authentication.getPrincipal() instanceof UserDetails)) {
        return null;
    }/* w  w  w .j  a v a2s .  c  om*/
    UserDetails userDetails = (UserDetails) authentication.getPrincipal();
    Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
    ArrayList<GrantedAuthority> grantedRoles = new ArrayList<GrantedAuthority>(authorities);
    UserRoles userRoles = new UserRoles(userDetails.getUsername(), grantedRoles);
    return userRoles;
}