session management using filters - java

I am working on session management using filters i have written method and using managedbean annotation i'm trying to send the validation success to filter .
#ManagedBean(name = "customer")
#SessionScoped
public class CustomerBean implements Serializable{
public String checkValidCustomer(){
FacesContext context = FacesContext.getCurrentInstance();
HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
HttpSession session = request.getSession(true);
Customer cust = new Customer();
cust.setUsername(getUsername());
cust.setPassword(getPassword());
String returnValue = customerBo.checkValidCustomer(cust);
if(returnValue == "success"){
session.setAttribute("customer", returnValue);
}
else
{
session.setAttribute("customer", null);
}
return returnValue;
and i'm getting succes in retunValue string so i tried to pass as value to managedBean annotation .and myfilter code is like.
#WebFilter("/faces/*")
public class LoginFilter implements Filter {
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
String cust = (String) req.getSession().getAttribute("customer");
if (cust != null && cust.equals("success")) {
chain.doFilter(request, response);
} else {
resp.sendRedirect(req.getContextPath() + "/faces/default.xhtml");
}
}
I'm getting null value for String cust and when i open the page for login it shows This webpage has a redirect loop.Can you please tell where i'm doing wrong..

try this...
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
System.out.println("Inside the filter.............." );
HttpSession session = request.getSession();
User u = null;
if(session.getAttribute("customer")!=null){
u = (User) session.getAttribute("customer");
}
if (u!= null)
{
System.out.println("user does exits.." + u.getUname() );// u can see who was logged here
chain.doFilter(req, resp);
}else{
System.out.println("user does exits..");
}

Related

doFilter with HttpServletRequest

I stuck up with doFilter of HttpServletRequest.
Im trying to replace new URL for that request.
My code is as follows:
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpReq = (HttpServletRequest) req;
HttpServletResponse httpRes = (HttpServletResponse) res;
//If request resources ==> Continue
if(httpReq.getContextPath().startsWith(httpReq.getContextPath()+"/resources")){
chain.doFilter(req, res);
return;
}
HttpSession session = httpReq.getSession();
EmployeeDTO currentEmployee =(EmployeeDTO)session.getAttribute("currentEmployee");
//If dont have session ==> Return login page
if(currentEmployee == null){
String requestURI = "";
requestURI = httpReq.getRequestURI().replace(httpReq.getRequestURI(), httpReq.getContextPath()+ "/login");
System.out.println(requestURI);
//httpRes.reset();
//httpRes.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
//httpRes.setHeader("Location", requestURI);
httpRes.sendRedirect(requestURI);
chain.doFilter(req, res);
return;
}
chain.doFilter(req, res);
return;
}
But the code above is still not working. How can i do for this?
Thanks in advance!
Why do you have to do a chain.doFilter() after setting a redirect response?
private FilterConfig filterConfig;
public void init(FilterConfig config) throws ServletException {
this.filterConfig = config;
}
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpReq = (HttpServletRequest) req;
HttpServletResponse httpRes = (HttpServletResponse) res;
HttpSession session = httpReq.getSession();
boolean requestResources = false;
//If request resources ==> Continue
if(httpReq.getContextPath().startsWith(httpReq.getContextPath()+"/resources")){
requestResources = true;
}
if(session != null){
EmployeeDTO currentEmployee =(EmployeeDTO)session.getAttribute("currentEmployee");
}
if(requestResources || currentEmployee != null){
chain.doFilter();
}else if(currentEmployee == null){
String loginURI = //hardcode the loginURI here.
httpRes.sendRedirect(loginURI);
/*alternatively use the following to do an internal forward rather than a redirect
RequestDispatcher rd = filterConfig.getServletContext().getRequestDispatcher(loginURI); //here the loginURI path should not have the context in the url.
rd.forward(servletReq, response);
*/
}
}
I have also refactored your code to remove the redundant and multiple 'return' statements

How to redirect jsp page after session expired?

<%
if(session == null) {
System.out.println("Expire");
response.sendRedirect("/login.jsp");
}else{
System.out.println("Not Expire");
}
%>
<%
HttpSession sess = request.getSession(false);
String email = sess.getAttribute("email").toString();
Connection conn = Database.getConnection();
Statement st = conn.createStatement();
String sql = "select * from login where email = '" + email + "' ";
ResultSet rs = st.executeQuery(sql);
%>
I tried to redirect the login.jsp page when session is expired.
But I am geeting error in "String email = sesss.getAttribute("email").toString();".
So anyone please help me to solve this error.
Basically I want to redirect to login.jsp page when the session is expired.
First of all. You are mixing JSP and Java code. You should separate it.
Keep Java code in controllers.
You can use:
if(request.getSession(false) == null) {
response.sendRedirect("/login.jsp");
}
"...If create is false and the request has no valid HttpSession, this method returns null."
For example create Authentication Filter
#WebServlet(
name = "AuthenticationFilter",
description = "Authentication Filter",
urlPatterns = "/AuthenticationFilter"
)
#WebFilter("*.jsp")
public class AuthenticationFilter implements Filter {
private ServletContext context;
#Override
public void init(FilterConfig filterConfig) throws ServletException {
this.context = filterConfig.getServletContext();
this.context.log("AuthenticationFilter initialized");
}
#Override
public void destroy() {
//close any resources here
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
String uri = req.getRequestURI();
this.context.log("Requested Resource::" + uri);
HttpSession session = req.getSession(false);
Object user_o = req.getSession().getAttribute("username");
this.context.log("Authentication Filter, user_name::" + user_o);
if (user_o == null && !(uri.endsWith("index.jsp") || uri.endsWith("LoginUser"))) {
this.context.log("None authenticatied request, session:: " + session);
res.sendRedirect("index.jsp");
} else {
this.context.log("Authenticatied request, session:: " + session);
chain.doFilter(request, response);
}
}
I tried this and its working fine for me.
<%
if(session.getAttribute("email") == null) {
response.sendRedirect("login.jsp");
return ;
}
%>
I just put return statement and It will redirect to "login.jsp" when the session is expired.

Restful api how to pass info after basic http auth

I am building a mobile app and Restful API, I want the user of the app to be able to do GET what ever resources he want without Authentication. But if he want to do POST he have to enter his username and pass.
I already made a HTTP basic Authentication by putting a filter in web.xml.
<filter>
<filter-name>AuthenticationFilter</filter-name>
<filter-class>org.service.RestAuthenticationFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>AuthenticationFilter</filter-name>
<url-pattern>/webapi/*</url-pattern>
</filter-mapping>
and there are the classes
public class AuthenticationService {
ClientsService s = new ClientsService();
public boolean authenticate(String authCredentials) {
if (null == authCredentials)
return false;
// header value format will be "Basic encodedstring" for Basic
// authentication. Example "Basic YWRtaW46YWRtaW4="
final String encodedUserPassword = authCredentials.replaceFirst("Basic"
+ " ", "");
String usernameAndPassword = null;
try {
byte[] decodedBytes = Base64.decode(
encodedUserPassword);
usernameAndPassword = new String(decodedBytes, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
final StringTokenizer tokenizer = new StringTokenizer(
usernameAndPassword, ":");
final String username = tokenizer.nextToken();
final String password = tokenizer.nextToken();
boolean authenticationStatus =s.auth(username, password);
return authenticationStatus;
}
}
and the filter
public class RestAuthenticationFilter implements javax.servlet.Filter {
public static final String AUTHENTICATION_HEADER = "Authorization";
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filter) throws IOException, ServletException {
if (request instanceof HttpServletRequest) {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
String authCredentials = httpServletRequest
.getHeader(AUTHENTICATION_HEADER);
// better injected
AuthenticationService authenticationService = new AuthenticationService();
boolean authenticationStatus = authenticationService
.authenticate(authCredentials);
if (authenticationStatus) {
filter.doFilter(request, response);
} else {
if (response instanceof HttpServletResponse) {
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
httpServletResponse
.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
}
}
}
#Override
public void destroy() {
}
#Override
public void init(FilterConfig arg0) throws ServletException {
}
}
what i need to know is : how to pass the username and password or maybe just the id of the client to the methods of Restful after the Authentication.
A solution different to my comment: you can look for the HTTP request method and then make a decision if you call a authentication method or not:
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filter) throws IOException, ServletException {
if (request instanceof HttpServletRequest) {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
String authCredentials = httpServletRequest
.getHeader(AUTHENTICATION_HEADER);
boolean authenticationStatus;
// check request method
if (((HttpServletRequest).request).getMethod().equals("GET")) {
authenticationStatus=true;
} else {
// better injected
AuthenticationService authenticationService =
new AuthenticationService();
authenticationStatus = authenticationService
.authenticate(authCredentials);
}
if (authenticationStatus) {
filter.doFilter(request, response);
} else {
if (response instanceof HttpServletResponse) {
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
httpServletResponse
.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
}
}
}
Update:
With JAX-RS a possible solution for obtaining more request information may look like this:
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
#GET
#Path("offers")
#Produces("application/xml")
public YourList getOffers(#Context HttpServletRequest request)
{
System.out.println("request to "+request.getRequestURI()+" , Auth: "+request.getHeader(AUTHENTICATION_HEADER));
// more stuff for obtaining data
}

Same session in different browser tabs in jsp-servlet [duplicate]

I've a filter used for the login. It performs a textual checking, on fields "Username" and "Password". If and only if the textual checking is correctly done the request goes to the Servlet. This latter performs the control that has to interact with the Database. Is this chain correct?
Preface: I gather you're using homegrown login instead of container managed login. For all ways, see How to handle authentication/authorization with users in a database?
The filter (the interceptor) shouldn't check the validity of the username/password combo. That's the responsibility of the servlet (the controller).
The filter should merely check if the user is logged-in or not (usually by just checking the presence of a session attribute) and then continue the request or block it by redirecting back to the login page.
#WebFilter("/*")
public class LoginFilter implements Filter {
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
HttpSession session = request.getSession(false);
String loginURI = request.getContextPath() + "/login";
boolean loggedIn = session != null && session.getAttribute("user") != null;
boolean loginRequest = request.getRequestURI().equals(loginURI);
if (loggedIn || loginRequest) {
chain.doFilter(request, response);
} else {
response.sendRedirect(loginURI);
}
}
// ...
}
The servlet should collect the submitted data, find the associated User in database and if found then store it as a session attribute and then redirect to the home page, else redisplay the form with validation errors.
#WebServlet("/login")
public class LoginServlet extends HttpServlet {
#EJB
private UserService userService;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
Map<String, String> messages = new HashMap<String, String>();
if (username == null || username.isEmpty()) {
messages.put("username", "Please enter username");
}
if (password == null || password.isEmpty()) {
messages.put("password", "Please enter password");
}
if (messages.isEmpty()) {
User user = userService.find(username, password);
if (user != null) {
request.getSession().setAttribute("user", user);
response.sendRedirect(request.getContextPath() + "/home");
return;
} else {
messages.put("login", "Unknown login, please try again");
}
}
request.setAttribute("messages", messages);
request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
}
}
See also:
Our servlet-filters wiki page
Our servlets wiki page

Java Servlets cant use session attribute in another servlet

I am trying to get my first servlets to work. I have found some similar problems and solutions to them, but it´s not excatly what I would like to do.
This is my login servlet:
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String username=request.getParameter("username");
String password=request.getParameter("password");
if(LoginValidator.validate(username, password)){
HttpSession session = request.getSession();
session.setAttribute("user", username);
session.setMaxInactiveInterval(30*60);
Cookie sessionCookie = new Cookie("sessionKuki", username);
sessionCookie.setMaxAge(30*60);
response.addCookie(sessionCookie);
RequestDispatcher rd=request.getRequestDispatcher("paste.jsp"); //INSTEAD of paste.jsp I would like to get session attribute called uri I set in filter. BUT I when I try to use get attribute, Eclipse says there is no attribute called URI.
rd.forward(request,response);
}
else{
out.print("Sorry username or password error");
RequestDispatcher rd=request.getRequestDispatcher("login.html");
rd.include(request,response);
}
out.close();
}
}
And there is filter that I use to redirect to login page, when user is not signed in:
public class SessionFilter implements Filter{
// private ServletContext context;
public void init(FilterConfig filterConfig) throws ServletException {
//this.context = filterConfig.getServletContext();
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
String uri = req.getRequestURI(); //THERE IS uri of the site from where the user gets redirected to login page
HttpSession session = req.getSession(false);
session.setAttribute("uri", uri); // HERE I TRY to set uri to session attribute. My intention is to use that uri in my login servlet
if(uri.endsWith(".css")) {
chain.doFilter(request, response);
return;
}
if(uri.endsWith(".js")) {
chain.doFilter(request, response);
return;
}
if(session == null && !(uri.endsWith("login.html") || uri.endsWith("login") || uri.endsWith("forgot.jsp") || uri.endsWith("signup.jsp"))){
res.sendRedirect("login.html");
System.out.print("redirecting to login");
}else{
chain.doFilter(request, response);
}
}
public void destroy() {
}
}
Is it even possible, what I am trying to do? How to do it? Is there a better way to do it? I dont want to mix html and script. My intention is that, when user comes to a pages, and trys to get access to somewhere, he is redirected to login page. And after he logs in, he should be redirected to the page he wanted to go at the beginning.
Not sure if this would work but please try doing your filter like this:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
String uri = req.getRequestURI();
HttpSession currentSession = req.getSession(false);
if(uri.endsWith(".css")) {
chain.doFilter(request, response);
return;
}
if(uri.endsWith(".js")) {
chain.doFilter(request, response);
return;
}
if(currentSession == null && !(uri.endsWith("login.html") || uri.endsWith("login") || uri.endsWith("forgot.jsp") || uri.endsWith("signup.jsp"))){
HttpSession newSession = req.getSession();
newSession.setAttribute("uri", uri);
res.sendRedirect("login.html");
System.out.print("redirecting to login");
}else{
chain.doFilter(request, response);
}
}
What i did was create a new session in the filter if the session is null.

Categories