RequestDispatcher to a jsp or servlet - servlets

Parameters[userName, UserPW] are sent by the user through a home.jsp. These parameters are matched in Login servlet against a stored userInfo Db using JDBC.
In the doPost method I am using if condition tfor authentication as follows
if (rs.next()) {
String refName = rs.getString("UserName");
String refPass = rs.getString("userPW");
if (user.equals(refName) && pw.equals(refPass)) {
out.println("<br>You are In");
RequestDispatcher dispatch= getRequestDispatcher("/SearchFriend.jsp");
dispatch.forward(req, resp);
System.out.println("sucess");
}
When the authentication is successfull, How can i direct the user to a new jsp or servlet where he can input few textboxes and select-options to select few records from the Db table.
its not clear to me that How can I direct the page to a Search.jsp page in above If condition. The Search.jsp is in weBContent folder of Juno.
I am using JDBC with tomcat7. Please help

It is probably not clear , what exactly your requirement are and what you are trying to achieve by looking into the code you have posted.Kindly reframe your question
According to my assumption , you need to redirect the user to the home page when the authentication is successful.
If so, for that you can store the user credential in the session by making a custom filter say SessionFilter implements Filter
HttpSession session = request.getSession();
Store the credenials in the session and if authentication is successful then redirect using :
RequestDispatcher view = request.getRequestDispatcher(/home.jsp);
view.forward(req,resp);

Related

How does session managment work in spring?

I can't really understand the concept of this.
Take a look what I have:
#PostMapping("/login")
public ModelAndView login( #ModelAttribute UserLoginDTO userDto, HttpSession session) {
if (authenticateService.loginCheck(userDto.getUsername(), userDto.getPassword())) {
session.setAttribute("sessionid",123);
return new ModelAndView("redirect:/profile");
} else {
return new ModelAndView("signin","error","Invalid username or password combination, or the user does not exist.");
}
}
I have set a sessionID to the session. When the user navigates around the website, how do I know that it is the same user?
Do I have to store the sessionID on server side in a ConcurrentHashMap?
And when there is a page switch I should do this?
if (conHashMap[...] == session.getId()) {...}
else //redirect to login page
Also on logout, do I just remove the element from the hashmap and call for session.invalidate()?
Or is there a way of doing this without using hashmaps at all?
You know the session is from the same user if the id is the same, yes.
You can eventually store informations on the session. Alternativelly, you can create session scoped beans :
#Component
#Scope(value="session")
public class MyComponent {
// ...
}
All you will store in this kind of objects are only accessible by one user.
Figured it out.
After invalidating, the browser will visit the site with a new session. The new session won't have the "sessionid" attribute bound to it. This way, I could determine which session is a valid one, without using hashmaps.
if (session.getAttribute("sessionid")==null){
return new ModelAndView("signin","error","Session expired, please log in again.");

Show a message after redirecting after a successful POST request without using TempData

I am using the Post-Redirect-Get pattern.
In my asp.net core MVC web app, this is what happens:
User submits a form via POST which adds an item to db.
Controller adds the new item and redirects with 302/303 to "/Home/Index/xxxx", where xxxx is the id of the item.
The new request (/Home/Index/xxxx) is served by the controller, and it displays the item. And the item url in the address bar is something the user can copy and share.
At step 3 above, I would like to show the user a message saying "Item was successfully added".
This is my code (without the success message):
public async Task<IActionResult> Index(string id)
{
ItemView itemView = null;
if (string.IsNullOrEmpty(id))
itemView = new ItemView(); // Create an empty item.
else
itemView = await itemService.GetItemAsync(id);
return View(itemView);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Index(ItemView itemView)
{
string id = await itemService.AddItemAsync(itemView);
return RedirectToAction("Index", "Home", new { id = id });
}
There are few ways to do this that I found in other answers on stackoverflow.
Redirect to "/Home/Index/xxxx?success=true". When action sees a success=true param, it can display the success message. But I don't want to use an extra param because I would like users to be able to just copy the url from the address bar and share it. And I don't want them sharing the url that has success param, because then everyone who clicks on the shared link will see the message "Item was successfully added".
This post suggests using TempData, which is a good solution. I think that would need me to enable sticky behavior on the server, which I would like to avoid if possible.
I can probably use referrer url to determine if the request came after a form submission, and in that case I can show the message.
The original answer by "snoopy" did point me in the right direction. But for some unknown reason, that answer no longer exists, so I am posting the answer myself in the hope it would benefit someone in future.
ASP .NET Core 1.1 and higher supports Cookie based Tempdata provider called CookieTempDataProvider. Link to Microsoft Docs.
This is similar to Session based Tempdata, but no data is stored on the server side. The response from the server set's a cookie in the browser with the data you want to store. The next request from the browser will include this cookie. The framework automatically parses this and populates this in TempData, which the controller can use. Once the controller reads this data, then the CookieTempDataProvider automatically adds the appropriate headers in the response to clear this cookie.
In your Startup class's ConfigureServices method, you need to register CookieTempDataProvider:
services.AddSingleton<ITempDataProvider, CookieTempDataProvider>();
To store some data in cookie based temp data, you simple set the value like this in your controller:
TempData["key"] = "value";
To read the data in your controller, you read it like this:
string value = TempData["key"];
if (value != null)
{
// Do something with the the value.
}
The check for non-null tells you if that key exists in TempData or not. Note that you can also check using .ContainsKey() method, but that is not counted as a read. The data (& the cookie) will not be cleared unless you read it. For example this will not clear the data:
if (TempData.ContainsKey("key"))
{
// Do something without actually reading the value of TempData["key"].
}

Sharing data in spring session attributes

Am using spring security and spring MVC. Am keeping a data in session attribute in unAuthenticated request(security:none in spring security). I tried printing the session id.After that i logged into the application. here new session is created. i tried printing the session id. both are different. but when i access the data placed in session attribute. it exist. In my understanding as new session is created after login, data should get lost or Is spring is sharing the session attributes ?
below is the code.
#RequestMapping(value = "/persistFKey")
public #ResponseBody String persistFKey(HttpServletRequest req,HttpServletResponse res,ModelMap modelMap) {
System.out.println("SEssion ID ----persistKey ----"+request.getSession().getId());
String fkey = request.getParameter("fkey");
modelMap.addAttribute("fkey", fkey);
return "success";
}
In spring security xml, i gave
<sec:http security="none" pattern="/portal/persistFKey" />
After login, while invoking the new page am getting the data kept in session attribute
#RequestMapping(value = "/renderScreen")
public String renderScreen(HttpServletRequest request, Model model,
#ModelAttribute("srceenModel") ScreenModel srceenModel,ModelMap modelMap) {
System.out.println("SEssion ID ----renderBooking----"+request.getSession().getId());
System.out.println("SessionKey persisted --------"+(String)modelMap.get("fkey"));
}
Both are in same spring MVC controller.
By default, Spring Security changes the user's session id on login to avoid Session Fixation attacks.
It is also nice enough to migrate the user's old session data to the new one.
You can change this behaviour via <session-management session-fixation-protection="..." />

HttpContext.User.Idenity is empty

I'm using asp.net and trying to assign roles for a user with forms authentication like this:
public ActionResult AdminLogin(string password, string username)
{
User _user = _us.GetUsers(username, password).FirstOrDefault();
if (_user != null)
{
string _username = _user.Username;
FormsAuthentication.SetAuthCookie(_username, false);
string[] _roles = _us.GetUserRoles(_username);
HttpContext.User = new GenericPrincipal(HttpContext.User.Identity, _roles);
return RedirectToAction("Index", "Admin");
When I debug HttpContext.User.Identity always is null, but _username and _roles contains the proper data. Howto fix this?
/M
Your action is setting the User IPrincipal for the current context. As soon as you redirect to your other action (and all subsequent requests) a new HttpContext is created with a null User IPrincipal.
What you could do is persist the information in the authentication cookie and then extract that data in the Application_AuthenticateRequest method in your Global.asax file and set the User property of the HttpContext there.
This answer contains more details and example code
I believe the issue is that you are just setting the user as authenticated, and therefore, the HttpContext is not updated yet since the auth cookie has not yet been set on the users side of the request.
I was struggling too.
I was trying to carryout my authentication and authorization inside a WCF service using standard ASP.Net Membership and Role providers.
I wanted to pass in credentials and a 'requested app' to determine if the user 'authenticated' for that app. (not the ASP.Net APP, but an app in my own database).
To do this, I wanted access to the roles, but didn't want to 'redirect' or have a second call to my WCF service.
Here is some code that works for me:
First I determine if the user is valid as follows:
if (Membership.ValidateUser(CompanyCn, CompanyPwd))
{
sbLogText.AppendFormat("\r\n\r\n\tValid User UID/PWD: '{0}'/'{1}'", CompanyCn, CompanyPwd);
FormsAuthentication.SetAuthCookie(CompanyCn, false);
}
Then the following code workes nicely for getting the list of roles:
List<string> roleList = new List<string>(Roles.GetRolesForUser(CompanyCn));
sbLogText.AppendFormat("\r\n\r\n\tUser ('{0}'): Roles ({1}):", CompanyCn, roleList.Count);
foreach (string s in roleList)
sbLogText.AppendFormat("\r\n\t\tRole: {0}", s);

Java Servlet session management, how to create session for login

I am working on a small webapp for fun, using just Java Servlets at the moment. I have two pages, test1 and test2. At the moment I am creating a new session in test1 like this:
HttpSession session = request.getSession(true);
if (session.isNew() == false) {
session.invalidate();
session = request.getSession (true);
}
In test2 I am retrieving the session like so:
HttpSession session = request.getSession(false);
if (session == null) {
throw new ServletException ("No session.");
}
So the problem is that if I go to test2 first, I am always getting a valid session because the browser creates one. I want to restrict the flow from test1 to test2 so that I have to go to test1 first. My plan is to eventually create a login page that will create the session, but the problem I am seeing here would still be present.
How should I handle this? I would like any ideas to not include 3rd party libraries. I'm doing this as a learning exercise.
Thanks!
This makes no sense. Forget the request.getSession(boolean). Just get the session by request.getSession() and never worry about the nullness/validness.
If you want to pass data through session attributes, then just do in test1:
request.getSession().setAttribute("test", "foo");
and in test2 (which is of course requested in the same session after test1):
String test = (String) request.getSession().getAttribute("test"); // Returns "foo".
As to using the session to check the logged-in User, just do something like in the login code:
User user = userDAO.find(username, password);
if (user != null) {
request.getSession().setAttribute("user", user);
} else {
// Show error?
}
and then in a Filter which is mapped on a url-pattern which represents the restricted area, just check if the User is present or not:
if (((HttpServletRequest) request).getSession().getAttribute("user") != null) {
chain.doFilter(request, response); // Just continue.
} else {
((HttpServletResponse) response).sendRedirect("login"); // Not logged-in, redirect to login page.
}
and when you logout, you just remove the User from the session:
request.getSession().removeAttribute("user");
// Or, more drastically:
request.getSession().invalidate();
Alternatively you can also take a look for declarative Container Managed Security with help of some simple entries in web.xml and the server.xml. This way you don't need to hassle with login/filter logic yourself.
See also:
How do servlets work? Instantiation, sessions, shared variables and multithreading
How to handle authentication/authorization with users in a database?
Authentication filter and servlet for login
If you want to restrict the flow to ensure that test1 comes before test2, have test1 put an attribute value in the session that says it's been visited, and test for that attribute value in test2. If the value is not there, have test2 redirect to test1.
In test1, do this:
HttpSession session = request.getSession();
session.setAttribute("test1",true);
Then, in test2, you can do this:
HttpSession session = request.getSession();
if (session.getAttribute("test1") == null){
response.sendRedirect("test1");
return;
}
A session is just a basket that starts out empty. The concept of whether a user is authenticated or not is separate from whether or not the user has a session.
Java EE and the servlet specifications handle all the login stuff for you, redirecting to login pages and so on. Read up on the built-in capabilities of Java EE. Maybe start here.
When someone login with right credentials set a secession with this
request.getSession().setAttribute("user", "user");
now, you can check in this session user already present or not with this
if (((HttpServletRequest) request).getSession().getAttribute("user") != null)
and you can delete the session at the time of logout
request.getSession().invalidate();
this work perfectly
NOTE:
import HttpServletRequest and pass request parameter like this
import javax.servlet.http.HttpServletRequest;
public home(HttpServletRequest request){}

Resources