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:fi.helsinki.opintoni.security.CustomAuthenticationSuccessHandler.java

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws IOException, ServletException {
    AppUser appUser = (AppUser) authentication.getPrincipal();

    try {/*from  w  w w .  ja va  2s .  c o  m*/
        syncUserWithDatabase(appUser);

        addLanguageCookie(appUser, response);
        addLastLoginCookie(response);
        addHasLoggedInCookie(response);

        response.sendRedirect("/");

    } catch (OodiIntegrationException e) {
        response.sendRedirect("/error/maintenance");
    }

}

From source file:oobbit.orm.Users.java

public User getCurrentUser() throws SQLException, NothingWasFoundException, NotLoggedInException {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    if (auth.getPrincipal().equals("anonymousUser")) {
        throw new NotLoggedInException("You are not logged in.");
    }//from   w w w.  j  a va2  s  .co m

    return this.get((String) auth.getPrincipal());
}

From source file:de.hybris.platform.acceleratorstorefrontcommons.security.AbstractAcceleratorAuthenticationProvider.java

@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
    final String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED"
            : authentication.getName();/*from  w  w  w . ja v  a  2s. co  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);
        }

        throw new BadCredentialsException(
                messages.getMessage("CoreAuthenticationProvider.badCredentials", "Bad credentials"));

    }

    return super.authenticate(authentication);

}

From source file:com.mycompany.apps.web.resources.MemberResource.java

@GET
@Path("/getMyInfo")
public String getMyInfo() {

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    com.mycompany.apps.domain.dto.Users principal = (com.mycompany.apps.domain.dto.Users) auth.getPrincipal();

    Users users = usersMapper.selectByUsername(principal.getUsername());
    if (users == null) {
        throw new UnsupportedOperationException("User not found...");
    }/*w  w  w  . j a v  a 2s .  c  om*/
    return "\n\tProtected Resource(getMyInfo) Accessed !!!! Returning from Myresource getMyInfo";
}

From source file:fi.helsinki.opintoni.security.SecurityUtils.java

public String getCurrentLogin() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    Authentication authentication = securityContext.getAuthentication();
    String userName = null;//from w  ww  .j a va 2 s .  c om
    if (authentication != null) {
        if (authentication.getPrincipal() instanceof UserDetails) {
            UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
            userName = springSecurityUser.getUsername();
        } else if (authentication.getPrincipal() instanceof String) {
            userName = (String) authentication.getPrincipal();
        }
    }
    return userName;
}

From source file:br.com.sescacre.controleAcesso.bean.UsuarioBean.java

public UsuarioBean() {
    usuario = new Usuarios();
    SecurityContext context = SecurityContextHolder.getContext();
    if (context instanceof SecurityContext) {
        Authentication authentication = context.getAuthentication();
        if (authentication instanceof Authentication) {
            usuario.setLogin(((User) authentication.getPrincipal()).getUsername());
        }//from w  w w .jav  a2 s.c  o m
    }
}

From source file:handlers.CustomLoginSuccessHandler.java

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws ServletException, IOException {
    this.setDefaultTargetUrl(defaultSuccessUrl);
    String username = ((User) authentication.getPrincipal()).getUsername();
    userService.updateLastLoginAccess(username, new Date());
    HttpSession session = request.getSession();
    if (session != null) {
        String redirectUrl = (String) session.getAttribute("url_prior_login");
        if (redirectUrl != null) {
            logger.info("Redirigiendo usuario a : " + redirectUrl);
            // we do not forget to clean this attribute from session
            session.removeAttribute("url_prior_login");
            // then we redirect
            getRedirectStrategy().sendRedirect(request, response, redirectUrl);
        } else {/* ww  w  .  j  a v  a2s .c  om*/
            super.onAuthenticationSuccess(request, response, authentication);
        }
    } else {
        super.onAuthenticationSuccess(request, response, authentication);
    }
}

From source file:org.tibetjungle.demo.service.ContactServiceImpl.java

protected String getUsername() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    if (auth.getPrincipal() instanceof UserDetails) {
        return ((UserDetails) auth.getPrincipal()).getUsername();
    } else {//from   w ww.  ja  v a 2s .  c  o  m
        return auth.getPrincipal().toString();
    }
}

From source file:shiver.me.timbers.spring.security.jwt.JwtPrincipalAuthenticationConverterTest.java

@Test
@SuppressWarnings("unchecked")
public void Can_convert_a_jwt_principle_to_a_jwt_authentication() {

    final JwtPrincipal principal = mock(JwtPrincipal.class);

    final List<String> roles = mock(List.class);
    final String username = someString();
    final Collection<GrantedAuthority> authorities = asList(mock(GrantedAuthority.class),
            mock(GrantedAuthority.class), mock(GrantedAuthority.class));

    // Given//from   ww w.  ja v  a 2  s .  c  om
    given(principal.getUsername()).willReturn(username);
    given(principal.getRoles()).willReturn(roles);
    given(grantedAuthorityConverter.convert(roles)).willReturn((Collection) authorities);

    // When
    final Authentication actual = converter.convert(principal);

    // Then
    assertThat(actual.getPrincipal(), is((Object) username));
    assertThat(actual.getAuthorities(), is((Collection) authorities));
    assertThat(actual.isAuthenticated(), is(true));
}

From source file:de.knightsoftnet.validators.server.security.LoggedInChecker.java

/**
 * get logged in user.// w  w w. ja v a2s .c om
 *
 * @return UserData or null if no one is logged in
 */
public User getLoggedInUser() {
    User user = null;

    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null) {
        final Object principal = authentication.getPrincipal();

        // principal can be "anonymousUser" (String)
        if (principal instanceof UserDetails) {
            user = this.userDetailsConverter.convert((UserDetails) principal);
        }
    }
    return user;
}