What is the Java Equivalent for HttpContext in C#? I need to convert the following to Java. This code is basically extracting a cookie.
// This method returns the username from the login cookie, or null if no user is logged in.
public string ExtractUser(HttpContext context)
{
// Get the correct cookie from the request
var Cookie = context.Request.Cookies["dummyUser"];
// Return the cookie's value if it exists
if ((Cookie != null) && (Cookie.Value != null))
return Cookie.Value;
// Return null otherwise
return null;
}
Code base from here: https://sisense.dev/guides/sso/jwt/#actions
Try HttpServletRequest
See Here getCookies() method
public static String getCookie(HttpServletRequest req,String name) {
Cookie[] cookies = req.getCookies();
if(cookies!=null) {
for (Cookie cookie : cookies) {
if(cookie.getName().equals(name)) {
return cookie.getValue();
}
}
}
return null;
}
Related
I have the following code which is supposed to get user's IP:
public String getUserIP()
{
Object details = getDetails();
if (details instanceof WebAuthenticationDetails)
{
return ((WebAuthenticationDetails)details).getRemoteAddress();
}
return "";
}
#Nullable
public Object getDetails()
{
Authentication authentication = getCurrentUserAuth();
return authentication != null ? authentication.getDetails() : null;
}
However, under some unknown circumstances it returns 127.0.0.1 instead of real IP.
I decided to re-write like that:
public String getUserIP()
{
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
HttpServletRequest request = attr.getRequest();
String ip = request.getHeader("X-Forwarded-For").split(',')[0];
return ip;
}
But in some cases the header X-Forwarded-For is null. The exception only occurs where getUserIP() from the first snippet returns valid IP address. What's the problem? The web server is tomcat. Thanks in advance.
You can update like this.
public String getUserIP()
{
ServletRequestAttributes attr = (ServletRequestAttributes)
RequestContextHolder.currentRequestAttributes();
HttpServletRequest request = attr.getRequest();
return request.getRemoteAddr();
}
You Can Try this
public static String getUserIP(HttpServletRequest request) {
String xForwardedForHeader = request.getHeader("X-Forwarded-For");
if (xForwardedForHeader == null) {
return request.getRemoteAddr();
} else {
// As of https://en.wikipedia.org/wiki/X-Forwarded-For
// The general format of the field is: X-Forwarded-For: client, proxy1, proxy2 ...
// we only want the client
return new StringTokenizer(xForwardedForHeader, ",").nextToken().trim();
}
}
Can I know how can I get the session object which I have set in one controller method to another controller method.
Code:
public ResponseEntity<String> generateId(#RequestBody IdCreationVO idCreationVO, HttpServletRequest request) throws CareBusinessServiceException {
log.info("In Controller Method: generateId : "+idCreationVO.toString());
if(null !=idCreationVO && null == idCreationVO.getIsSupressCommunication()) {
HttpSession session = request.getSession();
session.setAttribute(AmhiConstants.COMMUNICATION_SUPPRESSED, idCreationVO.getIsSupressCommunication());
log.info("session object communication: "+ idCreationVO.getIsSupressCommunication());
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
return new ResponseEntity(idCreationService.generateId(idCreationVO), headers,
HttpStatus.OK);
}
public ResponseEntity<String> updateAuthorizationDetails(#RequestBody AuthorizationVO authorizationVO, HttpServletRequest request) throws CareBusinessServiceException {
String communicationSuppressed = null;
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
String authNbrResponse = idCreationService.updateAuthorizationDetails(authorizationVO);
if(null != request.getSession()) {
communicationSuppressed = (String) request.getSession().getAttribute(AmhiConstants.COMMUNICATION_SUPPRESSED);
log.info("communicationSuppressed value: "+ communicationSuppressed);
}
/** This method is get triggered from controller as the communication registered functionality get excecuted before updateAuthorizationDetails ends **/
if (null != authNbrResponse && communicationSuppressed.equals(AmhiConstants.CONSTANT_Y)) {
String[] authorizationNumber = authNbrResponse.split(":");
if (authorizationNumber.length > 1) {
if (authorizationNumber[1].equalsIgnoreCase(AmhiConstants.STATUS_SUCCESS)) {
idCreationService.triggercommunicationAfterAuthorizationRegistered(authorizationNumber[0]);
}
}
}
return new ResponseEntity(authNbrResponse, headers,
HttpStatus.OK);
}
As per requirement I need the value which been sent in generateId method to be get used in updateAuthorizationDetails method.
Can I know the above code implementation works fine in user session?
session.setAttribute and session.getAttribute methods should work.
But the problem seems to be in the if condition:
if(null !=idCreationVO && null == idCreationVO.getIsSupressCommunication()) {
HttpSession session = request.getSession();
session.setAttribute(AmhiConstants.COMMUNICATION_SUPPRESSED, idCreationVO.getIsSupressCommunication());
log.info("session object communication: "+ idCreationVO.getIsSupressCommunication());
}
It checks whether idCreationVO.getIsSupressCommunication() is null and then sets it to the session. In other words, it only sets the variable to the session when it is null.
I guess you mean:
if(null !=idCreationVO && null != idCreationVO.getIsSupressCommunication()) {
HttpSession session = request.getSession();
session.setAttribute(AmhiConstants.COMMUNICATION_SUPPRESSED, idCreationVO.getIsSupressCommunication());
log.info("session object communication: "+ idCreationVO.getIsSupressCommunication());
}
#Override
public void sessionDestroyed(HttpSessionEvent arg0)
{
boolean isRemoved = sessionIdSet.remove(arg0.getSession().getId());
if (isRemoved)
{
arg0.getSession().invalidate();
System.out.println(arg0.getSession().getAttribute("userName"));
System.out.println("session destroyed");
}
}
Suppose the attribute userName was testUser at the time of login. So after timeout in my java console I get null and session destroyed printed. So if it is null that means when I do following in my jsp I should get null but instead still I get testUser
$("body").click(function(event){
var property="<%=session.getAttribute("userName")%>";
//Here I expect property to be null as session is destroyed
//and it prints null in java so it should also here.
alert(property);
//But what i get here is testUser
}
Using Spring interceptor
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException {
boolean allowRequest = true;
String requestUri = request.getRequestURI().toString();
HttpSession session = request.getSession(false);
logger.info("Pre-intercepting request URI: " + requestUri);
try {
if(null != session) {
String sessionBelongsTo = (String) session.getAttribute("CUR_TYPE");
String user = (String) session.getAttribute("userName");
System.out.println(user);
if(!requestUri.endsWith("/login") && !requestUri.endsWith("/loginauth") && !requestUri.endsWith("sap-ui-core.js") && !requestUri.endsWith("/main")) {
if(null == user) {
logger.info(""
+ "Login required, redirecting to LOGIN page");
response.sendRedirect(request.getContextPath() + "/login");
allowRequest = false;
}
else {
logger.info("Login not required");
}
}
}
else{
logger.debug("session is null.redirecting to login");
session = request.getSession();
response.sendRedirect(request.getContextPath() + "/login");
allowRequest = false;
}
}catch(IOException ioe) {
logger.info(ioe.getMessage());
allowRequest = false;
}
return allowRequest;
}
Using interceptor makes an redirect call GET http://localhost:9090/app/login which is successfull but redirect never really happens.
You are mixing two different codes. You have to realize, where and when each code is executed - JSP on the server when the page is requested and rendered (i.e. before the response is send to the browser) and Javascript in the browser, after the browser receives the already generated response.
I.e. <%=session.getAttribute("userName")%> is processed on the server, and your browser receives e.g. var property="johndoe"; - the JSP code is NOT executed again when your onclick handler is executed.
I am creating a session in one of the servlets of my web application using HttpServletRequest.getSession(true) which also creates a cookie JSESSIONID. I want to change the path associated with this cookie. I am trying to do this by setPath method but its not working. I am using tomcat6. Thanks in advance. Below is the code I am using
HttpSession session = httpRequest.getSession(true);
Cookie[] cookies = httpRequest.getCookies();
if(cookies != null) {
for (Cookie c : cookies)
{
if(c.getName().equals("JSESSIONID"))
{
c.setPath("somepath");
}
}
}
You have changed the cookie path but did not attached the modified cookie to the response. So on the client side, the change is never going to be recognized.
Add the modified cookie to the response like this httpResponse.addCookie(c) after modifying it.
Try this code:
HttpSession session = httpRequest.getSession(true);
Cookie[] cookies = httpRequest.getCookies();
if(cookies != null) {
for (Cookie c : cookies)
{
if(c.getName().equals("JSESSIONID"))
{
c.setPath("somepath");
httpResponse.addCookie(c);
}
}
}
However it will not delete the existing cookie which has the old path instead it will create a new cookie with new path.
Unfortunately i could not able to find a way to delete the existing cookie. I have tried to remove the old cookie by setting it maxAge to -1 but didn't worked. Here is the code that i've tried so far:
String jSessionId = null;
HttpSession session = request.getSession(false);
if(session == null) {
session = request.getSession(true);
}
Cookie[] cookies = request.getCookies();
if(cookies != null) {
for (Cookie c : cookies)
{
if(c.getName().equals("JSESSIONID"))
{
jSessionId = c.getValue();
c.setValue(null);
c.setMaxAge(0);
response.addCookie(c);
}
}
}
if(jSessionId != null) {
Cookie c = new Cookie("JSESSIONID", jSessionId);
c.setPath("/servlet/sayhello");
c.setHttpOnly(true);
response.addCookie(c);
}
There is no major issues by having 2 different cookies. So you can use the first code snippet if you are comfortable with having two cookies.
I need to get current session Id without hitting the session (to give it a chance to expire).
I've used Cookies from Servlet code in order keep the session not-touched and then make the session expires after its timeout time.
I am using the following code:
public static String getSessionId(HttpServletRequest request)
{
String sessionId = "";
String logMsg = "";
if (request != null)
{
String sessionTimeout = PropertiesReader.SESSION_TIMEOUT_SCHEMA;
if (sessionTimeout != null && SessionHelper.SESSION_TIMEOUT_FIXED.equalsIgnoreCase(sessionTimeout))
{
logMsg = "FIXED: Getting SessionId from Cookies with activating the session";
Cookie[] cookies = request.getCookies();
if (cookies != null)
{
for (Cookie cook : cookies)
{
if ("JSESSIONID".equalsIgnoreCase(cook.getName()))
{
sessionId = cook.getValue();
break;
}
}
}
} else
{
logMsg = "PER_USAGE: Getting SessionId from Session";
sessionId = request.getSession(false) != null ? request.getSession(false).getId() : "";
}
}else
{
logMsg = "Request object is null";
}
logger.info(logMsg + ", sessionId=" + sessionId);
return sessionId;
}
One one OC4J app server, it works fine. although on another oc4j server, the code of accessing cookies makes the session keep active and don't timeout!
EDIT:
I really stucked!, I've trying to place afilter to remove the JSESSIONID cookie and remove all cookies from the HttpServletRequest, but when I call getSession(false) on the request passed to the servlet, I got a valid Session!
class CookieRemovalHttpServletRequestWrapper extends HttpServletRequestWrapper
{
public static final String COOKIE_HEADER = "cookie";
public static final String JSESSIONID = "JSESSIONID";
public CookieRemovalHttpServletRequestWrapper(HttpServletRequest request)
{
super(request);
}
#Override
public String getHeader(String name)
{
if (COOKIE_HEADER.equalsIgnoreCase(name))
{
return "";
}
return super.getHeader(name);
}
#Override
public Enumeration getHeaderNames()
{
Enumeration e = super.getHeaderNames();
List l = new ArrayList();
while (e.hasMoreElements())
{
String headerName = (String) e.nextElement();
if (!COOKIE_HEADER.equalsIgnoreCase(headerName))
{
l.add(headerName);
}
}
return Collections.enumeration(l);
}
#Override
public Enumeration getHeaders(String name)
{
if (COOKIE_HEADER.equalsIgnoreCase(name))
{
return new Enumeration()
{
public boolean hasMoreElements()
{
return false;
}
public Object nextElement()
{
return null;
}
};
}
return super.getHeaders(name);
}
#Override
public Cookie[] getCookies()
{
Cookie[] cs = super.getCookies();
List<Cookie> cokRet = new ArrayList<Cookie>(cs.length);
for (Cookie c : cs)
{
if (c.getName().equalsIgnoreCase(JSESSIONID)) continue;
cokRet.add(c);
}
return cokRet.toArray(new Cookie[] {});
}
}
And really think to forget all about Session and just use the session Id as just a unique identifier to the user, and do it myself the hard way.
As to your code, don't do it the hard way, use HttpServletRequest#getRequestedSessionId() and HttpServletRequest#isRequestedSessionIdValid() instead to check the requested session ID and if it is valid.
if (request.getRequestedSessionId() != null && !request.isRequestedSessionIdValid()) {
// The session has been expired (or a hacker supplied a fake cookie).
}
As to your concrete problem:
the code of accessing cookies makes the session keep active and don't timeout!
No, the code doesn't do that. It's the HTTP request itself which does that. It is not true that whenever you don't call getSession() or something, the session timeout won't be postponed. It will be postponed on every single HTTP request fired by the client, regardless of whether you need the session in the code.
To learn about how sessions work, you may find this answer helpful: How do servlets work? Instantiation, sessions, shared variables and multithreading
The session expiring isn't dependent on your code accessing the session, it depends on the user making a request with that session. Every time the user makes a request, the session's timeout will reset itself.
If you want to not have the user's request re-set the timeout (ie. have a fixed-length session), then you will need to do additional things for configuring the session, including possibly using a different filter to handle sessions.
The session is not timeout, that is correct behavior, because request was accepted and session expiration is updated in any case.