Get session object from one controller method to another - java

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());
}

Related

Authorize requests using tokens stored in database

I am try to implement authentication filter in spring project. I have tokens stored for customers in database. Currently the authorization happens separately in each API.
Here is the current version of the api:
#CrossOrigin
#RequestMapping(value="/thirdParty", method=RequestMethod.GET)
private void getThirdPartyOffers(HttpServletRequest request, HttpServletResponse response){
response.setHeader("Access-Control-Allow-Origin", "*");
String authToken = request.getHeader(AUTHORIZATION);
if (null != authToken) {
Customer customer = getCustomer(authToken, sessionFactory);
if (null != customer) {
JsonObject responseObject = new JsonObject();
Integer cityId=-1;
if(customer.getDeliveryAddress()!=null &&customer.getDeliveryAddress().getCity()!=null){
cityId=customer.getDeliveryAddress().getCity().getId();
}else if(customer.getLocality()!=null){
cityId= customer.getLocality().getCity().getId();
}else if(customer.getArea()!=null){
cityId= customer.getArea().getCity().getId();
}
JsonArray offers = promotionOfferUtils.getThirdPartyOfferList(customer, cityId);
responseObject.add("offers", offers);
responseObject.addProperty(ERROR, false);
sendResponse(response,HttpServletResponse.SC_OK,responseObject);
return;
}else{
sendResponse(response, HttpServletResponse.SC_UNAUTHORIZED, ERROR,
AUTHORIZATION_FAILED);
}
}else {
sendResponse(response, HttpServletResponse.SC_UNAUTHORIZED, ERROR,
AUTHORIZATION_FAILED);
}
}
The final api should be like this:
#CrossOrigin
#RequestMapping(value = "/thirdParty", method = RequestMethod.GET)
private void getThirdPartyOffers(HttpServletRequest request, HttpServletResponse response) {
response.setHeader("Access-Control-Allow-Origin", "*");
String customerId = response.getHeader("customerId");
Customer customer = getCustomer(sessionFactory, customerId);
JsonObject responseObject = new JsonObject();
Integer cityId = -1;
if (customer.getDeliveryAddress() != null && customer.getDeliveryAddress().getCity() != null) {
cityId = customer.getDeliveryAddress().getCity().getId();
} else if (customer.getLocality() != null) {
cityId = customer.getLocality().getCity().getId();
} else if (customer.getArea() != null) {
cityId = customer.getArea().getCity().getId();
}
JsonArray offers = promotionOfferUtils.getThirdPartyOfferList(customer, cityId);
responseObject.add("offers", offers);
responseObject.addProperty(ERROR, false);
sendResponse(response, HttpServletResponse.SC_OK, responseObject);
return;
}
I am now trying to authenticate using a filter.Here I have created the required filter.
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// invoked when a matching request sent to the server
// used to intercept the request and transform the response
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setHeader("Access-Control-Allow-Headers", "origin, content-type, Authorization, accept, x-requested-with, IS_UPDATED");
httpResponse.setHeader("Access-Control-Max-Age", "60"); // seconds to cache preflight request --> less OPTIONS traffic
httpResponse.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS");
httpResponse.setHeader("Access-Control-Allow-Origin", "*");
Customer customer;
try
{
if ("OPTIONS".equalsIgnoreCase(httpRequest.getMethod())) {
httpResponse.setStatus(HttpServletResponse.SC_OK);
return;
} else {
String url = ((HttpServletRequest) request).getRequestURL().toString();
String endUrlPath = url.split("/").length > 1 ? url.split("/")[url.split("/").length - 1] : "";
if (!endUrlPath.equalsIgnoreCase("login") && !endUrlPath.equalsIgnoreCase("forgotPasswordSendOtp") &&
!endUrlPath.equalsIgnoreCase("changePasswordInForgotPassword") && !endUrlPath.equalsIgnoreCase("verifyUserOTP")) {
String authToken = httpRequest.getHeader("Authorization");
customer = getCustomer(authToken,sessionFactory);
if (customer == null) {
httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
return;
}
httpResponse.addHeader("customerId", Integer.toString(customer.getId()));
}
}
} catch (Exception ex) {
httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
return;
}
chain.doFilter(request, response);// invokes next filter in the chain
}
The problem now is that the sessionFactory object is null at this point and I am unable to access database to get the customer.
I am unable to figure out how to get access to sessionFactory when the startup is incomplete?

Java equivalent for C# HttpContext

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;
}

Finding why an Angular 5 service subscription is returning a null observable

I have the following service subscription in my component:
this.userService.loginUser(this.user).subscribe(users => {
if (users == null) {
console.log('users is null');
this.isValid = !this.isValid;
} else {
this.userService.subscribers.next(users);
localStorage.setItem('user', JSON.stringify(users));
console.log(`User, ${this.user.username}, successfully logged in!`);
console.log(localStorage.getItem('user'));
this.router.navigate(['dashboard']);
}
});
The service method looks like this:
public loginUser(user: User) {
console.log(`Attempting to login user: ${user.username}`);
const json = JSON.stringify(user);
this.currentUser = user;
return this.http.post<User>(API_URL + 'login', json, HTTP_OPTIONS);
}
The post request goes to this java servlet method:
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("login attempt");
if (req.getInputStream() != null) {
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(req.getInputStream(), User.class);
user = userService.loginUser(user);
if (user != null) {
user.setPassword("");
HttpSession session = req.getSession();
session.setAttribute("user", user);
}
}
}
On the java end, a username and password match is found and the session attribute is correctly set. However, on the Angular end, 'users' is null, as evidenced by the console.log('users is null') in the first code block. So my question is, why is this null? Can someone please help me understand the mechanics of this? I'm having a very hard time grasping how certain aspects of Angular even work...
So the problem was that in the servlet I didn't have a response. At the end I needed
PrintWriter out = resp.getWriter();
out.write(mapper.writeValueAsString(user));

Fetching old session value even if session is destroyed

#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.

Getting sessionId without accessing the session using cookies API

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.

Categories