How to get the IP address when a session is created? - java

In my grails application, I have implemented the interface HttpSessionListener to listen for session creation as given below:
class MyHttpSessionListener implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent event) {
log.info "***************** Session created: id= ${event.getSession()?.id}"
}
}
Now, I would like to log the IP address that is responsible for the session creation.
How can I do that?

you can access the RequestContextHolder and get the value
String ipAddr = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes())
.getRequest().getRemoteAddr();

As far as I know you can't using the HttpSessionListener interface.
You can get and log the IP Address from "ServletRequest.getRemoteAddr()" but you don't have access to the servlet request from HttpSessionListener or from HttpSessionEvent.
Best idea would to have a javax.servlet.Filter which gets the IP address and sets it as a session attribute if not already present. (You could also do the logging if not already present).

You can also use this interface in your HttpSessionListener : ServletRequestListener
You can implement : requestInitialized() like this.
#Override
public void requestInitialized(ServletRequestEvent servletRequestEvent) {
this.request = (HttpServletRequest) servletRequestEvent.getServletRequest();
}
it s working fine, the request object can bring you the remote adress, there is a méthod to do that

Related

Get HTTPRequest in HttpSessionListener

Due to project requirement I have created a HttpSessionListener in my spring based application.
public class SessionListener implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent se) {
//some business logic
}
}
I need to set some parameters in request in this class but I am not able to find any way to get http request object in this class. Is there any way to get the http request object here? If no what is the other way too implement it?

How to find whether all the data were added or removed in a session?

I am using the following getSession() method to obtain all the attributes that are being stored in a session. Is there a way to find out whether all the data that were added or removed each time when the user is going through the different pages in the application.
protected HttpServletRequest getRequest() {
return (HttpServletRequest) FacesContext.getCurrentInstance()
.getExternalContext().getRequest();
}
protected HttpSession getSession() {
return getRequest().getSession();
}
The HttpSessionAttributeListener interface is done for that. Create a class in your web app that implements this interface and override its methods. Then, register your class with the WebListener annotation or directly in your web.xml file.

Injection variable to websocket annotation #ServerEndpoint("/myVar")

I have chat which mapping to static URL. I need get the opportunity creating rooms for user.
How to inject variable in annotation #ServerEndpoint("/myVariable") when app already running?
class SomeClass{
public void createRoom(User user) {
String name = user.getName();
//...Somehow inject name to annotation #ServerEndpoint("/name")...
}
}
#ServerEndpoint("/chat") //May be replace to #ServerEndpoint(someGetteUserName())
public class ChatEndpoint {
#OnMessage
public void message(String message, Session client)
throws IOException, EncodeException {
for (Session peer : client.getOpenSessions()) {
peer.getBasicRemote().sendText(message);
}
}
}
I don't use Spring this is clear websocket and Glassfish.
Help me create implementation variable injection to annotation. Thank You.
I think that you don't need any injection if you only want to create and handle chat rooms. You just need to handle this by java code independently from your endpoint.
I recommend you to:
Create one websocket server endpoint: #ServerEndpoint("/chat"/{client_id}). This client id pathParam is may serve as a session id.
In ChatEndpoint class, initialize a list of rooms (this list should be static <=> common between all threads).
Create your business methods to handle clients and rooms(create/delete user, create/delete room, subscribe to a room...etc).
Finally, in your chat message try to specify the room destination. This can be very simple if you use JSON format.
message = { ... ,"room": "room1", ... }

Store IP address in UserDetails instance

In my web-application I'm using Spring Security and UserDetailsService implementation for authentication.
Now I neet to get and store somewhere the client IP address for the current session and I'd like to store it in UserDetails instance to retrieve it where I need.
Which is the correct way to achieve this? Is there any facility in Spring MVC/Security to get IP address in service layer?
NOTE I also need to know IP address if the client is not authenticated (to log access attempt)
The ip-address is already present in the Authentication object (not the UserDetails).
You can call getDetails() on the Authentication object and in a web application and properly configured Spring Security environment this will give you an instance of WebAuthenticationDetails which has the ip-address inside it. You can call the getRemoteAddress method to obtain the address. (See the javadoc)..
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
WebAuthenticationDetails details = (WebAuthenticationDetails) auth.getDetails();
String ipAddress = details.getRemoteAddress();
Something along those lines, you could put this behind a utility method or something to obtain the ip-address.
Apparently you want to log authentication attempts, this can be easily achieved by implementing an ApplicationListener and let that listen to AbstractAuthenticationEvents. Spring Security issues those for each authentication attempt, and also includes the Authentication (containing the IP-address) into it.
public class AuthenticationAttemptLoggerListener implements ApplicationListener<AbstractAuthenticationEvent> {
private final Logger logger = LoggerFactory.getLogger(AuthenticationAttemptLoggerListener.class);
public void onApplicationEvent(AbstractAuthenticationEvent event) {
Authentication auth = event.getAuthentication();
WebAuthenticationDetails details = (WebAuthenticationDetails) auth.getDetails();
String ipAddress = details.getRemoteAddress();
if (event instanceof AbstractAuthenticationFailureEvent) {
logger.warn("Unsuccesful authentication attemped from: {}", ipAddress);
} else {
logger.info("Succesful authentication attemped from: {}", ipAddress);
}
}
}
Something like this should catch and log everything. You might want to take a look at all the available events.

tomcat 8 javax.websockets doesn't work

I have tomcat 8-RC1 installed in order to use javax.websockets to write websocket based applications.
there are examples at http://svn.apache.org/viewvc/tomcat/trunk/webapps/examples/WEB-INF/classes/websocket/ that show exactly the structure of a websocket class so I implemented the following interface:
public interface XpoWebSocket {
#OnOpen
public void onOpen(Session session);
#OnClose
public void onClose();
#OnMessage
public void onTextMessage(String message);
public Session getSession();
}
in the line above the class deceleration I also included the following:
#ServerEndpoint(value = "/ServConnect")
public class ServConnect implements XpoWebSocket {
...
so the ServerEndPoint is to point how to access to websocket, the question is what do i need to set in web.xml ? for now the web socket is still not accessible.
I try to define ServConnect as a regular Servlet in web.xml but that doesn't work. it just time out when I try to access the ServConnect location.
what configuration am I missing to let this ServConnect websocket class work ?
The WebSocket spec says that you have to annotate the concrete class. ServConnect will be treated as a WebSocket endpoint but will not receive any events as the annotations on the interface are ignored.
I'd suggest getting your own version of the Echo example working and then expanding from there.

Categories