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.cloudfoundry.identity.uaa.authentication.manager.LoginAuthenticationManagerTests.java

@Test
public void testHappyDayAutoAddButWithExistingUser() {
    manager.setAddNewAccounts(true);/* w ww. j av a  2  s .c  om*/
    UaaUser user = UaaUserTestFactory.getUser("FOO", "foo", "fo@test.org", "Foo", "Bar");
    Mockito.when(userDatabase.retrieveUserByName("foo")).thenReturn(user);
    Authentication authentication = manager
            .authenticate(UaaAuthenticationTestFactory.getAuthenticationRequest("foo"));
    assertEquals(user.getUsername(), ((UaaPrincipal) authentication.getPrincipal()).getName());
    assertEquals(user.getId(), ((UaaPrincipal) authentication.getPrincipal()).getId());
}

From source file:org.cloudfoundry.identity.uaa.authentication.manager.LoginAuthenticationManagerTests.java

@Test(expected = BadCredentialsException.class)
public void testFailedAutoAddButWithNewUser() {
    manager.setAddNewAccounts(true);/*from w ww.j a  v a2 s  .co m*/
    UaaUser user = UaaUserTestFactory.getUser("FOO", "foo", "fo@test.org", "Foo", "Bar");
    Mockito.when(userDatabase.retrieveUserByName("foo")).thenThrow(new UsernameNotFoundException("planned"));
    Authentication authentication = manager
            .authenticate(UaaAuthenticationTestFactory.getAuthenticationRequest("foo"));
    assertEquals(user.getUsername(), ((UaaPrincipal) authentication.getPrincipal()).getName());
    assertEquals(user.getId(), ((UaaPrincipal) authentication.getPrincipal()).getId());
}

From source file:org.web4thejob.security.SpringSecurityService.java

@Override
public boolean renewPassword(UserIdentity userIdentity, String oldPassword, String newPassword) {
    if (isPasswordValid(userIdentity, oldPassword)) {
        ContextUtil.getDRS().refresh(userIdentity);
        userIdentity.setCredentialsNonExpired(true);
        userIdentity.setPassword(ContextUtil.getSecurityService().encodePassword(userIdentity, newPassword));
        ContextUtil.getDWS().save(userIdentity);
        Authentication authentication = ContextUtil.getSecurityService().authenticate(userIdentity.getCode(),
                newPassword);/* w ww .j  a  v  a  2 s  .com*/
        if (authentication != null && authentication.getPrincipal() instanceof UserDetailsEx
                && ((UserDetailsEx) authentication.getPrincipal()).getUserIdentity().equals(userIdentity)) {
            SecurityContextHolder.getContext().setAuthentication(authentication);
            return true;
        }
    }
    return false;
}

From source file:com.eazytec.webapp.filter.CustomAuthenticationProvider.java

License:asdf

public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String username = String.valueOf(authentication.getPrincipal()).toLowerCase();
    String password = String.valueOf(authentication.getCredentials());
    logger.debug("Checking authentication for user {}" + username);
    logger.debug("userResponse: {}" + captchaCaptureFilter.getCaptcha_response());
    if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
        throw new BadCredentialsException("No Username and/or Password Provided.");
    }//from   w w  w  . ja  v  a 2  s. co m

    licensePreCheck();

    Boolean isCaptchaNeeded = Boolean
            .valueOf(PropertyReader.getInstance().getPropertyFromFile("Boolean", "system.captcha.needed"));

    Boolean adEnabled = Boolean
            .valueOf(PropertyReader.getInstance().getPropertyFromFile("Boolean", "system.ad.enabled"));

    // if(!adEnabled){

    if (isCaptchaNeeded && StringUtils.isBlank(captchaCaptureFilter.getCaptcha_response())) {
        throw new BadCredentialsException("Captcha Response is Empty");
    }

    if (isCaptchaNeeded) {
        // else {
        // Send HTTP request to validate user's Captcha
        boolean captchaPassed = SimpleImageCaptchaServlet.validateCaptcha(
                captchaCaptureFilter.getCaptcha_challenge(), captchaCaptureFilter.getCaptcha_response());

        // Check if valid
        if (captchaPassed) {
            logger.debug("Captcha is valid!");
            resetCaptchaFields();
        } else {
            logger.debug("Captcha is invalid!");
            resetCaptchaFields();

            throw new BPMAccountStatusException(I18nUtil.getMessageProperty("errors.captcha.mismatch"));
        }
    }
    User user = null;
    if (!adEnabled) {
        user = userService.getUserById(username);
    }
    if (user == null && adEnabled) {
        throw new BadCredentialsException(I18nUtil.getMessageProperty("errors.password.mismatch"));
    }
    if (user == null || !user.isEnabled() && !adEnabled) {
        throw new BPMAccountStatusException(I18nUtil.getMessageProperty("errors.password.mismatch"));
    }
    if (passwordEncoder.isPasswordValid(user.getPassword(), password, saltSource.getSalt(user))) {
        Set<GrantedAuthority> authorityList = (Set<GrantedAuthority>) user.getAuthorities();
        return new UsernamePasswordAuthenticationToken(user, password, authorityList);
    } else {
        if (adEnabled) {
            throw new BadCredentialsException(I18nUtil.getMessageProperty("errors.password.mismatch"));
        } else {
            throw new BPMAccountStatusException(I18nUtil.getMessageProperty("errors.password.mismatch"));
        }
    }
}

From source file:com.rockagen.gnext.service.spring.security.extension.BasicPrincipal.java

/**
 * Instantiates a new smart principal.//from   ww w .jav a  2  s  . co  m
 * 
 * @param authentication
 *            the authentication
 */
public BasicPrincipal(Authentication authentication) {
    Assert.notNull(authentication, "authentication cannot be null (violation of interface contract)");

    String username = null;

    if (authentication.getPrincipal() instanceof UserDetails) {
        username = ((UserDetails) authentication.getPrincipal()).getUsername();
    } else {
        username = (String) authentication.getPrincipal();
    }

    String ip = ((BasicWebAuthenticationDetails) authentication.getDetails()).getRemoteAddress();
    this.username = username;
    this.ip = ip;
}

From source file:org.cloudfoundry.identity.uaa.authentication.manager.LoginAuthenticationManagerTests.java

@Test
public void testHappyDayAutoAddButWithNewUser() {
    manager.setAddNewAccounts(true);/*from  w ww. j a  va2 s. c  o m*/
    UaaUser user = UaaUserTestFactory.getUser("FOO", "foo", "fo@test.org", "Foo", "Bar");
    Mockito.when(userDatabase.retrieveUserByName("foo")).thenThrow(new UsernameNotFoundException("planned"))
            .thenReturn(user);
    Authentication authentication = manager
            .authenticate(UaaAuthenticationTestFactory.getAuthenticationRequest("foo"));
    assertEquals(user.getUsername(), ((UaaPrincipal) authentication.getPrincipal()).getName());
    assertEquals(user.getId(), ((UaaPrincipal) authentication.getPrincipal()).getId());
}

From source file:com.github.dbourdette.otto.service.logs.Logs.java

private void store(String message) {
    BasicDBObject log = new BasicDBObject();

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

    if (authentication == null) {
        log.put("user", "system");
    } else {//from  w ww .ja v  a 2s.  co m
        Object principal = authentication.getPrincipal();

        if (principal instanceof User) {
            log.put("user", ((User) principal).getUsername());
        } else {
            log.put("user", authentication.getName());
        }
    }

    log.put("date", new Date());
    log.put("message", message);

    logs().insert(log);
}

From source file:org.jasig.schedassist.web.register.delegate.DelegateRegistrationHelper.java

/**
 * //from   w  w w .  ja v  a 2s  .co m
 * @return
 */
public String currentDelegateUsername() {
    SecurityContext context = SecurityContextHolder.getContext();
    Authentication authentication = context.getAuthentication();
    DelegateCalendarAccountUserDetailsImpl currentUser = (DelegateCalendarAccountUserDetailsImpl) authentication
            .getPrincipal();
    return currentUser.getUsername();
}

From source file:org.jasig.schedassist.web.register.delegate.DelegateRegistrationHelper.java

/**
 * /*ww w.jav  a  2  s.co  m*/
 * @return true if the current authenticated delegate has ineligible for service
 */
public boolean currentDelegateIsIneligible() {
    SecurityContext context = SecurityContextHolder.getContext();
    Authentication authentication = context.getAuthentication();
    DelegateCalendarAccountUserDetailsImpl currentUser = (DelegateCalendarAccountUserDetailsImpl) authentication
            .getPrincipal();
    boolean result = !currentUser.isEnabled();
    return result;
}

From source file:org.openengsb.opencit.ui.web.AbstractCitPageTest.java

private void mockAuthentication() {
    AuthenticationManager authManager = mock(AuthenticationManager.class);
    final Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    authorities.add(new GrantedAuthorityImpl("ROLE_USER"));
    when(authManager.authenticate(any(Authentication.class))).thenAnswer(new Answer<Authentication>() {
        @Override/*  w  ww  .j av  a2 s .  co  m*/
        public Authentication answer(InvocationOnMock invocation) {
            Authentication auth = (Authentication) invocation.getArguments()[0];
            if (auth.getCredentials().equals("password")) {
                return new UsernamePasswordAuthenticationToken(auth.getPrincipal(), auth.getCredentials(),
                        authorities);
            }
            throw new BadCredentialsException("wrong password");
        }
    });
    appContext.putBean("authenticationManager", authManager);
}