当前位置:网站首页>Login authentication filter

Login authentication filter

2022-06-12 05:48:00 Fairy-KunKun

In a JavaWeb In the project , For some special resources , Login is required to use

【 Settlement 】、【 download 】、【 Comment on 】

For functions like these , You need to log in first , And then you can use it

First check whether you are logged in

If you are not logged in , These resources cannot be used

Force login

otherwise : have access to

Previous practice : Such as home.jsp resources , You need to verify whether you are logged in

A unified extraction jsp,checkLogin.jsp, You need to control whether users log in jsp Use in <include> Tags introduced

/page/mymood/delete.do

                         |  Servlet resources    checkLogin.jsp It's not common anymore .

/page/mymood/publish.do

wait , There are many resources in the system that need access control

.jsp

     -----》 resources Unification   Cannot distinguish between suffixes

.do

.css

(1) Design a configuration file , It is used to configure the resources that need login control

urls=/page/user/home.jsp,/page/mymood/delete.do,/page/mymood/update.do

(2) Read authority file

package com.njwbhz.mood.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
 *
Read login authentication file
 
*/
public class AuthorityUtil {
  
private static List < String > urls = new ArrayList < String > ( );
  
public static List < String > load ( ) {
      BufferedReader reader =
null;
      reader =
new BufferedReader (
           
new InputStreamReader (
                  AuthorityUtil
                        .
class
                       
.getClassLoader ( )
                        .getResourceAsStream (
"authority" )
            )
      );
      
try {
         String lineData = reader.readLine ( );
         String[] resources = lineData.split (
"=" )[ 1 ].split ( "," );
        
urls = Arrays.asList ( resources );
      }
catch ( IOException e ) {
         e.printStackTrace ( );
      }
finally {
        
if ( null != reader ) {
           
try {
               reader.close ( );
            }
catch ( IOException e ) {
               e.printStackTrace ( );
            }
         }
      }
     
return urls;
   }
}

(3) Testing tools

package com.njwbhz.mood;
import com.njwbhz.mood.util.AuthorityUtil;
import org.junit.Test;
import java.util.List;
public class TestAuthority {
  
@Test
  
public void load ( ) {
      List < String > urls =
            AuthorityUtil.load ( );
      urls.forEach ( System.
out :: println );
   }
}

(4) Define filters

package com.njwbhz.mood.filter;
import com.njwbhz.mood.entity.User;
import com.njwbhz.mood.util.AuthorityUtil;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
/**
 *
Login validation filter
 
*/
public class AuthorityFilter implements Filter {
  
private List < String > urls;
  
  
@Override
  
public void init ( FilterConfig filterConfig ) throws ServletException {
     
// Load the file
     
urls = AuthorityUtil.load ( );
   }
  
  
@Override
  
public void doFilter ( ServletRequest servletRequest , ServletResponse servletResponse , FilterChain filterChain ) throws IOException, ServletException {
     
// Every request can be AuthorityFilter Intercept
     
// The request is within the scope of validation ?
     
// First get the current URL What is it? ?
     
HttpServletRequest request = ( HttpServletRequest ) servletRequest;
      HttpServletResponse response = ( HttpServletResponse ) servletResponse;
     
// Such as the current URLhttp://127.0.0.1:8080/mood/page/user/login.do?xxxx
     
String currentUri = request.getRequestURI ( );// /mood/page/user/login.do?xxxx
     
String contextPath = request.getContextPath ( );
      String currentURL = currentUri.substring ( contextPath.length ( ) );
// /page/user/login.do?xxxx
     
if ( currentURL.contains ( "?" ) ) {
         currentURL = currentURL.substring (
0 , currentURL.lastIndexOf ( "?" ) );
      }
     
// If in , Judge session
     
if ( urls.contains ( currentURL ) ) {
         User user = ( User ) request.getSession ( ).getAttribute (
"user" );
        
if ( null != user ) { // It's already logged in
           
// release
           
filterChain.doFilter ( request , response );
         }
else {
           
// The login page
           
String path = request.getContextPath ( );
            String basePath = request.getScheme ( )
                                +
"://" + request.getServerName ( )
                                +
":" + request.getServerPort ( )
                                + path +
"/";
            String loginUrl = basePath +
"page/user/login.jsp";
            response.setContentType (
"text/html;charset=UTF-8" );
            PrintWriter writer = response.getWriter ( );
            writer.write (
"<script type=\"text/javascript\">" );
            writer.write (
"alert(\" Not signed in yet , Please log in first !\");" );
            writer.write (
"window.top.location.href='" );
            writer.write ( loginUrl );
            writer.write (
"';" );
            writer.write (
"</script>" );
            writer.flush ( );
            writer.close ( );
         }
      }
else { // If not , Direct release
        
filterChain.doFilter ( request , response );
      }
   }
  
@Override
  
public void destroy ( ) {
     
   }
}

(5) To configure

<filter >
   <filter-name >authorityFilter</filter-name>
   <filter-class >com.njwbhz.mood.filter.AuthorityFilter</filter-class>
</filter>
<filter-mapping >
   <filter-name >authorityFilter</filter-name>
   <url-pattern >/*</url-pattern>
</filter-mapping>

(6)home.jsp

(7) test

原网站

版权声明
本文为[Fairy-KunKun]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/163/202206120537177646.html