Example usage for org.springframework.security.web.authentication WebAuthenticationDetails getRemoteAddress

List of usage examples for org.springframework.security.web.authentication WebAuthenticationDetails getRemoteAddress

Introduction

In this page you can find the example usage for org.springframework.security.web.authentication WebAuthenticationDetails getRemoteAddress.

Prototype

public String getRemoteAddress() 

Source Link

Document

Indicates the TCP/IP address the authentication request was received from.

Usage

From source file:fr.xebia.audit.Auditor.java

/**
 * <p>/* w  w  w. java 2  s .  com*/
 * Emmits the audit message : <code>
 * "$date{yyyy-MM-dd'T'HH:mm:ss.SSSZZ} ${message} by ${spring-security-user}|anonymous [coming from ${remote-address}]"</code>.
 * <p>
 * <p>
 * If the Spring Security authentication is <code>null</code>, 'anonymous'
 * is emmitted.
 * </p>
 * <p>
 * If the Spring Security authentication details are
 * {@link WebAuthenticationDetails}, the incoming
 * {@link WebAuthenticationDetails#getRemoteAddress()} is emmitted.
 * </p>
 * 
 * @param message
 *            message to audit
 * @see SecurityContextHolder#getContext()
 */
public static void audit(String message) {
    if (message == null) {
        message = "";
    }
    StringBuilder msg = new StringBuilder(40 + message.length());

    SimpleDateFormat simpleDateFormat = (SimpleDateFormat) dateFormatPrototype.clone();
    msg.append(simpleDateFormat.format(new Date()));

    msg.append(" ").append(message).append(" by ");

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication == null) {
        msg.append("anonymous");
    } else {
        msg.append(authentication.getName());
        if (authentication.getDetails() instanceof WebAuthenticationDetails) {
            WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails();
            msg.append(" coming from " + details.getRemoteAddress());
        }
    }
    auditLogger.info(msg.toString());
}

From source file:com.lll.util.SpringSecurityUtils.java

/**
 * ??IP, ?.//from   w w  w  .ja va 2 s . c o m
 */
public static String getCurrentUserIp() {
    Authentication authentication = getAuthentication();
    if (authentication != null) {
        Object details = authentication.getDetails();
        if (details instanceof WebAuthenticationDetails) {
            WebAuthenticationDetails webDetails = (WebAuthenticationDetails) details;
            return webDetails.getRemoteAddress();
        }
    }

    return "";
}

From source file:com.rosy.bill.security.SpringSecurityUtils.java

/**
 * ??IP, ?.//from w  w w. j  a  va2s.c om
 */
public static String getCurrentUserIp() {
    Authentication authentication = getAuthentication();

    if (authentication == null) {
        return "";
    }

    Object details = authentication.getDetails();
    if (!(details instanceof WebAuthenticationDetails)) {
        return "";
    }

    WebAuthenticationDetails webDetails = (WebAuthenticationDetails) details;
    return webDetails.getRemoteAddress();
}

From source file:org.cloudfoundry.identity.uaa.authentication.UaaAuthenticationDetails.java

public UaaAuthenticationDetails(HttpServletRequest request) {
    WebAuthenticationDetails webAuthenticationDetails = new WebAuthenticationDetails(request);
    this.origin = webAuthenticationDetails.getRemoteAddress();
    this.sessionId = webAuthenticationDetails.getSessionId();
    String clientId = request.getParameter("client_id");
    if (clientId != null) {
        this.clientId = clientId;
    }//from  w w w . j  ava 2 s  . com
}

From source file:org.duracloud.account.security.auth.AuthProvider.java

@Override
protected void additionalAuthenticationChecks(UserDetails userDetails,
        UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
    super.additionalAuthenticationChecks(userDetails, authentication);

    DuracloudUser dcUser = (DuracloudUser) userDetails;
    String userIpLimits = dcUser.getAllowableIPAddressRange();

    // if user IP limits are set, check request IP
    if (null != userIpLimits && !userIpLimits.equals("")) {
        WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails();
        String requestIp = details.getRemoteAddress();

        String[] ipLimits = userIpLimits.split(";");
        for (String ipLimit : ipLimits) {
            if (ipInRange(requestIp, ipLimit)) {
                // User's IP is within this range, grant access
                log.debug("Allowing authentication check to continue for user " + dcUser.getUsername()
                        + " because their IP " + requestIp + " exists in a valid range " + ipLimit);
                return;
            }// w  ww .  jav  a2 s .  c  o  m
        }

        // There are IP limits, and none of them match the user's IP, deny
        log.debug("Denying authentication request for user " + dcUser.getUsername() + " because their IP "
                + requestIp + " does not match any valid ranges " + userIpLimits);
        throw new InsufficientAuthenticationException(
                "Originating IP for authentication request" + requestIp + " is not in an accepted range.");
    } else { // No user IP limits, which means all IPs are accepted
        log.debug("Allowing authentication check to continue for user " + dcUser.getUsername()
                + " because no IP limits are defined");
        return;
    }
}

From source file:fi.helsinki.opintoni.config.audit.AuditEventConverter.java

/**
 * Internal conversion. This method will allow to save additional data.
 * By default, it will save the object as string
 *
 * @param data the data to convert//from   w w  w.jav a 2 s .co m
 * @return a map of String, String
 */
public Map<String, String> convertDataToStrings(Map<String, Object> data) {
    Map<String, String> results = new HashMap<>();

    if (data != null) {
        for (String key : data.keySet()) {
            Object object = data.get(key);

            // Extract the data that will be saved.
            if (object instanceof WebAuthenticationDetails) {
                WebAuthenticationDetails authenticationDetails = (WebAuthenticationDetails) object;
                results.put("remoteAddress", authenticationDetails.getRemoteAddress());
                results.put("sessionId", authenticationDetails.getSessionId());
            } else {
                results.put(key, object.toString());
            }
        }
    }

    return results;
}

From source file:org.springframework.security.web.jackson2.WebAuthenticationDetailsMixinTest.java

@Test
public void webAuthenticationDetailsDeserializeTest() throws IOException, JSONException {
    String actualJson = "{\"@class\": \"org.springframework.security.web.authentication.WebAuthenticationDetails\","
            + "\"sessionId\": \"1\", \"remoteAddress\": \"/home\"}";
    WebAuthenticationDetails details = this.mapper.readValue(actualJson, WebAuthenticationDetails.class);
    assertThat(details).isNotNull();//w  w  w. j a  va2  s  .  co m
    assertThat(details.getRemoteAddress()).isEqualTo("/home");
    assertThat(details.getSessionId()).isEqualTo("1");
}

From source file:fr.xebia.monitoring.demo.payment.CreditCardServiceAuditingImpl.java

@Override
public PaymentTransaction purchase(MonetaryAmount total, Order order, String requestId) {
    StringBuilder auditMessage = new StringBuilder("creditcardservice.purchase(" + requestId + ", "
            + order.getAccount().getEmail() + ", " + total + ") by ");
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication == null) {
        auditMessage.append("anonymous");
    } else {/* ww  w  .  j a v a  2s. co  m*/
        auditMessage.append(authentication.getName());
        if (authentication.getDetails() instanceof WebAuthenticationDetails) {
            WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails();
            auditMessage.append(" coming from " + details.getRemoteAddress());
        }
    }

    long nanosBefore = System.nanoTime();
    try {
        PaymentTransaction paymentTransaction = creditCardService.purchase(total, order, requestId);

        auditMessage.append(" SUCCESS ").append(paymentTransaction.getTransactionId());
        auditMessage.append(" in ")
                .append(TimeUnit.MILLISECONDS.convert(System.nanoTime() - nanosBefore, TimeUnit.NANOSECONDS))
                .append(" ms");
        auditLogger.info(auditMessage.toString());
        return paymentTransaction;
    } catch (RuntimeException e) {
        auditMessage.append(" FAILURE ").append(Joiner.on(", ").join(Throwables.getCausalChain(e)));
        auditMessage.append(" in ")
                .append(TimeUnit.MILLISECONDS.convert(System.nanoTime() - nanosBefore, TimeUnit.NANOSECONDS))
                .append(" ms");
        auditLogger.warn(auditMessage.toString());
        throw e;
    }

}

From source file:fr.xebia.springframework.security.core.providers.ExtendedDaoAuthenticationProvider.java

/**
 * Checks that the {@link org.springframework.security.web.authentication.WebAuthenticationDetails#getRemoteAddress()}
 * matches one of the {@link ExtendedUser#getAllowedRemoteAddresses()}. If
 * the given <code>userDetails</code> is not an {@link ExtendedUser} of if
 * the given <code>authentication.details</code> is not a
 * {@link org.springframework.security.web.authentication.WebAuthenticationDetails}, then the ip address check is silently
 * by passed./*from   w  w w  . j a va2 s  .  com*/
 */
@Override
protected void additionalAuthenticationChecks(UserDetails userDetails,
        UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {

    super.additionalAuthenticationChecks(userDetails, authentication);

    if (!(userDetails instanceof ExtendedUser)) {
        if (log.isDebugEnabled()) {
            log.debug("Given userDetails '" + userDetails
                    + "' is not an ExtendedUser, skip ipAddress verification");
        }
        return;
    }
    ExtendedUser extendedUser = (ExtendedUser) userDetails;

    if (!(authentication.getDetails() instanceof WebAuthenticationDetails)) {
        if (log.isDebugEnabled()) {
            log.debug("Given authentication '" + authentication
                    + "' does not hold WebAuthenticationDetails, skip ipAddress verification");
        }
        return;
    }
    WebAuthenticationDetails webAuthenticationDetails = (WebAuthenticationDetails) authentication.getDetails();

    String remoteIpAddress = webAuthenticationDetails.getRemoteAddress();

    if (log.isDebugEnabled()) {
        log.debug("Evaluate permission for '" + extendedUser + "' to authenticate from ip address "
                + remoteIpAddress);
    }

    List<Pattern> allowedRemoteAddressesPatterns = extendedUser.getAllowedRemoteAddressesPatterns();
    if (!matchesOneAddress(remoteIpAddress, allowedRemoteAddressesPatterns)) {
        throw new BadCredentialsException("Access denied from IP : " + remoteIpAddress);
    }
}

From source file:com.rockagen.gnext.service.spring.security.extension.BasicWebAuthenticationDetails.java

@Override
public boolean equals(Object obj) {
    if (obj instanceof WebAuthenticationDetails) {
        WebAuthenticationDetails rhs = (WebAuthenticationDetails) obj;

        if ((getRemoteAddress() == null) && (rhs.getRemoteAddress() != null)) {
            return false;
        }/*  ww w  .j  av a  2 s .  com*/

        if ((getRemoteAddress() != null) && (rhs.getRemoteAddress() == null)) {
            return false;
        }

        if (getRemoteAddress() != null) {
            if (!getRemoteAddress().equals(rhs.getRemoteAddress())) {
                return false;
            }
        }

        if ((getSessionId() == null) && (rhs.getSessionId() != null)) {
            return false;
        }

        if ((getSessionId() != null) && (rhs.getSessionId() == null)) {
            return false;
        }

        if (getSessionId() != null) {
            if (!getSessionId().equals(rhs.getSessionId())) {
                return false;
            }
        }

        return true;
    }

    return false;
}