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:alpha.portal.webapp.listener.UserCounterListener.java

/**
 * When user's logout, remove their name from the hashMap.
 * /*from   ww w . ja  v a  2s.  co  m*/
 * @param event
 *            the session binding event
 * @see javax.servlet.http.HttpSessionAttributeListener#attributeRemoved(javax.servlet.http.HttpSessionBindingEvent)
 */
public void attributeRemoved(final HttpSessionBindingEvent event) {
    if (event.getName().equals(UserCounterListener.EVENT_KEY) && !this.isAnonymous()) {
        final SecurityContext securityContext = (SecurityContext) event.getValue();
        final Authentication auth = securityContext.getAuthentication();
        if ((auth != null) && (auth.getPrincipal() instanceof User)) {
            final User user = (User) auth.getPrincipal();
            this.removeUsername(user);
        }
    }
}

From source file:com.razorfish.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 a v a 2 s .  c  o m*/
    String usernameResult = username;

    UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;

    if (!usernameResult.isEmpty()) {
        final List<CustomerModel> result = getCustomerDao().findCustomerByMobileNumber(usernameResult);
        if (!result.isEmpty()) {
            usernameResult = result.iterator().next().getOriginalUid();
            token = new UsernamePasswordAuthenticationToken(usernameResult,
                    (String) authentication.getCredentials());
            token.setDetails(authentication.getDetails());
        }
    }

    if (getBruteForceAttackCounter().isAttack(usernameResult)) {
        try {
            final UserModel userModel = getUserService().getUserForUID(StringUtils.lowerCase(usernameResult));
            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 " + usernameResult);
        } finally {
            throw new BadCredentialsException(
                    messages.getMessage("CoreAuthenticationProvider.badCredentials", "Bad credentials"));
        }
    }

    checkCartForUser(usernameResult);
    return super.authenticate(token);
}

From source file:com.thinkbiganalytics.auth.jwt.JwtRememberMeServices.java

/**
 * Sets a JWT cookie when the user has successfully logged in.
 *
 * @param request        the HTTP request
 * @param response       the HTTP response
 * @param authentication the user/*from   w  w  w  . ja va2s. c o m*/
 */
@Override
protected void onLoginSuccess(@Nonnull final HttpServletRequest request,
        @Nonnull final HttpServletResponse response, @Nonnull final Authentication authentication) {
    final Stream<String> user = Stream.of(authentication.getPrincipal().toString());
    final Stream<String> groups = authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority);
    final String[] tokens = Stream.concat(user, groups).toArray(String[]::new);

    setCookie(tokens, getTokenValiditySeconds(), request, response);
}

From source file:com.netflix.spinnaker.fiat.shared.FiatPermissionEvaluator.java

private String getUsername(Authentication authentication) {
    String username = "anonymous";
    if (authentication.isAuthenticated() && authentication.getPrincipal() != null) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof User) {
            username = ((User) principal).getUsername();
        } else if (StringUtils.isNotEmpty(principal.toString())) {
            username = principal.toString();
        }//from   ww  w .j a  v a  2s. c om
    }
    return username;
}

From source file:org.apigw.authserver.web.controller.MonitoringController.java

@RequestMapping(method = RequestMethod.GET, params = { "clientId", "state" })
public ModelAndView list(@RequestParam("clientId") String clientId, @RequestParam("state") String state,
        Authentication authentication) {

    Application application = appManagement.getApplicationByClientId(clientId);
    UserDetails user = (UserDetails) authentication.getPrincipal();

    if (application == null) {
        throw new IllegalArgumentException("No application found with client id " + clientId);
    }/* ww  w  .  jav  a  2  s. c o  m*/

    if (!user.getUsername().equals(application.getDeveloper().getResidentIdentificationNumber())) {
        throw new IllegalArgumentException("Application developer is not the same as the logged in user");
    }

    if (!state.toUpperCase().equals("SERVER_FAILURE") && !state.toUpperCase().equals("CLIENT_FAILURE")
            && !state.toUpperCase().equals("SUCCESS")) {
        throw new IllegalArgumentException("Provided state not recogonized: " + state);
    }

    TreeMap<String, Object> model = new TreeMap<String, Object>();

    RestTemplate template = new RestTemplate();

    long from = System.currentTimeMillis() - 24 * 3600 * 1000;

    Map<String, Object> params = new HashMap<String, Object>();
    params.put("from", from);
    params.put("client", clientId);
    params.put("state", state);

    // Load list of last 100 failed requests 
    List<Map<String, Object>> requests = template.getForObject(
            location + "/api/timeline/resourceRequest?from={from}&state={state}&client={client}", List.class,
            params);

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    for (Map<String, Object> request : requests) {
        long timestamp = (Long) request.get("timestamp");
        Date date = new Date(timestamp);
        request.put("datetime", format.format(date));
    }

    model.put("requests", requests);
    model.put("client", clientId);
    model.put("state", state);

    return new ModelAndView("monitoring", model);
}

From source file:csns.security.LogoutRedirectHandler.java

@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws IOException, ServletException {
    // authentication could be null if the session already expired or the
    // user clicked the logout link twice.
    if (authentication != null) {
        User user = (User) authentication.getPrincipal();
        logger.info(user.getUsername() + " signed out.");
    }//from   ww  w  . j  av a  2  s. c om

    SimpleUrlLogoutSuccessHandler logoutSuccessHandler = new SimpleUrlLogoutSuccessHandler();
    logoutSuccessHandler.setDefaultTargetUrl(defaultUrls.anonymousHomeUrl(request));
    logoutSuccessHandler.onLogoutSuccess(request, response, authentication);
}

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

@Test
public void testHappyDayNoAutoAdd() {
    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
public void testHappyDayWithAuthorities() {
    UaaUser user = UaaUserTestFactory.getAdminUser("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.getAuthorities(), authentication.getAuthorities());
}

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

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) {
    Authentication auth = getAuthentication(request, response);
    String timezone = request.getParameter("user_timezone");
    String language = request.getParameter("native_language");
    SecuredUser securedUser = (SecuredUser) auth.getPrincipal();
    User user = securedUser.getUser();/*from  w  w w .  j a va  2  s. c  o m*/
    User existingUser = userRepository.findOneByUserId(user.getUserId());
    if (existingUser != null) {
        user = existingUser;
    }
    user.setTimeZone(timezone);
    user.setUserLanguage(language);
    securedUser.setUser(userRepository.saveAndFlush(user));
    return auth;
}

From source file:eu.supersede.gr.rest.JudgeActRest.java

@RequestMapping(method = RequestMethod.PUT, value = "/{judgeActId}/vote/{vote}")
public void setjudgeActVote(Authentication authentication, @PathVariable Long judgeActId,
        @PathVariable Long vote) {

    DatabaseUser currentUser = (DatabaseUser) authentication.getPrincipal();
    User judge = users.findOne(currentUser.getUserId());

    HAHPJudgeAct judgeAct = judgeActs.findOne(judgeActId);

    judgeAct.setJudge(judge);/*from ww w.j  av  a2 s .c o  m*/
    judgeAct.setVoted(true);
    judgeAct.setVotedTime(new Date());
    judgeActs.save(judgeAct);

    HAHPRequirementsMatrixData requirementsMatrixData = judgeAct.getRequirementsMatrixData();
    requirementsMatrixData.setValue(vote);
    requirementsMatricesData.save(requirementsMatrixData);

    Long criteriaId = requirementsMatrixData.getCriteria().getCriteriaId();

    // add points for judge move
    pointsLogic.addPoint(judge, -2l, criteriaId);

    // set played true to all player_moves connected with the requirementsMatrixDataId      
    List<HAHPPlayerMove> playerMovesList = playerMoves.findByRequirementsMatrixData(requirementsMatrixData);
    for (int i = 0; i < playerMovesList.size(); i++) {
        playerMovesList.get(i).setPlayed(true);
        playerMoves.save(playerMovesList.get(i));
    }
}