how can i prevent a user from directly accessing a pages if not authenticated?

*爱你&永不变心* 提交于 2021-01-28 06:56:23

问题


I am using custom tag and i want to know how can i prevent a user from directly accessing my application pages without authenticating. Below is the view page coding, please let me know how to go about it, I even tried using page session directive but that didnt work.

  <html>
  <head>
  <script>
      function check(submit)
      {
    var x = document.getElementById("r");
    var xlength=x.value.length;
    if(xlength!=5 || x=="")
  {
               alert("Enter 5 digit Employee Id");
               document.getElementById("r").focus();
return false;
 }
 }
 </script>  
  </head>
  <body>
  <form method=post>
  <input type=text style="color:grey" name=reqno id=r 

  value=requestno maxlength="5" onFocus="if 

  (this.value==this.defaultValue) this.value=''" onblur="if 

  (this.value=='') this.value = this.defaultValue" >
  </br>
  <input type = submit name = submit value = Submit 

   onclick="return check(this)" >
  <input type = submit name = back value = Back>

<%

  String r=request.getParameter("reqno");
  String btn=request.getParameter("submit");
  String btn1=request.getParameter("back");
  HttpSession session1=request.getSession();
  session1.setAttribute("requestno",r);
 if (btn!=null)
   response.sendRedirect("findrequest1.jsp");
 else if (btn1!=null)
   response.sendRedirect("selectaction.jsp");


%>
</form>
</body>
</html>

Here is the Login Page

<jsp:useBean id="theBean" class="pack.java.MyModel"/>
<jsp:setProperty name="theBean" property="name" param="userName"/>
<jsp:setProperty name="theBean" property="pass" param="userPass"/>
<%@ taglib uri="taglib1.tld" prefix="easy" %>
<html>
<head>
<script>
 history.forward();
</script>
</head>
<header>
<h4 align="right"><a href="projectregister.jsp">Register Now</a></br>
</h4>
</header>
 <form = "loginform" method="post">
<h1>Login please</h1>
Enter username : <input type = text  name = userName  >
</br>
Enter password : <input type = password  name = userPass  >
</br>
<input type = submit name = submit value = submit>
</br>
<%
String btn = request.getParameter("submit");
String uu= request.getParameter("userName");
String pp= request.getParameter("userPass");
HttpSession sessions=request.getSession();
String st=(String)request.getAttribute("user");

  if(request.getParameter("userName")!="" && request.getParameter("userPass")!="")
{
  if (btn!=null )
{

%>
<easy:myTag/>
<% 
}
}
%>
</form>
</body>
</html>

This is a filter

       package pack.java;
       import java.io.*;
       import javax.servlet.*;

       public class loginfilter implements Filter
     {
        String aa;
    public void destroy()
        {
        }

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
 {
    aa=request.getRequestURI();
    chain.doFilter(request, response);
 }

  public void init(FilterConfig fconfig) throws ServletException
 {
  }

}

This the Login (controller) page

   package pack.java;
   import pack.java.MyModel;
   import java.io.*;
   import java.lang.*;
   import javax.servlet.*;
   import javax.servlet.http.*;
   import javax.servlet.jsp.*;
   import javax.servlet.jsp.tagext.*;
   import java.sql.*;
    public class MyController extends TagSupport
 {

HttpServletRequest request;
HttpServletResponse response;
String msg="";
String empid="";
    public int doStartTag()throws JspException
{

 request=(HttpServletRequest)pageContext.getRequest();              
 response=(HttpServletResponse)pageContext.getResponse();
    return EVAL_PAGE;
 }  

    public void check()
 {

   HttpSession mysession=request.getSession();

    JspWriter out=pageContext.getOut();
    int f=0;
    try
  {
   Class.forName("oracle.jdbc.driver.OracleDriver");
  }
   catch(ClassNotFoundException ex)
  {
    msg=ex.getMessage();
  }
    try 
 {   
     Connection con;
     CallableStatement stmt;
     ResultSet rs;
     String aa=(String)MyModel.name.trim();
     String bb=(String)MyModel.pass.trim();

 if(!aa.matches(".*[%#^<>&;'\0-].*") && !bb.matches(".*[%#^<>&;'\0-].*"))
{

 con=    DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","gaurav","oracle");
    stmt=con.prepareCall("select usercheck1(?,?) from dual");
    stmt.setString(1,aa);
    stmt.setString(2,bb);       
    rs=stmt.executeQuery();

  while (rs.next())
 {
   empid=rs.getString (1);     
  mysession.setAttribute("user",empid);

  if(empid!=null)
 {
  response.sendRedirect("/Myjsp/selectaction.jsp");
 }
   else 
   out.println("Invalid Details");
 }
 }
  else
  out.println("Invalid Details");
}
 catch(SQLException ex)
 {
   msg=ex.getMessage();
 }         
  catch(Exception ex)
 {
  msg=ex.getMessage();
} 

} 
   public int doEndTag() throws JspException
{

    check();
   return EVAL_PAGE;
 }

}

In web.xml file below is the code i entered

<filter>
    <filter-name>loginfilter</filter-name>
    <filter-class>pack.java</filter-class>
 </filter>


 <filter-mapping>
    <filter-name>loginfilter</filter-name>  
    <url-pattern>/*</url-pattern>
 </filter-mapping> 

回答1:


You can use filters for handling such scenario.Filters are classes which are used to intercept request from a client before they access a resource at back end. You can also use filters the other way round i.e.intercept response before it reaches client. Here you can use former one.

Steps can be as below:

1.When user logs in successfully you can set some session attribute to indicate that user is logged in

 session.setAttribute("isUserLoggedIn",true);

2.You can write a class which implements javax.servlet.filter interface and override the doFilter method.In the doFilter method you can check whether "isUserLoggedIn" attribute is already set.If its already set ,you can allow the request to go ahead ,or else you can forward the user to login page or any custom page you want.

You can decide which URL patterns you want this filter to get invoked.If you want this filter to be invoked for each request i.e. for each URL pattern ,you can say soemthing like below in web.xml:

  <url-pattern>/*</url-pattern>

You can get idea of how filters work @

http://www.oracle.com/technetwork/java/filters-137243.html

Hope this helps!




回答2:


You can do this declaratively with security constraints in the deployment descriptor.

Essentially, you say 'this set of resources is only accessible by users in a given set of rules using a given set of HTTP methods', as follows:

Resources behind URLs /secured/* are only accessible to authenticated users in the 'admin' role.

<web-resource-collection>
  <web-resource-name>secured</web-resource-name>
  <description>Secured pages</description>
  <url-pattern>/secured/*</url-pattern>
  <http-method>POST</http-method>
  <http-method>GET</http-method>
</web-resource-collection>

<auth-constraint>
  <description>Administrative users</description>
  <role-name>admin</role-name>
</auth-constraint>

It requires some setup - security realms etc, login form configuration, but it means that your security setup is not done programmatically, instead it is in a tool-supported and abstracted, declarative way. This helps keep your code clean and focussed.

Also read this http://www.tutorialspoint.com/jsp/jsp_security.htm it will give you a good idea




回答3:


For JSP/HTML pages, there're many ways to prevent user from accessing directly. The simplest one is to move all those pages to WEB-INF folder where user can't access from the URL. It also means you only allow user to access servlet action and completely forbid user to access JSP pages. Go here for example.

For authentication you can use servlet filter or common servlet approaches which is discussed here



来源:https://stackoverflow.com/questions/22530073/how-can-i-prevent-a-user-from-directly-accessing-a-pages-if-not-authenticated

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!