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.osiam.resources.controller.MeController.java

/**
 * This method is used to get information about the user who initialised the authorization process.
 * <p/>//from  ww w . jav a2  s.c o  m
 * The result should be in json format and look like:
 * <p/>
 * {
 * "id": "73821979327912",
 * "name": "Arthur Dent",
 * "first_name": "Arthur",
 * "last_name": "Dent",
 * "link": "https://www.facebook.com/arthur.dent.167",
 * "username": "arthur.dent.167",
 * "gender": "male",
 * "email": "arthur@dent.de",
 * "timezone": 2,
 * "locale": "en_US",
 * "verified": true,
 * "updated_time": "2012-08-20T08:03:30+0000"
 * }
 * <p/>
 * if some information are not available then ... will happen.
 *
 * @return an object to represent the json format.
 */
@RequestMapping(value = "/**", method = { RequestMethod.GET, RequestMethod.POST })
@ResponseBody
public FacebookInformationConstruct getInformation(HttpServletRequest request) {
    String accessToken = getAccessToken(request);

    OAuth2Authentication oAuth = accessTokenValidationService.loadAuthentication(accessToken);
    if (oAuth.isClientOnly()) {
        throw new ConflictException("Can't return an user. This access token belongs to a client.");
    }

    Authentication userAuthentication = oAuth.getUserAuthentication();

    Object principal = userAuthentication.getPrincipal();
    if (principal instanceof User) {
        User user = (User) principal;
        UserEntity userEntity = userDao.getById(user.getId());
        return new FacebookInformationConstruct(userEntity);
    } else {
        throw new IllegalArgumentException("User was not authenticated with OSIAM.");
    }
}

From source file:com.bisone.saiku.security.replace.SessionService.java

public Map<String, Object> getSession() throws Exception {
    if (SecurityContextHolder.getContext() != null
            && SecurityContextHolder.getContext().getAuthentication() != null) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        Object p = auth.getPrincipal();
        if (sessionHolder.containsKey(p)) {
            Map<String, Object> r = new HashMap<String, Object>();
            r.putAll(sessionHolder.get(p));
            r.remove("password");
            return r;
        }//from  w ww. j  a va 2 s .  c o m

    }
    return new HashMap<String, Object>();
}

From source file:com.bisone.saiku.security.replace.SessionService.java

public Map<String, Object> getAllSessionObjects() {
    if (SecurityContextHolder.getContext() != null
            && SecurityContextHolder.getContext().getAuthentication() != null) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        Object p = auth.getPrincipal();
        //TODO ??
        createSession(auth, null, null);
        if (sessionHolder.containsKey(p)) {
            Map<String, Object> r = new HashMap<String, Object>();
            r.putAll(sessionHolder.get(p));
            return r;
        }// ww w . ja  va  2 s.  c o  m

    }
    return new HashMap<String, Object>();
}

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

@Test
public void successfulAuthenticationReturnsTokenAndPublishesEvent() throws Exception {
    when(db.retrieveUserByName("auser")).thenReturn(user);
    Authentication result = mgr.authenticate(createAuthRequest("auser", "password"));

    assertNotNull(result);/*  ww w  .  ja  v  a2 s .c o  m*/
    assertEquals("auser", result.getName());
    assertEquals("auser", ((UaaPrincipal) result.getPrincipal()).getName());

    verify(publisher).publishEvent(isA(UserAuthenticationSuccessEvent.class));
}

From source file:org.jtalks.common.service.nontransactional.SecurityServiceImplTest.java

@Test
public void testGetCurrentUser() throws Exception {
    User user = getUser();//from  w  w  w.  ja v  a  2  s  . c om
    Authentication auth = mock(Authentication.class);
    when(auth.getPrincipal()).thenReturn(user);
    when(securityContext.getAuthentication()).thenReturn(auth);
    when(userDao.getByUsername(USERNAME)).thenReturn(user);

    User result = securityService.getCurrentUser();

    assertEquals(result.getUsername(), USERNAME, "Username not equals");
    assertEquals(result.getAuthorities().iterator().next().getAuthority(), "ROLE_USER");
    assertTrue(result.isAccountNonExpired());
    assertTrue(result.isAccountNonLocked());
    assertFalse(result.isEnabled());
    assertTrue(result.isCredentialsNonExpired());
    verify(userDao).getByUsername(USERNAME);
    verify(auth).getPrincipal();
    verify(securityContext).getAuthentication();
}

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

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

    if (getBruteForceAttackCounter().isAttack(username)) {
        try {
            final UserModel userModel = getUserService().getUserForUID(StringUtils.lowerCase(username));

            if (userModel instanceof CustomerModel) {
                final CustomerModel customerModel = (CustomerModel) userModel;

                customerModel.setLoginDisabled(true);
                customerModel.setStatus(Boolean.TRUE);
                customerModel.setAttemptCount(Integer.valueOf(0));

                getModelService().save(customerModel);
            } else {
                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"));
        }
    }

    return doAuth(authentication, username);
}

From source file:org.ng200.openolympus.SpringSecurityAuditorAware.java

@Override
public User getCurrentAuditor() {

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

    if (authentication == null || !authentication.isAuthenticated()) {
        return null;
    }//ww w  .j a va  2s.c o m

    return this.userService.getUserByUsername(((Principal) authentication.getPrincipal()).getName());
}

From source file:com.rcn.controller.ResourceController.java

@RequestMapping(value = "/license-key", method = RequestMethod.POST)
public String licenseKeyPost(@RequestParam("name") String name, @RequestParam("validFor") Integer validFor,
        @RequestParam("keyExpires") Integer keyExpires,
        @RequestParam("activationsNumber") Integer activationsNumber,
        @RequestParam("customKey") String customKey, @RequestParam("key") Long key,
        @RequestParam("val") String val,
        @RequestParam(name = "resourceGroup", required = false) boolean resourceGroup,
        @RequestParam(name = "customNumber", required = false) boolean customNumber, Authentication principal,
        Model model) {/* ww w  .j  a  v a 2  s .  c  o  m*/

    RcnUserDetail user = (RcnUserDetail) principal.getPrincipal();
    Long targetUserId = user.getTargetUser().getId();
    try {
        String lk = customNumber
                ? IntStream.range(0, 1).mapToObj(a -> customKey.toUpperCase()).filter(a -> a.length() == 16)
                        .filter(a -> resourceRepository.containsKey(a) == null).findFirst()
                        .orElseThrow(() -> new IllegalArgumentException(l("invalid.custom.number")))
                : IntStream.range(0, 10).mapToObj(a -> generateLicenseKey())
                        .filter(a -> resourceRepository.containsKey(a) == null).findFirst()
                        .orElseThrow(() -> new IllegalArgumentException(l("cant.generate.license.key")));

        Long id = resourceRepository.createLicenseKey(targetUserId, name, lk, validFor, keyExpires,
                activationsNumber);
        if (resourceGroup) {
            resourceRepository.licenseKeyToResourceGroup(targetUserId, id, key);
        }
    } catch (IllegalArgumentException e) {
        model.addAttribute("error", e.getMessage());
    }

    return "license-key";
}

From source file:eu.openanalytics.rsb.security.JmxSecurityAuthenticator.java

@Override
public Subject authenticate(final Object credentials) {
    try {//w w  w. ja v a 2  s. c  o  m
        final String[] info = (String[]) credentials;

        final Authentication authentication = authenticationManager
                .authenticate(new UsernamePasswordAuthenticationToken(info[0], info[1]));

        final User authenticatedUser = (User) authentication.getPrincipal();

        if ((isRsbAdminPrincipal(authenticatedUser)) || (isRsbAdminRole(authenticatedUser))) {
            final Subject s = new Subject();
            s.getPrincipals().add(new JMXPrincipal(authentication.getName()));
            return s;
        } else {
            throw new SecurityException("Authenticated user " + authenticatedUser + " is not an RSB admin");
        }
    } catch (final Exception e) {
        LOGGER.error("Error when trying to authenticate JMX credentials of type: " + credentials.getClass(), e);

        throw new SecurityException(e);
    }
}

From source file:nz.net.orcon.kanban.security.SecurityToolImpl.java

@Override
public String getCurrentUser() {
    SecurityContext context = SecurityContextHolder.getContext();
    Authentication authentication = context.getAuthentication();
    Object principal = SYSTEM;/*from  ww w  .j a v  a 2 s  .c  o  m*/
    if (authentication != null) {
        principal = authentication.getPrincipal();
    }
    return (String) principal;
}