org.springframework.security.authentication.event.AuthenticationSuccessEvent Java Examples

The following examples show how to use org.springframework.security.authentication.event.AuthenticationSuccessEvent. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: InternalAuthenticationProvider.java    From osiam with MIT License 7 votes vote down vote up
@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());
    }
}
 
Example #2
Source File: BaeldungPasswordEncoderSetup.java    From tutorials with MIT License 6 votes vote down vote up
@Bean
public ApplicationListener<AuthenticationSuccessEvent> authenticationSuccessListener(final PasswordEncoder encoder) {

    return (AuthenticationSuccessEvent event) -> {
        final Authentication auth = event.getAuthentication();

        if (auth instanceof UsernamePasswordAuthenticationToken && auth.getCredentials() != null) {

            final CharSequence clearTextPass = (CharSequence) auth.getCredentials(); // 1
            final String newPasswordHash = encoder.encode(clearTextPass); // 2

            LOG.info("New password hash {} for user {}", newPasswordHash, auth.getName());

            ((UsernamePasswordAuthenticationToken) auth).eraseCredentials(); // 3
        }
    };
}
 
Example #3
Source File: SpringEventListener.java    From ranger with Apache License 2.0 6 votes vote down vote up
@Override
   public void onApplicationEvent(AbstractAuthenticationEvent event) {
try {
    if (event instanceof AuthenticationSuccessEvent) {
	process((AuthenticationSuccessEvent) event);
    } else if (event instanceof AuthenticationFailureBadCredentialsEvent) {
	process((AuthenticationFailureBadCredentialsEvent) event);
    } else if (event instanceof AuthenticationFailureDisabledEvent) {
	process((AuthenticationFailureDisabledEvent) event);
    }
    // igonre all other events

} catch (Exception e) {
    logger.error("Exception in Spring Event Listener.", e);
}
   }
 
Example #4
Source File: FacebookLoginFilter.java    From OAuth-2.0-Cookbook with MIT License 6 votes vote down vote up
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;
    }
}
 
Example #5
Source File: OpenIdConnectFilter.java    From OAuth-2.0-Cookbook with MIT License 6 votes vote down vote up
@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;
    }
}
 
Example #6
Source File: LoggerListener.java    From document-management-system with GNU General Public License v2.0 5 votes vote down vote up
@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();
		}

		// AUTOMATION - POST
		Map<String, Object> env = new HashMap<>();
		env.put(AutomationUtils.USER, event.getAuthentication().getName());
		try {
			AutomationManager.getInstance().fireEvent(AutomationRule.EVENT_USER_LOGIN, AutomationRule.AT_POST, env);
		} catch (Exception e) {
			log.info("Automation ERROR: {}", e.getCause());
		}

		UserActivity.log(event.getAuthentication().getName(), "LOGIN", null, null, params);
	} else if (event instanceof AuthenticationFailureBadCredentialsEvent) {
		log.info("Authentication ERROR: {}", event.getAuthentication().getName());
	}
}
 
Example #7
Source File: SpringEventListener.java    From ranger with Apache License 2.0 5 votes vote down vote up
protected void process(AuthenticationSuccessEvent authSuccessEvent) {
Authentication auth = authSuccessEvent.getAuthentication();
WebAuthenticationDetails details = (WebAuthenticationDetails) auth
	.getDetails();
String remoteAddress = details != null ? details.getRemoteAddress()
	: "";
String sessionId = details != null ? details.getSessionId() : "";

Calendar cal = Calendar.getInstance();
logger.info("Login Successful:" + auth.getName() + " | Ip Address:"
		+ remoteAddress + " | sessionId=" + sessionId +  " | Epoch=" +cal.getTimeInMillis() );

// success logins are processed further in
// AKASecurityContextFormationFilter
   }
 
Example #8
Source File: LoginSuccessHandler.java    From fredbet with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
@Override
public void onApplicationEvent(AuthenticationSuccessEvent event) {
	Object principal = event.getAuthentication().getPrincipal();
	if (principal instanceof AppUser) {
		AppUser appUser = (AppUser) principal;
		LOG.debug("User with name {} has logged in.", appUser.getUsername());
		Optional<AppUser> appUserOpt = appUserRepository.findById(appUser.getId());
		if (appUserOpt.isPresent()) {
			AppUser foundAppUser = appUserOpt.get();
			foundAppUser.setLastLogin(LocalDateTime.now());
			appUserRepository.save(foundAppUser);
		}
	}
}
 
Example #9
Source File: SuccessfulLoginListener.java    From webanno with Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example #10
Source File: UserLoginListener.java    From find with MIT License 5 votes vote down vote up
@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);
    }
}
 
Example #11
Source File: AuthenticationListener.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@EventListener({ InteractiveAuthenticationSuccessEvent.class, AuthenticationSuccessEvent.class })
public void handleAuthenticationSuccess( AbstractAuthenticationEvent event )
{
    Authentication auth = event.getAuthentication();

    if ( TwoFactorWebAuthenticationDetails.class.isAssignableFrom( auth.getDetails().getClass() ) )
    {
        TwoFactorWebAuthenticationDetails authDetails =
            ( TwoFactorWebAuthenticationDetails ) auth.getDetails();

        log.debug( String.format( "Login attempt succeeded for remote IP: %s", authDetails.getIp() ) );
    }

    final String username = event.getAuthentication().getName();

    UserCredentials credentials = userService.getUserCredentialsByUsername( username );

    boolean readOnly = config.isReadOnlyMode();

    if ( Objects.nonNull( credentials ) && !readOnly )
    {
        credentials.updateLastLogin();
        userService.updateUserCredentials( credentials );
    }

    securityService.registerSuccessfulLogin( username );
}
 
Example #12
Source File: AuthenticationSuccessEventHandler.java    From smaker with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Handle an application event.
 *
 * @param event the event to respond to
 */
@Override
public void onApplicationEvent(AuthenticationSuccessEvent event) {
	Authentication authentication = (Authentication) event.getSource();
	if (CollUtil.isNotEmpty(authentication.getAuthorities())) {
		handle(authentication);
	}
}
 
Example #13
Source File: AuthenticationSuccessEventListener.java    From spring-boot with Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(final AuthenticationSuccessEvent e) {
    final WebAuthenticationDetails auth = (WebAuthenticationDetails) e.getAuthentication().getDetails();
    if (auth != null) {
        loginAttemptService.loginSucceeded(auth.getRemoteAddress());
    }
}
 
Example #14
Source File: OpenIdConnectFilter.java    From OAuth-2.0-Cookbook with MIT License 5 votes vote down vote up
@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;
    }
}
 
Example #15
Source File: AuthenticationSuccessEventListener.java    From cola with MIT License 5 votes vote down vote up
@Override
public void onApplicationEvent(AuthenticationSuccessEvent event) {
	if (event.getClass().equals(AuthenticationSuccessEvent.class)) {
		Authentication authentication = event.getAuthentication();
		this.userService.processLoginSuccess(authentication.getName(), null, null);
		log.info("Authentication success:" + authentication.getName() + " ," + AuthenticationSuccessEvent.class);
	}
}
 
Example #16
Source File: JwtAuthenticationSuccessEventListener.java    From cola with MIT License 5 votes vote down vote up
@Override
public void onApplicationEvent(AuthenticationSuccessEvent event) {
	jwtTokenStore.save(event.getAuthentication().getName(), event.getAuthentication());
	if (log.isDebugEnabled()) {
		log.debug("Jwt token: [{}] store success", event.getAuthentication().getName());
	}
}
 
Example #17
Source File: AuthenticationSuccessListener.java    From gravitee-management-rest-api with Apache License 2.0 4 votes vote down vote up
@Override
public void onApplicationEvent(AuthenticationSuccessEvent event) {
    final UserDetails details = (UserDetails) event.getAuthentication().getPrincipal();
    try {
        UserEntity registeredUser = userService.findBySource(details.getSource(), details.getSourceId(), false);
        updateRegisteredUser(registeredUser, details);
        // Principal username is the technical identifier of the user
        // Dirty hack because spring security is requiring a username...
        details.setUsername(registeredUser.getId());
        // Allows to override email of in memory users
        if ("memory".equals(details.getSource()) && registeredUser.getEmail() != null) {
            details.setEmail(registeredUser.getEmail());
            SecurityContextHolder.getContext().setAuthentication(event.getAuthentication());
        }
    } catch (UserNotFoundException unfe) {
        final NewExternalUserEntity newUser = new NewExternalUserEntity();
        newUser.setSource(details.getSource());
        newUser.setSourceId(details.getSourceId());
        newUser.setFirstname(details.getFirstname());
        newUser.setLastname(details.getLastname());
        newUser.setEmail(details.getEmail());

        byte[] pictureData = details.getPicture();
        if(pictureData != null && pictureData.length > 0) {
            String picture = computePicture(pictureData);
            newUser.setPicture(picture);
        }

        boolean addDefaultRole = false;
        if (event.getAuthentication().getAuthorities() == null || event.getAuthentication().getAuthorities().isEmpty()) {
            addDefaultRole = true;
        }
        UserEntity createdUser = userService.create(newUser, addDefaultRole);
        // Principal username is the technical identifier of the user
        details.setUsername(createdUser.getId());

        if (!addDefaultRole) {
            addRole(RoleScope.ENVIRONMENT, createdUser.getId(), event.getAuthentication().getAuthorities());
            addRole(RoleScope.ORGANIZATION, createdUser.getId(), event.getAuthentication().getAuthorities());
        }
    }


    userService.connect(details.getUsername());
}
 
Example #18
Source File: HostedLoginCodeFlowExampleApplication.java    From samples-java-spring with Apache License 2.0 4 votes vote down vote up
/**
 * Create an ApplicationListener that listens for successful logins and simply just logs the principal name.
 * @return a new listener
 */
@Bean
protected ApplicationListener<AuthenticationSuccessEvent> authenticationSuccessEventApplicationListener() {
    return event -> logger.info("Authentication Success with principal: {}", event.getAuthentication().getPrincipal());
}
 
Example #19
Source File: AuthenticationSuccessEventListener.java    From oauth2-resource with MIT License 4 votes vote down vote up
@Override
public void onApplicationEvent(AuthenticationSuccessEvent event) {
    log.info("User Oauth2 login success");
}
 
Example #20
Source File: PreAuthencationSuccessListener.java    From pre with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onApplicationEvent(AuthenticationSuccessEvent event) {
    PreSecurityUser xytSecurityUser = (PreSecurityUser) event.getAuthentication().getPrincipal();;
    log.info("用户名:{},成功登录", xytSecurityUser.getUsername());
}