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.companyname.providers.DAOAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    // Determine username and password
    String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED" : authentication.getName();

    String credentials = (authentication.getPrincipal() == null) ? "NONE_PROVIDED"
            : (String) authentication.getCredentials();

    logger.info("platform: Start authenticating user [" + username + "]");

    try {//from w  ww .j av  a  2  s  .  c  o m
        Authentication auth = null;

        // authenticate from cache first to enhance performance
        auth = cache.authenticateFromCache(authentication);

        // perform authentication against our user's database store
        if (auth != null && auth.isAuthenticated()) {
            logger.info("User [" + username + "] is successfully authenticated against the cache");
        } else {
            auth = super.authenticate(authentication);
            cache.add(auth);
            logger.info("User [" + username + "] is successfully authenticated against DB store");
        }

        // build platform authentication object
        Authentication platformAuthentication = PlatAuthentication.getPlatAuthentication(auth);
        ((PlatAuthentication) platformAuthentication).setUserCredentials(credentials);
        return platformAuthentication;

    } catch (AuthenticationException ex1) {
        logger.log(Level.SEVERE, "Unsuccessfully authenticating user [" + username + "] ", ex1);
    }

    return null;
}

From source file:org.ngrinder.security.NGrinderPluginUserDetailsServiceTest.java

@SuppressWarnings({ "unchecked", "serial" })
@Test/*from   www  .  j  a  v  a  2 s.c om*/
public void testSecondAuth() {
    // Given that there exists two plugins.
    Authentication auth = mock(UsernamePasswordAuthenticationToken.class);
    authProvider = spy(authProvider);

    when(auth.getPrincipal()).thenReturn("hello1");
    when(auth.getName()).thenReturn("hello1");
    when(auth.getCredentials()).thenReturn("world");

    when(manager.getEnabledModulesByClass(any(OnLoginRunnable.class.getClass()), any(OnLoginRunnable.class)))
            .thenReturn(new ArrayList<OnLoginRunnable>() {
                {
                    add(defaultLoginPlugin);
                    add(mockLoginPlugin);
                }
            });

    // When user is return by plugin module.
    User user = new User();
    user.setUserName("hello1");
    user.setUserId("hello1");
    user.setEmail("helloworld@gmail.com");
    user.setRole(Role.SUPER_USER);
    user.setAuthProviderClass(mockLoginPlugin.getClass().getName());
    when(mockLoginPlugin.loadUser("hello1")).thenReturn(user);
    when(mockLoginPlugin.validateUser(anyString(), anyString(), anyString(), any(), any())).thenReturn(true);

    // Then, Auth should be succeeded.
    assertThat(authProvider.authenticate(auth), notNullValue());

    // And should be inserted into DB
    // verify(authProvider, times(1)).addNewUserIntoLocal(any(SecuredUser.class));

    reset(authProvider);
    when(mockLoginPlugin.loadUser("hello1")).thenReturn(user);
    // Then, Auth should be succeeded.
    assertThat(authProvider.authenticate(auth), notNullValue());

    // And should not be inserted into DB
    // verify(authProvider, times(0)).addNewUserIntoLocal(any(SecuredUser.class));

}

From source file:br.com.semanticwot.cd.controllers.SwotApplicationController.java

@RequestMapping("/deploy")
public ModelAndView deploy(Authentication authentication) {
    System.out.println("Iniciando o processo " + shell);
    startNodeRed((SystemUser) authentication.getPrincipal());
    return new ModelAndView("redirect:/#three");
}

From source file:com.devicehive.auth.rest.providers.JwtTokenAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    String token = (String) authentication.getPrincipal();
    try {/*www .j ava 2 s  . c  o  m*/
        JwtPayload jwtPayload = jwtClientService.getPayload(token);

        if (jwtPayload == null
                || (jwtPayload.getExpiration() != null
                        && jwtPayload.getExpiration().before(timestampService.getDate()))
                || jwtPayload.getTokenType().equals(TokenType.REFRESH)) {
            throw new BadCredentialsException("Unauthorized");
        }
        logger.debug("Jwt token authentication successful");

        HivePrincipal principal = new HivePrincipal();
        if (jwtPayload.getUserId() != null) {
            UserVO userVO = userService.findById(jwtPayload.getUserId());
            principal.setUser(userVO);
        }

        Set<String> networkIds = jwtPayload.getNetworkIds();
        if (networkIds != null) {
            if (networkIds.contains("*")) {
                principal.setAllNetworksAvailable(true);
            } else {
                principal.setNetworkIds(networkIds.stream().map(Long::valueOf).collect(Collectors.toSet()));
            }
        }

        Set<String> deviceGuids = jwtPayload.getDeviceGuids();
        if (deviceGuids != null) {
            if (deviceGuids.contains("*")) {
                principal.setAllDevicesAvailable(true);
            } else {
                principal.setDeviceGuids(deviceGuids);
            }
        }

        Set<String> availableActions = jwtPayload.getActions();
        if (availableActions != null) {
            if (availableActions.contains("*")) {
                principal.setActions(AvailableActions.getAllHiveActions());
            } else if (availableActions.isEmpty()) {
                principal.setActions(AvailableActions.getClientHiveActions());
            } else {
                principal.setActions(
                        availableActions.stream().map(HiveAction::fromString).collect(Collectors.toSet()));
            }
        }

        return new HiveAuthentication(principal, AuthorityUtils.createAuthorityList(HiveRoles.JWT));

    } catch (Exception e) {
        throw new BadCredentialsException("Unauthorized");
    }
}

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

@Transactional
@RequestMapping(method = RequestMethod.POST, value = "")
public List<UserGadget> saveUserAuthenticatedApplicationsGadgets(Authentication auth,
        @RequestBody List<UserGadget> gadgets) {
    DatabaseUser user = (DatabaseUser) auth.getPrincipal();
    Long userId = user.getUserId();

    for (long i = 0; i < gadgets.size(); i++) {
        UserGadget g = gadgets.get((int) i);
        g.setUserId(userId);/*from  ww  w .j av a2  s.c o m*/
        g.setGadgetId(i);
    }

    userGadgets.deleteByUserId(userId);
    userGadgets.save(gadgets);

    return gadgets;
}

From source file:org.hspconsortium.platform.authorization.launchcontext.LaunchOrchestrationEndpoint.java

@RequestMapping(value = "/Launch", method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public void handleLaunchRequest(HttpServletRequest request, HttpServletResponse response,
        @RequestBody String jsonString) {
    Map<String, Object> jsonMap = new HashMap<String, Object>();
    try {//from w w  w .  ja v  a2s .  com

        HttpSession sessionObj = request.getSession();

        JsonObject json = new JsonParser().parse(jsonString).getAsJsonObject();
        JsonObject jsonParams = json.get("parameters").getAsJsonObject();

        JsonElement jsonLaunchId = jsonParams.get("launch_id");
        String launchId = null;
        String patientId = null;
        if (jsonLaunchId != null) {
            launchId = jsonLaunchId.getAsString();
        }
        JsonElement jsonPatientId = jsonParams.get("patient");
        if (jsonPatientId != null) {
            patientId = jsonPatientId.getAsString();
        }

        LaunchContext launchContext = createLaunchContext(launchId, patientId);
        LaunchContextHolder.addLaunchContext(launchContext);

        SecurityContext securityContext = (SecurityContext) sessionObj.getAttribute("SPRING_SECURITY_CONTEXT");
        if (securityContext != null) {
            Authentication authentication = securityContext.getAuthentication();
            User user = (User) authentication.getPrincipal();
            jsonMap.put("username", user.getUsername());
        } else { //TODO this shouldn't happen when we turn authentication back on
            jsonMap.put("username", "none");
        }

        //TODO: get actual values
        jsonMap.put("created_by", "hspc_platform");
        jsonMap.put("launch_id", launchContext.getLaunchId());
        jsonMap.put("created_at", new Date().toString());
        Map<String, Object> retMap = new Gson().fromJson(json.get("parameters"),
                new TypeToken<HashMap<String, Object>>() {
                }.getType());
        jsonMap.put("parameters", retMap);

    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }

    response.setHeader("Content-Type", "application/json;charset=utf-8");
    try {
        response.getWriter().write(new Gson().toJson(jsonMap));
    } catch (IOException io_ex) {
        throw new RuntimeException(io_ex);
    }
}

From source file:org.jtalks.poulpe.service.transactional.TransactionalGroupService.java

/**
 * {@inheritDoc}// ww  w .j av a  2  s  . c o  m
 */
@Override
public void deleteGroup(Group group) throws NotFoundException {
    Assert.throwIfNull(group, "group");

    for (User user : group.getUsers()) {
        user.getGroups().remove(group);
        userDao.saveOrUpdate((PoulpeUser) user);
    }
    dao.delete(group);

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    User currentUser = (User) auth.getPrincipal();
    UserGroupSid sid = new UserGroupSid(group);
    UserSid sidHeier = new UserSid(currentUser);
    try {
        manager.deleteSid(sid, sidHeier);
    } catch (EmptyResultDataAccessException noSidError) {
        throw new NotFoundException();
    }
}

From source file:ru.ttk.baloo.rest.security.oauth.CustomUserAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    LOG.info("Going to process authentication: " + authentication);
    if (authentication != null && authentication.getPrincipal() != null
            && authentication.getCredentials() != null) {

        LOG.info("authentication principal: " + authentication.getPrincipal());
        LOG.info("authentication credentials: " + authentication.getCredentials());

        /*//from  w  w w  .j  a  v a  2 s. c om
         * authentication.getPrincipal() <=> userName
         * authentication.getCredentials() <=> password
         */
        IRemoteUser remoteUser = remoteServiceFindUser.findUser(authentication.getPrincipal().toString(),
                authentication.getCredentials().toString());
        if (remoteUser != null) {
            List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
            CustomUserPasswordAuthenticationToken auth = new CustomUserPasswordAuthenticationToken(
                    authentication.getPrincipal(), authentication.getCredentials(), grantedAuthorities);
            return auth;
        }
    }
    throw new BadCredentialsException(WRONG_USER_CREDENTIALS);
}

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

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

    CustomerModel userModel = null;
    try {
        userModel = (CustomerModel) getUserService().getUserForUID(StringUtils.lowerCase(username));
    } catch (final UnknownIdentifierException e) {
        LOG.warn("Brute force attack attempt for non existing user name " + username);
    }
    if (userModel == null) {
        throw new BadCredentialsException("Bad credentials");
    }

    if (getBruteForceAttackCounter().isAttack(username)) {
        userModel.setLoginDisabled(true);
        userModel.setStatus(Boolean.TRUE);
        userModel.setAttemptCount(0);
        getModelService().save(userModel);
        bruteForceAttackCounter.resetUserCounter(userModel.getUid());
        throw new LockedException("Locked account");
    } else {
        userModel.setAttemptCount(bruteForceAttackCounter.getUserFailedLogins(username));
        getModelService().save(userModel);
    }

    return super.authenticate(authentication);

}

From source file:com.linuxbox.enkive.permissions.SpringContextPermissionService.java

@Override
public Collection<String> canReadAddresses(String userId) {

    SecurityContext ctx = SecurityContextHolder.getContext();
    Authentication auth = ctx.getAuthentication();

    final UserDetails userDetails = (UserDetails) auth.getPrincipal();

    if (userDetails instanceof EnkiveUserDetails) {
        return ((EnkiveUserDetails) userDetails).getKnownNormalizedEmailAddresses();
    } else {//from w  w  w .j a va2 s . c  o m
        LOGGER.warn("user \"" + userId
                + "\" did not seem to authenticate producing an instance of EnkiveUserDetails");

        // this is assuming that the userId can be treated as an email
        // address; ideally we'll never take this path; perhaps we should
        // throw an exception
        final Collection<String> addresses = new HashSet<String>();
        addresses.add(emailAddressNormalizer.map(userId));

        return addresses;
    }
}