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:sk.lazyman.gizmo.security.GizmoAuthProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String principal = (String) authentication.getPrincipal();
    if (StringUtils.isBlank(principal)) {
        throw new BadCredentialsException("web.security.provider.invalid");
    }//  ww w.j  a  va  2  s .c om

    if (useLdapAuth()) {
        return authenticateUsingLdap(authentication);
    }

    return authenticateUsingDb(authentication);
}

From source file:org.ngrinder.user.service.UserContext.java

/**
 * Get current user object from context.
 *
 * @return current user;/*from  www  .  j av  a 2s .com*/
 */
public User getCurrentUser() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth == null) {
        throw new AuthenticationCredentialsNotFoundException("No authentication");
    }
    Object obj = auth.getPrincipal();
    if (!(obj instanceof SecuredUser)) {
        throw new AuthenticationCredentialsNotFoundException("Invalid authentication with " + obj);
    }
    SecuredUser securedUser = (SecuredUser) obj;
    return securedUser.getUser();
}

From source file:it.av.youeat.web.security.FacebookAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    HttpServletRequest request = (HttpServletRequest) authentication.getPrincipal();

    FacebookJaxbRestClient authClient;//from  ww w  .  jav  a2 s . c om
    try {
        authClient = bookAuthHandler.getAuthenticatedClient(request);
        String facebookSession = authClient.getCacheSessionKey();
        long facebookUserId = authClient.users_getLoggedInUser();

        Eater eater = eaterService.getBySocialUID(Long.toString(facebookUserId), SocialType.FACEBOOK);
        checkAndCreateUser(authClient, facebookUserId, eater);

        eater = eaterService.getBySocialUID(Long.toString(facebookUserId), SocialType.FACEBOOK);
        eater.setSocialSessionKey(facebookSession);
        Authentication authenticationToReturn = new FacebookAuthenticationToken(new UserDetailsImpl(eater));
        authenticationToReturn.setAuthenticated(true);
        return authenticationToReturn;
    } catch (Exception e) {
        log.info("Facebook session not available");
    }
    return authentication;

}

From source file:br.com.hslife.orcamento.component.UsuarioComponent.java

public Usuario getUsuarioLogado() {
    try {//from  ww w  . j  a  v a2s  .c o m
        String login = "";
        SecurityContext context = SecurityContextHolder.getContext();
        if (context instanceof SecurityContext) {
            Authentication authentication = context.getAuthentication();
            if (authentication instanceof Authentication) {
                login = ((User) authentication.getPrincipal()).getUsername();
            }
        }
        return getService().buscarPorLogin(login);
    } catch (Throwable t) {
        logger.catching(t);
        throw new RuntimeException(t);
    }
}

From source file:br.com.officium.beans.UsuarioBean.java

@PostConstruct
public void ini() {
    usuario = new Usuario();
    SecurityContext context = SecurityContextHolder.getContext();

    if (context instanceof SecurityContext) {
        Authentication authentication = context.getAuthentication();
        if (authentication instanceof Authentication) {
            try {
                usuario = getUsuarioDao().logon(((User) authentication.getPrincipal()).getUsername(),
                        ((User) authentication.getPrincipal()).getPassword());
            } catch (Exception ex) {
                Logger.getLogger(UsuarioBean.class.getName()).log(Level.SEVERE, null, ex);
            }//from ww  w  .j  a v a2s.c  o  m
            usuario.setUsername(((User) authentication.getPrincipal()).getUsername());
        }
    }

}

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

public void decide(Authentication authentication, Object securityObject,
        Collection<ConfigAttribute> configAttributes)
        throws AccessDeniedException, InsufficientAuthenticationException {

    try {//from ww w.j  a v a 2 s.c  o m
        if (authentication.getPrincipal() instanceof String
                && "anonymousUser".equals(authentication.getPrincipal())) {
            throw new AccessDeniedException(" no permission access?");
        }
        return;
    } catch (Exception e) {
        throw new AccessDeniedException("Role check fails.");
    }
}

From source file:eu.supersede.fe.rest.NotificationRest.java

@RequestMapping("/count")
public Long countByUserId(Authentication authentication, @RequestParam(defaultValue = "true") Boolean toRead) {
    DatabaseUser currentUser = (DatabaseUser) authentication.getPrincipal();
    User u = users.getOne(currentUser.getUserId());
    Long c;/* ww w .ja  v a  2 s  .  c o m*/

    if (toRead) {
        c = notifications.countByUserAndRead(u, !toRead);
    } else {
        c = notifications.countByUser(u);
    }

    return c;
}

From source file:at.ac.univie.isc.asio.security.HttpMethodRestrictionFilterTest.java

@Test
public void should_keep_anonymous_type() throws Exception {
    final AnonymousAuthenticationToken token = new AnonymousAuthenticationToken("key", "principal",
            Collections.<GrantedAuthority>singletonList(Permission.INVOKE_UPDATE));
    token.setDetails("details");
    setAuthentication(token);//from   www.j a v a2 s  .c  om
    request.setMethod(HttpMethod.GET.name());
    subject.doFilter(request, response, chain);
    final Authentication filtered = getAuthentication();
    assertThat(filtered, instanceOf(AnonymousAuthenticationToken.class));
    assertThat(filtered.getPrincipal(), equalTo(token.getPrincipal()));
    assertThat(filtered.getDetails(), equalTo(token.getDetails()));
}

From source file:com.cami.web.controller.LeController.java

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

    ModelAndView model = new ModelAndView();

    //check if user is login
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (!(auth instanceof AnonymousAuthenticationToken)) {
        UserDetails userDetail = (UserDetails) auth.getPrincipal();
        model.addObject("username", userDetail.getUsername());
    }/*from  w  w w  . j  a  va  2s.  c om*/

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

}

From source file:com.epam.cme.storefront.security.AcceleratorAuthenticationProvider.java

@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
    final String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED"
            : authentication.getName();//  w  w w  .  ja  v a 2s  .  c  o m

    if (getBruteForceAttackCounter().isAttack(username)) {
        try {
            final UserModel userModel = getUserService().getUserForUID(StringUtils.lowerCase(username));
            userModel.setLoginDisabled(true);
            getModelService().save(userModel);
            bruteForceAttackCounter.resetUserCounter(userModel.getUid());
        } catch (final UnknownIdentifierException e) {
            LOG.warn("Brute force attack attempt for non existing user name " + username);
        } finally {
            throw new BadCredentialsException(
                    messages.getMessage("CoreAuthenticationProvider.badCredentials", "Bad credentials"));
        }
    }
    checkUserCart(username);
    return super.authenticate(authentication);
}