Hi i have an application that uses its own implementation for user to authenticate ,by saving a User pojo in the HttpSession and invalidating that HttpSession Object when the session is done, but what i want to do is to use the security context to authenticate the user.
let's say that i have servlet AuthenticateUserServlet:
public void doPost(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,IOException{
String username=req.getParameter("username");
String password=req.getParameter("password");
if(Authenticator.check(username,password)){
HttpSession session=req.getSession(true);
session.setAttribute("user",Authenticator.getUser(username));
PrintWriter out= req.getWriter();
out.println("<h2>Welcome</h2>");
}else{
PrintWriter out= req.getWriter();
out.println("<h2>the password or username are incorrect</h2>");
}
}
the code above won't give me the power of security context so what i wan't is when i check that the user is ok to login tell in someway the security context that this user can access here are his roles
something like this inside my AuthenticateUserServlet:
public void doPost(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,IOException{
String username=req.getParameter("username");
String password=req.getParameter("password");
LoginContext lc = new LoginContext("my-jaas",new MyCallbackHandler(username,password));
try{
lc.login();
//notice i have not save any thing in the HTTPSeession
//i want my container to remember this user like what happens in the
// form based authentication where nothing gets saved in the httpSession
// but the user keeps logged in(cartalina uses a session object not httpsession for that)
PrintWriter out= req.getWriter();
out.println("<h2>Welcome</h2>");
}
catch(LoginException e ){
PrintWriter out= req.getWriter();
out.println(e.getMessage());
}
}
i have created my own LoginModule ("my-jaas") and it works fine when i configure Form-Based authentication to work with it in tomcat7.
With Servlet 3.0, there is a login method in HttpServletRequest (https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#login(java.lang.String,%20java.lang.String)) so you can login like
public void doPost(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,IOException{
String username=req.getParameter("username");
String password=req.getParameter("password");
try{
req.login(username, password);
PrintWriter out= req.getWriter();
out.println("<h2>Welcome</h2>");
} catch(ServletException e ){
PrintWriter out= req.getWriter();
out.println(e.getMessage());
}
}
Related
I have project maven web-application. I have a few JSP files with HTML code and JSP tags. I have a connection in the local database and a few servlets.
Problem is that when I logged in to the app, I want to print a welcome message for the logged user.
This is the tag which should display a welcome message:
<div class="hello-text"><h1>Hello <span>${sessionScope.user_name}</span>. This is yours stats:</h1></div>
When I logged in the only text that I have is "Hello ${sessionScope.user_name}. This is your stats:
This is my servlet code for logging in:
#WebServlet("/login")
public class UserLoginServlet extends HttpServlet {
private static final long serialVersionUID = 2717450811223035557L;
private UserRepository userRepository = new UserRepositoryBean();
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
String login = req.getParameter("login");
String password = req.getParameter("password");
PrintWriter writer = resp.getWriter();
if (login == null | login.isEmpty() | password == null | password.isEmpty()) {
writer.write("ERROR");
return;
} else {
if (userRepository.validateUser(login, password)) {
HttpSession session = req.getSession();
session.setAttribute("user_name", login);
resp.sendRedirect("profile.jsp");
} else {
req.setAttribute("error", "Invalid login or password. Try again.");
req.getRequestDispatcher("login.jsp").forward(req, resp);
}
}
writer.close();
}
}
Why I don't have a message, for example, Hello Admin. This is your stats:?
I always have Hello ${sessionScope.user_name}. This is your stats:...
A sendRedirect should not be mixed by other output of some page.
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String login = req.getParameter("login");
String password = req.getParameter("password");
if (login.isEmpty() || password.isEmpty()) {
resp.setContentType("text/html");
PrintWriter writer = resp.getWriter();
writer.write("ERROR");
return;
}
if (userRepository.validateUser(login, password)) {
HttpSession session = req.getSession();
session.setAttribute("user_name", login);
resp.sendRedirect("profile.jsp");
} else {
req.setAttribute("error", "Invalid login or password. Try again.");
req.getRequestDispatcher("login.jsp").forward(req, resp);
}
}
The first if could be done by the validation - as empty input happens often - by a nice error message reposted to the same form with already done input saved.
If the JSP comes as HTML, then ensure it has a valid servlet mapping.
Also the JSP better should not be placed in a public directory, but maybe under WEB-INF/jsps/ or such.
I am unable to close my session using session.invalidate() in my logout method please help!
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
response.getWriter().println("<h3><a href='/assign2'>Logged out Successfully</a></h3>");
HttpSession session = request.getSession(false);
if(session!=null)
session.invalidate();
}
the username does not get written to null at all
here's my welcome page to where i am redirecting it
HttpSession session=request.getSession(false);
if(session!=null)
{
if((request.getSession().getServletContext().getAttribute("userid")) != null)
{
username = request.getSession().getServletContext().getAttribute("userid").toString();
}
}
System.out.println(username);
The logoff page is OK, but in the welcome page you are mixing concepts:
Altough the execution of session.invalidate does unbind all the bound attributes, you are retrieving attribute userid from the ServletContext, not the Session. Besides, note that request.getSession() creates a new session if necessary.
The coherent way to store and retrieve attributes would be through the HttpSession object:
HttpSession session=request.getSession(false);
if(session!=null)
{
if((session.getAttribute("userid")) != null)
{
username = session.getAttribute("userid").toString();
}
}
System.out.println(username);
//inboxservlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name=request.getParameter("uname");
PrintWriter out=response.getWriter();
out.println("welcome "+name);
out.println("<a href='SentItems?uname="+name+" '>sent items</a>");
out.println("<a href=''>Logout</a>");
}
If i click logout it redirects to login page.Help me with this
Try like this
Proper way to logout is below way:
out.println("Logout")
You have to create a servlet to call logout properly:
public class LogoutServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
request.getRequestDispatcher("loginPage.jsp").include(request, response);
HttpSession session=request.getSession();
session.invalidate();
out.print("You are successfully logged out!");
out.close();
}
}
out.println("<a href=''>Logout</a>");
I believe your javascript code must be binding the event during page load time. See related javascript code.
I am having a problem with a relativly easy thing. I am trying to do a simple program, where you can log in and log out using the session.
The session is created, but I am always getting forwarded to panel servlet and then to NoCorrectSession page. As if on login page the server saw isActive attribute, and then on panel page had not.
//class Login extends HttpServlet
private RequestDispatcher pageLogin, pagePanel, pageError; //defined in init()
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
String name = request.getParameter("name");
String isBeingRequested = request.getParameter("isBeingRequested");
if (session.getAttribute("isActive") != null) {
//user has been logged in before, redirect him
pagePanel.forward(request, response);
} else if (isBeingRequested != null) {
//user has entered data into the login page and submitted it
if (name.length() == 0) {
//user has not stated his name
pageError.forward(request, response);
} else {
//otherwise access is granted and account created
session.setAttribute("isActive", "yes"); //setting session to active
pagePanel.forward(request, response);
}
} else {
//neither of these? user just entered the login screen
pageLogin.forward(request, response);
}
}
//class Panel extends HttpServlet {
private RequestDispatcher pageNoCorrectSession;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
//session has expired or never was started
if (session.getAttribute("isActive") == null) {
pageNoCorrectSession.forward(request, response);
//session valid
} else {
//logged in - do stuff
}
After digging in the project it turned out I've not made a mistake in these servlets, but in HTML code causing submitting a form directly to the panel servlet (and not creating the account object in the process). I know it is silly, but it was a great lesson. Expect the unexpected :P
I do check in with a servlet, it works.
How validation of form filling?
For example, re-send the user to .jsp-file, if a username is already registered?
Sorry for bad english.
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// fetch the username that was sent in the request
String username = request.getParameter("username");
// TODO: verify if the username is taken in the database
// based on the results set the value
request.setAttribute("isUsernameTaken", "true");
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/register.jsp");
dispatcher.forward(request, response);
}