I am doing a webview project in android java in cordova framework .The session id is sent as cookie from the server when user logs in.I need the session id for maintaining the session. I am getting cookie as
ASP.NET_Session_Id=123345; yourAuthCookie=6415176A0448E891D99DAA57BBB7FC77785AD0A3F2BCBAF660957E1CE4A7C3D47E5FDF1DDA522FBC1306C96A50029E088805CC1ECC223CE0B4A29286327907779F5FFEBD8F6AA8B2CE685579667BB29D4CBC50C1EEA
I just want session id . How can i get just the session id from cookie?
After some research i found an answer,
public String cookieElement(String Url,String CookieName){
String CookieValue = null;
CookieManager cookieManager = CookieManager.getInstance();
String cookies = cookieManager.getCookie(Url);
String[] temp=cookies.split(";");
for (String ar1 : temp ){
if(ar1.contains(CookieName)){
String[] temp1=ar1.split("=");
CookieValue = temp1[1];
break;
}
}
return CookieValue;
}
the function can be called as
String sessionid = cookieElement("https://www.example.com/","ASP.NET_Session_Id");
Related
i am facing one issue in linkedIn social integration with spring mvc based web application updated their social library to 1.0a Oauth to 2.0 Oauth in linked in developer network i mentioned Redirect url to http://localhost:8080/Myproject/signin/linkedin here once i run the project linkedin login page is coming but after entering user name password on click of login page is redirected once again to login page it is not going particular page of application.
this is my spring code
public ProviderSignInController providerSignInController(ConnectionFactoryLocator connectionFactoryLocator, UsersConnectionRepository usersConnectionRepository) {
ProviderSignInController providerSignInController = new ProviderSignInController(connectionFactoryLocator, usersConnectionRepository, new SignInAdapter() {
#Override
public String signIn(String socialuserid, Connection<?> connection, Nativewebrequest request) {
final HttpServletRequest httpServletRequest = request.getNativeRequest(HttpServletRequest.class);
final HttpSession httpSession = httpServletRequest.getSession(false);
final User user = userService.getUserBySocialId(userService.getSocialUser(socialUserId).getUserId());
final SecurityUser securityUser;
if (httpSession != null) {
final String token = (String)httpSession.getAttribute("invitationToken");
if(token != null && !"".equals(token)) {
System.out.println("user service token ...");
final Invitation invitation = userService.consumeInvitation(token);
if(invitation != null) user.setMembers(userService.getInvitationMembers(invitation.getEmail(), invitation.getInviteType()));
user.setRole(invitation.getInviteType());
userService.removeInvitations(invitation.getEmail(), invitation.getInviteType());
userService.createUserMember(member);
}
httpSession.removeAttribute("invitationToken");
}
}
securityUser = new SecurityUser(user);
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(securityUser, null, securityUser.getAuthorities()));
return null;
}
});
client id and client secret id is mentioned correctly
i am little bit strck with this please help me sort out this is issue
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'm testing a website that requires some basic authentication. Upon successful login a session key is sent back in cookies. I've written some code to get this cookie via the web service. It ends like this:
public List<HttpCookie> getCookies(String Domain, String user, String pass) {
// Actual services to log in here
List<HttpCookie> cookies = cookieStore.getCookies();
for (HttpCookie cookie : cookies) {
System.out.println(cookie);
}
return cookies;
}
When I debug I can see my sessionKey in there with a valid value. It's got the same domain that I passed above, and a blank path like /.
Here's how I've tried adding the cookie to my WebDriver instance:
List<HttpCookie> cookies = getCookies(DOMAIN, USERNAME, PASSWORD);
for (HttpCookie cookie : cookies) {
String cookieName = cookie.getName();
String cookieValue = cookie.getValue();
String cookieDomain = cookie.getDomain();
String cookiePath = cookie.getPath();
Date cookieExpiry = new Date();
Cookie selCookie = new Cookie(cookieName, cookieValue, cookieDomain, cookiePath, cookieExpiry);
driver.manage().addCookie(selCookie);
}
driver.get(ROOT_URL+"/some/internal/page");
When I try to add selCookie I get the following error message:
org.openqa.selenium.InvalidCookieDomainException: You may only set cookies for the current domain
I'm copying the domain directly from the cookie I received. I even tried passing it as a bare String instead of relying on the getDomain() method, but it returned the same error. Any idea what could be causing it to complain?
To add a cookie to a WebDriver instance, the domain in the cookie has to match the current domain of the WebDriver instance. I was trying to add the cookie before driver had visited anything, so driver's current domain was blank. I fixed it by just sending driver to ROOT_URL before I retrieve the session cookie and add it to driver:
//Added this:
driver.get(ROOT_URL);
List<HttpCookie> cookies = getCookies(DOMAIN, USERNAME, PASSWORD);
for (HttpCookie cookie : cookies) {
String cookieName = cookie.getName();
String cookieValue = cookie.getValue();
String cookieDomain = cookie.getDomain();
String cookiePath = cookie.getPath();
Date cookieExpiry = new Date();
Cookie selCookie = new Cookie(cookieName, cookieValue, cookieDomain, cookiePath, cookieExpiry);
driver.manage().addCookie(selCookie);
}
driver.get(ROOT_URL+"/some/internal/page");
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.
I just enabled Session in my Google AppEngine/Java + GWT application. And how do I use it? How do I get session ID and play will all good stuff from it? Are there any real examples of simple login page where I'm just entering LoginName and Password, then it goes to the server over RPC call, authenticates against database and sends Session ID back to the client.
I have following code already but don't know what to do next:
GWT Login Form:
public class LoginForm {
private final LoginServiceAsync loginService = GWT.create(LoginService.class);
VerticalPanel loginVp = new VerticalPanel();
TextBox loginTxt = new TextBox();
TextBox passTxt = new TextBox();
Button loginBtn = new Button("Login");
public Widget getLoginWidget(){
loginBtn.addClickHandler(new ClickHandler(){
public void onClick(ClickEvent arg0) {
loginService.authenticateUser(loginTxt.getText(), passTxt.getText(),
new AsyncCallback<String>(){
public void onFailure(Throwable caught) {
InfoPanel.show(InfoPanelType.HUMANIZED_MESSAGE, "No Connetion", "Problem conneting to the server.");
}
public void onSuccess(String result) {
InfoPanel.show(InfoPanelType.HUMANIZED_MESSAGE, "Session ID", "Your session id is: " + result);
GWT.log("Setting up session", null);
String sessionID = result;
final long DURATION = 1000 * 60 * 60 * 24 * 14; //duration remembering login. 2 weeks
Date expires = new Date(System.currentTimeMillis() + DURATION);
Cookies.setCookie("sid", sessionID, expires, null, "/", false);
}
}
);
}
});
loginVp.add(loginTxt);
loginVp.add(passTxt);
loginVp.add(loginBtn);
return loginVp;
}
}
RPC Servlet:
public class LoginServiceImpl extends RemoteServiceServlet implements LoginService{
//Sends back to the client session id
public String authenticateUser(String login, String password){
String sessionId = new String();
// TODO: figure out how to work with session id in GAE/J
sessionId = "How to get session id?";
return sessionId;
}
public Boolean checkIfSessionIsValid(String sessionId){
//TODO: figure out how to check user's credentials
return true;
}
}
Any hints in the right direction would be helpful.
Thanks.
Enabling session support gives you a standard Servlet HttpSession.
This will be tracked by means of a cookie (called JSESSONID), which is managed by the servlet container under the covers. You do not need to care about the session id.
You can then set attributes (server-side) that will be associated with the session (so that you can retrieve them later).
HttpServletRequest request = this.getThreadLocalRequest();
HttpSession session = request.getSession();
// in your authentication method
if(isCorrectPassword)
session.setAttribute("authenticatedUserName", "name");
// later
if (session.getAttribute("authenticatedUserName") != null)
This should also work with Ajax requests from GWT.
Please refer to any Servlet tutorial for more details.
The drawback of sessions on GAE (compared to other servlet engines) is that they are serialized in and loaded from the database every time, which could be expensive, especially if you put a lot of data in there.
Here is how you can get the session in GAE:
this.getThreadLocalRequest().getSession();