How do I show a show home page if a user requests login page with a valid session using spring security?
if(session == null) {
// not valid
} else {
String username = (String) request.getParameter("username");
String age = (String) request.getParameter("age");
}
When you load the login page, check for a valid session. If a valid session exists, then you can redirect the page to your home page. Where as if there is no session, you can continue with display of login screen.
Related
I am testing a new functionality in my web app where i'm allowing the user to remain signed in even after the browing session expires. In order to achieve this, i have a "Keep me logged in" checkbox on my login page. Upon successful login, a cookie is created containing the userID and the login process continues normally. The first thing the first method in my main controller does is check for the presence of that cookie, read the userId in it, set the User object in the session correctly and bypass the login process, going directly to the home page. When the user signs out, the cookie is recreated with an expiration of 0 which means it's automatically deleted.
My Spring sessions last 30 minutes currently. I have successfully tested everything but i'm trying to replicate the Spring session expiring, which gets rid of the User object in memory and would normally force the user to login. In order to replicate it, i am deleting the JSESSIONID cookie from Chrome. When i do that, the HttpServletRequest object (which I am checking cookies on) is null.
Here is the first code that runs in my main controller :
#RequestMapping(value = {"/"}, method = RequestMethod.GET)
public String home(ModelMap model, HttpServletRequest request)
{
if (session.getAttribute("loggedInUser") != null)
{
return "home";
}
else
{
String userId = null;
for (Cookie cookie : request.getCookies())
{
if (cookie.getName().compareTo("MDHISStaySignedIn") == 0)
{
userId = cookie.getValue();
break;
}
}
if (userId != null)
{
session.setAttribute("loggedInUser", userService.findByUserId(userId));
return "redirect:/";
}
else
{
model.addAttribute("login", new Login());
model.addAttribute("register", new Register());
model.addAttribute("registering", false);
return "login";
}
}
}
Is it normal that my request object is null when deleting this cookie? Am i not correctly replicating the Spring session timing out by deleting it? This NullPointerException only happens when deleting this cookie and upon first running the web app, the controller does not thrown the exception when the cookie is created by the first run. Should i somehow be checking for this null value and redirecting the controller back to this method if it is?
Thanks!
The solution is to add the following method parameter :
#CookieValue(value = "MDHISStaySignedIn", defaultValue = "notFound") String cookie
This will assign the content of the cookie to the value if it's present and assign "notFound" if it is not. This way one can access cookies when the request object is null!
what I'm trying to do is relative simple
In my webapp there are these two servlets:
(I will write some pseudocode)
servlet A code: :
HttpSession sess = req.getSession();
String str = (String) sess.getAttribute("log");
if(str == null)
{
// send html page with a form
// to enter password and name
// data will be proceessed by servlet B
}
else
{
// send html page with a form
// to enter only a name
//data will be proceessed by servlet B
}
servlet B code: :
HttpSession sess = req.getSession();
String logged = (String) sess.getAttribute("log");
if(logged == null)
{
//check if password correct
if(correct)
{
sess.setAttribute("log","ok");
// print name
// and tell the user
// that next time password
// will not be requested
}
else
{
// print error message
}
}
else
{
// print name
}
for some reason the second time the servlet A is called after that the user filled in password and name correctly
str is null so the if part gets printed.
EDIT:
I discovered that if the user after inserting the password and
being redirected to servletB writes the url of servletA by himself
all goes right , but it odesn't work when the user gets back to the previous
page using a link created by servletA:
A HREF=\"http://localhost:8080/Blog/ServletA\" back
again , any suggestions why this happens?
I believe its not entering in your if(correct) block i.e. correct condition is not getting satisfied. Correct the condition there and make sure, it sets the log attribute in the session. Once a attribute is set into the session, its there until session expires or your remove it.
I am trying to make a simple login page to deal with database using JSP, servlet with MVC concept and Data Access Object(DAO) and I am new in this. My problem now that I need to alert a box message in servlet if the user enters invalid name and password and sendRedirect to login.jsp page again. I set flag to be 1 if the user valid then do this if-check
if(validUserFlage == 1)
response.sendRedirect("User_Manipulation_Interface.jsp");
else {
//Here i want to alert message cause user invalid ??
response.sendRedirect("Admin_And_User_Login_Form.jsp");
}
searching for this i find this answer but i can`t understand how can i do it
the answer i found:
(( With send redirect you cant display the message where you want in the code. So as per me there might be two approaches. Display a message here and use include of requestdispatcher instead of send redirect or else pass some message to admin.jsp and display the message there. ))
Set a flag parameter like this,
response.sendRedirect("Admin_And_User_Login_Form.jsp?invalid=true");
on jsp
<c:if test=${invalid eq 'true'}">invalid credentials</c:if>
You can set the Parameters like errormsg in the servlet page and add it to the ri-direct object. Then you can check that variable errormsg and if it is null then the username is correct else the username is incorrect..
In Servlet Code:
if(username.equal(databaseusername))
{
RequestDispatcher rd = request.getRequestDispatcher("NextPage.jsp");
req.setAttribute("errormsg", "");
rd.forward(request, response);
}
else
{
RequestDispatcher rd = request.getRequestDispatcher("login.jsp");
req.setAttribute("errormsg", "Wrong Username or Password");
rd.forward(request, response);
}
In JSP code:
<%
String msg=req.getAttribute("errormsg").toString();
if(!msg.equals(""))
{
// Print here the value of Msg.
}
%>
In servlet
String strExpired = (String) session.getAttribute("Login_Expired");
response.sendRedirect("jsp/page.jsp");
In jsp
<%
String strExpired = (String) session.getAttribute("Login_Expired");
out.print("alert('Password expired, please update your password..');");
%>
If my user is redirected to a login page, how to make it so that, after they log in, they get redirected to the -original- destination page (the one they first clicked on)?
Pass the originally requested URL as request parameter on the redirect to the login page.
String from = request.getRequestURI();
if (request.getQueryString() != null) {
from += "?" + request.getQueryString();
}
response.sendRedirect("login.jsp?from=" + URLEncoder.encode(from, "UTF-8"));
In login.jsp, pass it to the login form submit target as a hidden input field.
<input type="hidden" name="from" value="${fn:escapeXml(param.from)}" />
(note: fn:escapeXml() prevents you from XSS when redisplaying user-controlled data in HTML)
In the login action, check if it is there and then handle accordingly.
String from = request.getParameter("from");
if (from != null && !from.isEmpty()) {
response.sendRedirect(from);
} else {
response.sendRedirect("home.jsp");
}
I’m building a J2EE web application which uses Oracle SSO with an OID back-end as the means for authenticating users.
If a user wants to use the application, first he must provide a valid login/password at SSO's login page.
When the user is done using the application, he may click on the logout button; behind the scenes, the action associated with this button invalidates the user’s session and clears up the cookies using the following Java code:
private void clearCookies(HttpServletResponse res, HttpServletRequest req) {
res.setContentType("text/html");
for (Cookie cookie : req.getCookies()) {
cookie.setMaxAge(0);
cookie.setPath("/");
cookie.setDomain(req.getHeader("host"));
res.addCookie(cookie);
}
}
Also, I have an onclick JavaScript event associated with the logout button, which is supposed to delete the SSO cookies by calling the delOblixCookie() function (as found in some Oracle forum):
function delCookie(name, path, domain) {
var today = new Date();
// minus 2 days
var deleteDate = new Date(today.getTime() - 48 * 60 * 60 * 1000);
var cookie = name + "="
+ ((path == null) ? "" : "; path=" + path)
+ ((domain == null) ? "" : "; domain=" + domain)
+ "; expires=" + deleteDate;
document.cookie = cookie;
}
function delOblixCookie() {
// set focus to ok button
var isNetscape = (document.layers);
if (isNetscape == false || navigator.appVersion.charAt(0) >= 5) {
for (var i=0; i<document.links.length; i++) {
if (document.links.href == "javascript:top.close()") {
document.links.focus();
break;
}
}
}
delCookie('ObTEMC', '/');
delCookie('ObSSOCookie', '/');
// in case cookieDomain is configured delete same cookie to all subdomains
var subdomain;
var domain = new String(document.domain);
var index = domain.indexOf(".");
while (index > 0) {
subdomain = domain.substring(index, domain.length);
if (subdomain.indexOf(".", 1) > 0) {
delCookie('ObTEMC', '/', subdomain);
delCookie('ObSSOCookie', '/', subdomain);
}
domain = subdomain;
index = domain.indexOf(".", 1);
}
}
However, my users are not getting logged out from SSO after they hit the logout button: although a new session is created if they try to access the index page, the SSO login page is not presented to them and they can go straight to the main page without having to authenticate. Only if they manually delete the cookies from the browser, the login page shows up again - not what I need: the users must provide their login/password every time they log out from the application, so I believe there must be something wrong in the code that deletes the cookies.
I’d greatly appreciate any help with this problem, thanks in advance.
Oracle have two web SSO products - Oracle Access Manager and Oracle Single Sign On. The Javascript code you have posted is for Access Manager, so it won't help you. Besides, you shouldn't need to do anything in Javascript to log the user out.
Have a look at the logout section of the OSSO docs. It recommends using the following code:
// Clear application session, if any
String l_return_url := return url to your application
response.setHeader( "Osso-Return-Url", l_return_url);
response.sendError( 470, "Oracle SSO" );
You need a page, with a name of logout, that includes those JavaScript functions.
That's what the documentation says:
The WebGate logs a user out when it receives a URL containing
"logout." (including the "."), with the exceptions of logout.gif and
logout.jpg, for example, logout.html or logout.pl. When the WebGate
receives a URL with this string, the value of the ObSSOCookie is set
to "logout.
Cookies don't "delete" untill the browser is closed.