public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { try { OAuth2AccessToken accessToken = restTemplate.getAccessToken(); FacebookUser facebookUser = userIdentity.findOrCreateFrom(accessToken); repository.save(facebookUser); Authentication authentication = new UsernamePasswordAuthenticationToken( facebookUser, null, Arrays.asList(new SimpleGrantedAuthority("ROLE_USER"))); publish(new AuthenticationSuccessEvent(authentication)); return authentication; } catch (OAuth2Exception e) { BadCredentialsException error = new BadCredentialsException( "Cannot retrieve the access token", e); publish(new OAuth2AuthenticationFailureEvent(error)); throw error; } }
@Override public Authentication attemptAuthentication( HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { try { OAuth2AccessToken accessToken = restTemplate.getAccessToken(); Claims claims = Claims.createFrom(jsonMapper, accessToken); GoogleUser googleUser = userIdentity.findOrCreateFrom(claims); repository.save(googleUser); Authentication authentication = new UsernamePasswordAuthenticationToken( googleUser, null, googleUser.getAuthorities()); publish(new AuthenticationSuccessEvent(authentication)); return authentication; } catch (OAuth2Exception e) { BadCredentialsException error = new BadCredentialsException( "Cannot retrieve the access token", e); publish(new OAuth2AuthenticationFailureEvent(error)); throw error; } }
@Override public void onApplicationEvent(AbstractAuthenticationEvent event) { if (event instanceof AuthenticationSuccessEvent) { log.debug("Authentication OK: {}", event.getAuthentication().getName()); // Activity log Object details = event.getAuthentication().getDetails(); String params = null; if (details instanceof WebAuthenticationDetails) { WebAuthenticationDetails wad = (WebAuthenticationDetails) details; params = wad.getRemoteAddress(); } else if (GenericHolder.get() != null) { params = (String) GenericHolder.get(); } UserActivity.log(event.getAuthentication().getName(), "LOGIN", null, null, params); } else if (event instanceof AuthenticationFailureBadCredentialsEvent) { log.info("Authentication ERROR: {}", event.getAuthentication().getName()); } }
@Override public void onApplicationEvent( final AuthenticationSuccessEvent authenticationSuccessEvent ) { final String username = authenticationSuccessEvent.getAuthentication().getName(); UserCredentials credentials = userService.getUserCredentialsByUsername( username ); boolean readOnly = config.isReadOnlyMode(); if ( Objects.nonNull( credentials ) && !readOnly ) { credentials.updateLastLogin(); userService.updateUserCredentials( credentials ); } if ( credentials != null ) { securityService.registerSuccessfulLogin( username ); } }
@Override public void onApplicationEvent(AbstractAuthenticationEvent appEvent) { String currentUserName = extractUserName(appEvent); if (currentUserName == null || isLockMechanismDisabled()) { return; } if (appEvent instanceof AuthenticationSuccessEvent && accessCounter.containsKey(currentUserName) && accessCounter.get(currentUserName) < maxLoginFailures) { accessCounter.remove(currentUserName); lastFailedLogin.remove(currentUserName); } if (appEvent instanceof AuthenticationFailureBadCredentialsEvent) { if (accessCounter.containsKey(currentUserName)) { accessCounter.put(currentUserName, accessCounter.get(currentUserName) + 1); } else { accessCounter.put(currentUserName, 1); } lastFailedLogin.put(currentUserName, new Date()); } }
/** * Обрабатывает событие успешной аутентификации * * @param event событие */ private void handleAuthenticationSuccessEvent(AuthenticationSuccessEvent event) { if (LOG.isInfoEnabled()) { Authentication authentication = event.getAuthentication(); String commonMessage = String.format( SUCCESS_TEMPLATE, DateUtil.formatDateTime(new Date(event.getTimestamp())), extractPrincipal(authentication), StringUtils.collectionToCommaDelimitedString(authentication.getAuthorities()) ); String detailsMessage = (authentication.getDetails() != null) ? OBJECT_HEX_PATTERN.matcher(authentication.getDetails().toString()).replaceAll("") : null; String resultMessage = StringUtils.hasText(detailsMessage) ? String.format(DETAILS_TEMPLATE, commonMessage, detailsMessage) : commonMessage; LOG.info(resultMessage); } }
@Override public void onApplicationEvent(AuthenticationSuccessEvent event) { try { User user = userService.findByLogin(((UserDetails) event.getAuthentication().getPrincipal()).getUsername()); user.setLastConnection(new Date()); userService.update(user); } catch (ServiceException e) { e.printStackTrace(); } }
@Override public Authentication attemptAuthentication( HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { try { OAuth2AccessToken accessToken = restTemplate.getAccessToken(); Claims claims = Claims.createFrom(jsonMapper, accessToken); GoogleUser googleUser = userIdentity.findOrCreateFrom(claims); String userName = getUserNameFromUserInfo(accessToken, googleUser.getOpenIDAuthentication().getSubject()); googleUser.getOpenIDAuthentication().setName(userName); repository.save(googleUser); Authentication authentication = new UsernamePasswordAuthenticationToken( googleUser, null, googleUser.getAuthorities()); publish(new AuthenticationSuccessEvent(authentication)); return authentication; } catch (OAuth2Exception e) { BadCredentialsException error = new BadCredentialsException( "Cannot retrieve the access token", e); publish(new OAuth2AuthenticationFailureEvent(error)); throw error; } }
/** * record successful login attempt * * @param e authentication success event */ @Override public void onApplicationEvent(final AuthenticationSuccessEvent e) { final WebAuthenticationDetails auth = (WebAuthenticationDetails) e.getAuthentication().getDetails(); final String email = e.getAuthentication().getPrincipal().toString(); loginAttemptService.loginSucceeded(email, auth.getRemoteAddress()); }
private void storeLogMessage(final AbstractAuthenticationEvent event) { try { if (event instanceof InteractiveAuthenticationSuccessEvent) { accountAuditService.auditLoginSuccessEvent(InteractiveAuthenticationSuccessEvent.class.cast(event)); } else if (event instanceof AuthenticationSuccessEvent) { accountAuditService.auditLoginSuccessEvent(AuthenticationSuccessEvent.class.cast(event)); } else if (event instanceof AbstractAuthenticationFailureEvent) { accountAuditService.auditLoginFailureEvent(AbstractAuthenticationFailureEvent.class.cast(event)); } } catch (Exception ex) { LOG.error("Failed to audit authentication event in database", ex); } }
private void logToAuditService(AbstractAuthenticationEvent event) { if (event instanceof AuthenticationSuccessEvent) { final Authentication authentication = event.getAuthentication(); final ImmutableMap.Builder<String, Object> extra = auditService.extra("remoteAddress", getRemoteAddress(authentication)); addGrantedAuthorities(authentication, extra); addSource(event, extra); auditService.log("loginSuccess", authentication.getName(), extra.build()); } }
@Transactional public void auditLoginSuccessEvent(AuthenticationSuccessEvent successEvent) { final AccountActivityMessage message = createLogMessage( null, successEvent.getAuthentication(), AccountActivityMessage.ActivityType.LOGIN_SUCCESS); logMessageRepository.save(message); }
@Test public void testAuditLogin_success() { final AuthenticationSuccessEvent event = new AuthenticationSuccessEvent(authMock); auditService.auditLoginSuccessEvent(event); verify(accountActivityMessageRepository, times(1)) .save(argThat(matches(true, username, null))); verifyNoMoreInteractions(accountActivityMessageRepository); }
@Override public void onApplicationEvent(AuthenticationSuccessEvent event) { final User principal = (User) event.getAuthentication().getPrincipal(); Map<String, String> details = (Map<String, String>) event.getAuthentication().getDetails(); try { io.gravitee.am.model.User user = userService.loadUserByUsernameAndDomain(domain.getId(), principal.getUsername()); UpdateUser updateUser = new UpdateUser(); if (details != null) { updateUser.setSource(details.get(RepositoryProviderUtils.SOURCE)); updateUser.setClient(details.get(OAuth2Utils.CLIENT_ID)); } updateUser.setLoggedAt(new Date()); updateUser.setLoginsCount(user.getLoginsCount() + 1); updateUser.setAdditionalInformation(principal.getAdditionalInformation()); userService.update(domain.getId(), user.getId(), updateUser); } catch (UserNotFoundException unfe) { final NewUser newUser = new NewUser(); newUser.setUsername(principal.getUsername()); if (details != null) { newUser.setSource(details.get(RepositoryProviderUtils.SOURCE)); newUser.setClient(details.get(OAuth2Utils.CLIENT_ID)); } newUser.setLoggedAt(new Date()); newUser.setLoginsCount(1l); newUser.setAdditionalInformation(principal.getAdditionalInformation()); userService.create(domain.getId(), newUser); } }
@Override public void handle(Object event) { AuthenticationSuccessEvent loginSuccessEvent = (AuthenticationSuccessEvent) event; Object name = loginSuccessEvent.getAuthentication().getPrincipal(); if (name != null) { Users user = (Users) name; user.setFailedLoginAttemptsToZero(); usersRepository.updateUser(user); } }
@Test public void testHandle() { AuthenticationSuccessEvent loginSuccessEvent=mock(AuthenticationSuccessEvent.class); Authentication authentication=mock(Authentication.class); Users user=mock(Users.class); when(loginSuccessEvent.getAuthentication()).thenReturn(authentication); when(authentication.getPrincipal()).thenReturn(user); loginSuccessEventListener.handle(loginSuccessEvent); verify(user).setFailedLoginAttemptsToZero(); verify(usersRepository).updateUser(user); }
@Override public void onApplicationEvent(final AuthenticationSuccessEvent e) { final WebAuthenticationDetails auth = (WebAuthenticationDetails) e.getAuthentication().getDetails(); if (auth != null) { loginAttemptService.loginSucceeded(auth.getRemoteAddress()); } }
@Override public void onApplicationEvent(AbstractAuthenticationEvent event) { if (event instanceof AbstractAuthenticationFailureEvent) { onAuthenticationFailureEvent((AbstractAuthenticationFailureEvent) event); } else if (this.webListener != null && this.webListener.accepts(event)) { this.webListener.process(this, event); } else if (event instanceof AuthenticationSuccessEvent) { onAuthenticationSuccessEvent((AuthenticationSuccessEvent) event); } }
private void onAuthenticationSuccessEvent(AuthenticationSuccessEvent event) { Map<String, Object> data = new HashMap<String, Object>(); if (event.getAuthentication().getDetails() != null) { data.put("details", event.getAuthentication().getDetails()); } publish(new AuditEvent(event.getAuthentication().getName(), "AUTHENTICATION_SUCCESS", data)); }
@Override public void onApplicationEvent(AbstractAuthenticationEvent event) { Authentication source = event.getAuthentication(); if (event instanceof AbstractAuthenticationFailureEvent) { Exception e = ((AbstractAuthenticationFailureEvent) event).getException(); log.info(String.format("Authentication failure [user: %s] [error: %s]", source.getName(), e.getMessage())); } else if (event instanceof AuthenticationSuccessEvent) { String userName = source.getName(); log.info(String.format("User logged in [user: %s]", userName)); eventService.post(EventType.Login.toString(), userName, null); } }
@Override public void onApplicationEvent(final AuthenticationSuccessEvent e) { // final WebAuthenticationDetails auth = (WebAuthenticationDetails) e.getAuthentication().getDetails(); // if (auth != null) { // loginAttemptService.loginSucceeded(auth.getRemoteAddress()); // } final String xfHeader = request.getHeader("X-Forwarded-For"); if (xfHeader == null) { loginAttemptService.loginSucceeded(request.getRemoteAddr()); } else { loginAttemptService.loginSucceeded(xfHeader.split(",")[0]); } }
@Override public void onApplicationEvent(AuthenticationSuccessEvent event) { final UserDetails details = (UserDetails) event.getAuthentication().getPrincipal(); try { userService.findByName(details.getUsername(), false); } catch (UserNotFoundException unfe) { final NewExternalUserEntity newUser = new NewExternalUserEntity(); newUser.setUsername(details.getUsername()); newUser.setSource(details.getSource()); newUser.setSourceId(details.getSourceId()); newUser.setFirstname(details.getFirstname()); newUser.setLastname(details.getLastname()); newUser.setEmail(details.getEmail()); boolean addDefaultRole = false; if (event.getAuthentication().getAuthorities() == null || event.getAuthentication().getAuthorities().isEmpty()) { addDefaultRole = true; } userService.create(newUser, addDefaultRole); if (!addDefaultRole) { addRole(RoleScope.MANAGEMENT, newUser.getUsername(), event.getAuthentication().getAuthorities()); addRole(RoleScope.PORTAL, newUser.getUsername(), event.getAuthentication().getAuthorities()); } } userService.connect(details.getUsername()); }
@Override public void onApplicationEvent(ApplicationEvent aEvent) { if (aEvent instanceof AuthenticationSuccessEvent) { AuthenticationSuccessEvent event = (AuthenticationSuccessEvent) aEvent; User user = userRepository.get(event.getAuthentication().getName()); user.setLastLogin(new Date(event.getTimestamp())); userRepository.update(user); } }
@Override public void onApplicationEvent(final AuthenticationSuccessEvent authenticationSuccessEvent) { final Object principal = authenticationSuccessEvent.getAuthentication().getPrincipal(); if (principal instanceof CommunityPrincipal) { final CommunityPrincipal communityPrincipal = (CommunityPrincipal) principal; final String principalUsername = communityPrincipal.getUsername(); userEntityService.getOrCreate(principalUsername); } }
@Override @Transactional public void onApplicationEvent(final AuthenticationSuccessEvent event) { final Account account = ((User) event.getAuthentication().getPrincipal()).getAccount(); account.setFailedAuthCounter(0); account.setLastSuccessAuth(new Date()); account.setLastSuccessAuthIp(currentRequestRemoteAddr()); repository.save(account); }
@Override public void onApplicationEvent(AbstractAuthenticationEvent event) { // Authentication success if (event instanceof AuthenticationSuccessEvent) { handleAuthenticationSuccessEvent((AuthenticationSuccessEvent) event); } // Authentication failure if (event instanceof AbstractAuthenticationFailureEvent) { handleAuthenticationFailureEvent((AbstractAuthenticationFailureEvent) event); } // Authentication clear if (event instanceof AuthenticationCleanedEvent) { handleAuthenticationCleanedEvent((AuthenticationCleanedEvent) event); } }
@Override public void onApplicationEvent(AbstractAuthenticationEvent event) { Authentication authentication = event.getAuthentication(); if (event instanceof AuthenticationSuccessEvent) { ResourceOwnerPasswordResourceDetails resource = getResourceOwnerPasswordResourceDetails(); resource.setScope(Arrays.asList("words")); resource.setUsername(authentication.getName()); resource.setPassword(authentication.getCredentials().toString()); try { OAuth2AccessToken accessToken = accessTokenProvider.obtainAccessToken(resource, new DefaultAccessTokenRequest()); log.debug("Access token request succeeded for user: '{}', new token is '{}'" , resource.getUsername() , accessToken.getValue()); if (authentication instanceof AbstractAuthenticationToken && authentication.getDetails() instanceof CustomAuthenticationDetails) { ((CustomAuthenticationDetails) ((AbstractAuthenticationToken) authentication).getDetails()) .setBearer(accessToken.getValue()); log.debug("Access token was added to authentication as details"); } else if (log.isDebugEnabled()) { log.debug("Access token could not be added to authentication as details"); } } catch (Exception e) { log.error("Access token request failed for user: '" + resource.getUsername() + "'", e); } } if (authentication instanceof CredentialsContainer) { // Authentication is complete. Remove credentials and other secret data from authentication ((CredentialsContainer)authentication).eraseCredentials(); } }
@Override public void onApplicationEvent(ApplicationEvent event) { if(event instanceof AuthenticationSuccessEvent) { AuthenticationSuccessEvent successEvent = (AuthenticationSuccessEvent) event; final Authentication authentication = successEvent.getAuthentication(); final OpenAMUserdetails details = (OpenAMUserdetails) authentication.getDetails(); final String nickname = details.getUsername(); Query query = new Query(); query.addCriteria(Criteria.where("nickName").is(nickname)); final String surname = details.getAttributeValue("sn"); final String givenname = details.getAttributeValue("givenname"); final String email = details.getAttributeValue("mail"); Update update = new Update(); update.set("email", email); update.set("givenName", givenname); update.set("surName", surname); update.set("lastLogin", new Date()); try { update.set("gravatar", User.md5Hex(email)); } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { LOGGER.error("Failed while calculating gravatar hash!"); } final User user = mongoTemplate.findAndModify(query, update, FindAndModifyOptions.options().upsert(true).returnNew(true), User.class); if (user != null) { LOGGER.debug("LoginEvent for user: " + user.toString()); } else { LOGGER.debug("Upsert didn't return new user!"); } } }
@Override public void handle(Object event) { AuthenticationSuccessEvent loginSuccessEvent=(AuthenticationSuccessEvent)event; Object name = loginSuccessEvent.getAuthentication() .getPrincipal(); if(name!=null){ Users user=(Users)name; user.setFailedLoginAttemptsToZero(); usersRepository.updateUser(user); } }
public void testAuthenticationSuccessEventWithEverything() throws Exception { String userName = "bar"; String ip = "1.2.3.4"; String sessionId = "it tastes just like our regular coffee"; HttpServletRequest request = createMock(HttpServletRequest.class); HttpSession session = createMock(HttpSession.class); expect(request.getRemoteAddr()).andReturn(ip); expect(request.getSession(false)).andReturn(session); expect(session.getId()).andReturn(sessionId); replay(request, session); WebAuthenticationDetails details = new WebAuthenticationDetails(request); verify(request, session); org.springframework.security.core.Authentication authentication = new TestingDetailsAuthenticationToken(userName, "cheesiness", new GrantedAuthority[0], details); AuthenticationSuccessEvent authEvent = new AuthenticationSuccessEvent(authentication); SecurityAuthenticationEventOnmsEventBuilder builder = new SecurityAuthenticationEventOnmsEventBuilder(); builder.setEventProxy(m_eventProxy); builder.afterPropertiesSet(); EventBuilder eventBuilder = new EventBuilder(SecurityAuthenticationEventOnmsEventBuilder.SUCCESS_UEI, "OpenNMS.WebUI"); eventBuilder.addParam("user", userName); eventBuilder.addParam("ip", ip); m_eventProxy.send(EventEquals.eqEvent(eventBuilder.getEvent())); m_mocks.replayAll(); builder.onApplicationEvent(authEvent); m_mocks.verifyAll(); }
@Override @Transactional public void onApplicationEvent(AuthenticationSuccessEvent ev) { String username = ev.getAuthentication().getName(); TypedQuery<User> query = User.findUsersByEmailAddress(username, null, null); User targetUser = (User) query.getSingleResult(); if (targetUser != null) { // only for existing users targetUser.reportLoginOK(); targetUser.persist(); } }
@EventListener public void onLoginSuccess(AuthenticationSuccessEvent event) { LOGGER.info("User {} login successfully", event.getAuthentication().getPrincipal()); }
@Override public boolean canHandle(Object event) { return event instanceof AuthenticationSuccessEvent; }
@Test public void testCanHandle_when_event_unmatch() { AuthenticationSuccessEvent event=mock(AuthenticationSuccessEvent.class); assertEquals(loginFailureEventListener.canHandle(event),false); }