@Override @Transactional(propagation = Propagation.REQUIRED) public void onApplicationEvent(InteractiveAuthenticationSuccessEvent event) { LdapUserDetails userDetails = (LdapUserDetails) event.getAuthentication().getPrincipal(); log.info("Login Successful: {}", userDetails.getUsername()); Proprietario proprietario = proprietarioRepository.findByUsuarioIgnoreCase(userDetails.getUsername()); if (proprietario == null) { log.debug("Primeiro acesso de {}", userDetails.getUsername()); proprietario = new Proprietario(); proprietario.setUsuario(userDetails.getUsername()); completarComNome(proprietario, userDetails); } proprietario.setDataLogin(new Date()); proprietarioRepository.save(proprietario); }
@EventListener protected void createOrUpdateLocalUserGiven(InteractiveAuthenticationSuccessEvent event) { String userName = event.getAuthentication().getName(); if (userDetailsManager.userExists(userName)) { //TODO: update user's profile? log.info(format("skip local user creation since [%s] exists", userName)); } else { log.info(format("begin local user creation for [%s]", userName)); User user = new User(userName, UUID.randomUUID().toString(), // The user should login with the external provider new ArrayList<GrantedAuthority>() { { add(new SimpleGrantedAuthority("ROLE_USER")); } }); userDetailsManager.createUser(user); log.info(format("End local user creation for [%s]", userName)); } }
@Override protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authResult) throws IOException, ServletException { ServiceLocator.findService(AuthenticationManagement.class).onSuccessfulAuthentication( authResult); getRememberMeServices().loginSuccess(request, response, authResult); // Fire event if (this.eventPublisher != null) { eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(authResult, this .getClass())); } getSuccessHandler().onAuthenticationSuccess(request, response, authResult); }
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authResult) throws IOException, ServletException { if (logger.isDebugEnabled()) { logger.debug("Authentication success. Updating SecurityContextHolder to contain: " + authResult); } SecurityContextHolder.getContext().setAuthentication(authResult); rememberMeServices.loginSuccess(request, response, authResult); // Fire event if (this.eventPublisher != null) { eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(authResult, this.getClass())); } authenticationSuccessHandler.onAuthenticationSuccess(request, response, authResult); }
@Override protected void successfulAuthentication(final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain, final Authentication authResult) throws IOException, ServletException { LOGGER.debug("Authentication success. Updating SecurityContextHolder to contain: {}", authResult); // Set authentication to context SecurityContextHolder.getContext().setAuthentication(authResult); // Fire event if (this.eventPublisher != null) { this.eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(authResult, this.getClass())); } // Proceed request chain.doFilter(request, response); }
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authResult) throws IOException, ServletException { if (logger.isDebugEnabled()) { logger.debug("Authentication success. Updating SecurityContextHolder to contain: " + authResult); } SecurityContextHolder.getContext().setAuthentication(authResult); if (this.eventPublisher != null) { eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(authResult, this.getClass())); } removeJSessionIdCookie(request, response); // successHandler.onAuthenticationSuccess(request, response, authResult); }
public void onApplicationEvent(ApplicationEvent event) { try { if (event instanceof InteractiveAuthenticationSuccessEvent) { this.logLoginSuccess(event); } if (event instanceof AuthenticationFailureBadCredentialsEvent) { this.logBadCredential(event); } if (event instanceof AuthenticationFailureLockedEvent) { this.logLocked(event); } if (event instanceof AuthenticationFailureDisabledEvent) { this.logDisabled(event); } if (event instanceof AuthenticationFailureExpiredEvent) { this.logAccountExpired(event); } if (event instanceof AuthenticationFailureCredentialsExpiredEvent) { this.logCredentialExpired(event); } } catch (Exception ex) { logger.error(ex.getMessage(), ex); } }
public void logLoginSuccess(ApplicationEvent event) throws Exception { InteractiveAuthenticationSuccessEvent interactiveAuthenticationSuccessEvent = (InteractiveAuthenticationSuccessEvent) event; Authentication authentication = interactiveAuthenticationSuccessEvent .getAuthentication(); String tenantId = this.getTenantId(authentication); Object principal = authentication.getPrincipal(); String userId = null; if (principal instanceof SpringSecurityUserAuth) { userId = ((SpringSecurityUserAuth) principal).getId(); } else { userId = authentication.getName(); } AuditDTO auditDto = new AuditDTO(); auditDto.setUserId(userId); auditDto.setAuditTime(new Date()); auditDto.setAction("login"); auditDto.setResult("success"); auditDto.setApplication("lemon"); auditDto.setClient(getUserIp(authentication)); auditDto.setServer(InetAddress.getLocalHost().getHostAddress()); auditDto.setTenantId(tenantId); auditConnector.log(auditDto); // 登录成功,再发送一个消息,以后这里的功能都要改成listener,不用直接写接口了。解耦更好一些。 ctx.publishEvent(new LoginEvent(authentication, userId, this .getSessionId(authentication), "success", "default", tenantId)); }
@Override public void onApplicationEvent(InteractiveAuthenticationSuccessEvent event) { Authentication authentication = event.getAuthentication(); String ip = saveEvent(loginlogService, authentication); Optional.ofNullable(userMapper.findOne(authentication.getName())).ifPresent(user -> { userMapper.updateSelective(user.getId(), User.builder() .accesstime(Instant.now()) .ip(ip) .build()); }); }
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); } }
@Transactional public void auditLoginSuccessEvent(InteractiveAuthenticationSuccessEvent successEvent) { final AccountActivityMessage message = createLogMessage( null, successEvent.getAuthentication(), AccountActivityMessage.ActivityType.LOGIN_SUCCESS); logMessageRepository.save(message); }
@Override public void onApplicationEvent( InteractiveAuthenticationSuccessEvent event ) { SemossUser user = SemossUser.class.cast( event.getAuthentication().getPrincipal() ); String username = user.getUsername(); if ( !usermapper.exists( username ) ) { try { usermapper.create( user ); } catch ( Exception e ) { log.error( e, e ); } } }
@Test public void testOtherAuthenticationSuccess() { this.listener.onApplicationEvent(new InteractiveAuthenticationSuccessEvent( new UsernamePasswordAuthenticationToken("user", "password"), getClass())); // No need to audit this one (it shadows a regular AuthenticationSuccessEvent) verify(this.publisher, never()).publishEvent((ApplicationEvent) anyObject()); }
@Override @Transactional public void onApplicationEvent(InteractiveAuthenticationSuccessEvent event) { Object principal = event.getAuthentication().getPrincipal(); if (principal instanceof JpaUserDetails) { Long userId = ((JpaUserDetails) principal).getUserDbId(); this.jpaQueryFactory.update(QUser.user).setNull(QUser.user.lockedOutUntil) .setNull(QUser.user.failedLogins).where(QUser.user.id.eq(userId)) .execute(); } }
@Override public void onApplicationEvent(InteractiveAuthenticationSuccessEvent authenticationSuccessEvent) { Authentication authentication = authenticationSuccessEvent.getAuthentication(); if (!(authentication instanceof OAuth2Authentication)) { return; } OAuth2Authentication auth = (OAuth2Authentication) authentication; Map<String, String> details = (Map) auth.getUserAuthentication().getDetails(); String complex = auth.getPrincipal().toString(); registerUserService.register(details.get("name"), details.get("email"), complex); }
@Override public void onApplicationEvent(InteractiveAuthenticationSuccessEvent event) { Object principal = event.getAuthentication().getPrincipal(); if (principal instanceof MongoUserDetails) { String userId = ((MongoUserDetails) principal).getUserDbId(); this.mongoDb.getCollection(User.class).updateOne(Filters.eq(CUser.id, userId), Updates.combine(Updates.unset(CUser.lockedOutUntil), Updates.set(CUser.failedLogins, 0))); } }
@Override @Transactional public void onApplicationEvent(InteractiveAuthenticationSuccessEvent event) { Object principal = event.getAuthentication().getPrincipal(); if (principal instanceof JpaUserDetails) { User user = this.entityManager.find(User.class, ((JpaUserDetails) principal).getUserDbId()); user.setLockedOut(null); user.setFailedLogins(null); user.setExpirationDate(LocalDateTime.now().plusYears(1)); } }
@Override public void onApplicationEvent(InteractiveAuthenticationSuccessEvent event) { final User user = users.get(event.getAuthentication().getName()); final boolean isAdmin = user.getRole().equals(User.ROLE_ADMIN); logger.info((isAdmin ? "Admin" : "User") + " with id " + user.getIdLink() + " has successfully logged in!"); }
@Override public void onApplicationEvent(InteractiveAuthenticationSuccessEvent event) { Authentication auth = event.getAuthentication(); if(auth instanceof UsernamePasswordAuthenticationToken) { UsernamePasswordAuthenticationToken oAuth2 = (UsernamePasswordAuthenticationToken)auth; if(oAuth2.getDetails() != null) { // This is a google user //CustomUserDetails userDetails = (CustomUserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal(); //updateDbUser(userDetails); } } }
@Override public void onApplicationEvent(InteractiveAuthenticationSuccessEvent appEvent) { String userId = (String) appEvent.getAuthentication().getPrincipal(); ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); if (sra != null) { HttpServletRequest req = sra.getRequest(); try { this.bootstrapNewUser(req, userId); } catch (IOException e) { e.printStackTrace(); logger.error(e); } } }
@Override public void onApplicationEvent(InteractiveAuthenticationSuccessEvent event) { userService.updateLastLogin(event.getAuthentication().getName()); }
/** * {@inheritDoc} */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest)) { throw new ServletException("Can only process HttpServletRequest"); } if (!(response instanceof HttpServletResponse)) { throw new ServletException("Can only process HttpServletResponse"); } HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; if (SecurityContextHolder.getContext().getAuthentication() == null) { Authentication rememberMeAuth = rememberMeServices.autoLogin(httpRequest, httpResponse); if (rememberMeAuth != null) { // Attempt authenticaton via AuthenticationManager try { rememberMeAuth = authenticationManager.authenticate(rememberMeAuth); ServiceLocator.findService(AuthenticationManagement.class) .onSuccessfulAuthentication(rememberMeAuth); if (LOG.isDebugEnabled()) { LOG.debug("SecurityContextHolder populated with remember-me token: '" + SecurityContextHolder.getContext().getAuthentication() + "'"); } // Fire event if (this.eventPublisher != null) { eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent( SecurityContextHolder.getContext().getAuthentication(), this .getClass())); } } catch (AuthenticationException authenticationException) { if (LOG.isDebugEnabled()) { LOG.debug("SecurityContextHolder not populated with remember-me token, as " + "AuthenticationManager rejected Authentication " + "returned by RememberMeServices: '" + rememberMeAuth + "'; invalidating remember-me token", authenticationException); } rememberMeServices.loginFail(httpRequest, httpResponse); } } chain.doFilter(request, response); } else { if (LOG.isTraceEnabled()) { LOG.trace("SecurityContextHolder not populated with remember-me token, as it already contained: '" + SecurityContextHolder.getContext().getAuthentication() + "'"); } chain.doFilter(request, response); } }
@Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; try { Authentication apiKeyAuth = apiKeyServices.autoLogin(request, response); if (apiKeyAuth != null) { apiKeyAuth = authenticationManager.authenticate(apiKeyAuth); SecurityContextHolder.getContext().setAuthentication(apiKeyAuth); onSuccessfulAuthentication(request, response, apiKeyAuth); if (logger.isDebugEnabled()) { logger.debug("SecurityContextHolder populated with api key: '" + SecurityContextHolder.getContext().getAuthentication() + "'"); } if (this.eventPublisher != null) { eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent( SecurityContextHolder.getContext().getAuthentication(), this.getClass())); } if (successHandler != null) { successHandler.onAuthenticationSuccess(request, response, apiKeyAuth); return; } } } catch (UsernameNotFoundException e) { SecurityContextHolder.getContext().setAuthentication(null); } catch (AuthenticationException authenticationException) { if (logger.isDebugEnabled()) { logger.debug("SecurityContextHolder not populated with api key, as " + "AuthenticationManager rejected Authentication returned by ApiKeyServices", authenticationException); } apiKeyServices.loginFail(request, response); onUnsuccessfulAuthentication(request, response, authenticationException); } chain.doFilter(request, response); }
@Override public void onApplicationEvent(InteractiveAuthenticationSuccessEvent event) { if(logger.isDebugEnabled()) { logger.debug("Login success"); } }
@Override public void onApplicationEvent(InteractiveAuthenticationSuccessEvent event) { System.out.println(event); }
@Override public void onApplicationEvent(InteractiveAuthenticationSuccessEvent interactiveAuthenticationSuccessEvent) { boolean changes = false; Pair<ReturnResult, JsonNode> miscPair = misc.findByKey("user-list"); JsonNode userList = null; if(miscPair.getLeft() != ReturnResult.MISC_JSON_FOUND) { userList = new ObjectNode(JsonNodeFactory.instance); ((ObjectNode)userList).set("key", new TextNode("user-list")); ((ObjectNode)userList).set("data", new ArrayNode(JsonNodeFactory.instance)); Logger.info(getClass(), "No previous user-list"); changes = true; } else { userList = miscPair.getRight(); Logger.info(getClass(), "Previous user-list found"); } MetkaAuthenticationDetails details = AuthenticationUtil.getAuthenticationDetails(); JsonNode userNode = null; for(JsonNode node : (userList.get("data"))) { JsonNode user = node.get("userName"); if(user != null && user.textValue().equals(details.getUserName()) ) { userNode = node; break; } } if(userNode == null) { userNode = new ObjectNode(JsonNodeFactory.instance); ((ObjectNode)userNode).set("userName", new TextNode(details.getUserName())); ((ArrayNode)userList.get("data")).add(userNode); changes = true; } if(!StringUtils.isEmpty(details.getDisplayName()) && (userNode.get("displayName") == null || !details.getDisplayName().equals(userNode.get("displayName").textValue()))) { ((ObjectNode)userNode).set("displayName", new TextNode(details.getDisplayName())); changes = true; } if(changes) { misc.insert("user-list", userList); Logger.info(getClass(), "Updated user-list"); } }