下面列出了怎么用org.springframework.security.authentication.event.AuthenticationSuccessEvent的API类实例代码及写法,或者点击链接到github查看源代码。
@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());
}
}
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) {
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);
}
}
@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
}
};
}
/**
* 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);
}
}
@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());
}
}
@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);
}
}
@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;
}
}
@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 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());
}
}
@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 );
}
@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
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(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);
}
}
}
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
}
@Override
public void onApplicationEvent(AuthenticationSuccessEvent event) {
PreSecurityUser xytSecurityUser = (PreSecurityUser) event.getAuthentication().getPrincipal();;
log.info("用户名:{},成功登录", xytSecurityUser.getUsername());
}
@Override
public void onApplicationEvent(AuthenticationSuccessEvent event) {
log.info("User Oauth2 login success");
}
/**
* 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());
}
@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());
}