Discuss / Java / 使用DelegatingFilterProxy实现AuthFilter

使用DelegatingFilterProxy实现AuthFilter

Topic source

净净一隅

#1 Created at ... [Delete] [Delete and Lock User]

感觉【web开发】使用fileter的那种不是更方便些,用@WebFilter注解

package com.filter;

import com.entity.User;

import com.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;

import javax.servlet.*;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

import java.net.URLDecoder;

import java.nio.charset.StandardCharsets;

import java.sql.SQLException;

import java.util.Base64;

import java.util.Map;

@Component

public class AuthFilter implements Filter {

    @Autowired

    UserService userService;

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)

            throws IOException, ServletException{

        HttpServletRequest req = (HttpServletRequest) request;

        HttpServletResponse resp=(HttpServletResponse) response;

        // 获取Authorization头:

        String authHeader = req.getHeader("Authorization");

        if (authHeader != null && authHeader.startsWith("Basic ")) {

//base64解码

            byte[] decode= Base64.getDecoder().decode(authHeader.substring(6).replaceAll(" ","+"));

//url解码

            authHeader=URLDecoder.decode(new String(decode),String.valueOf(StandardCharsets.UTF_8));

// 解码后提取email和password:

            String email = prefixFrom(authHeader);

            String password = suffixFrom(authHeader);

            // 登录:

            User user = null;

            Map<String,Object> model= null;

            try {

                user = userService.login(email, password);

                // 放入Session:

                req.getSession().setAttribute("user", user);

            } catch (SQLException e){

                e.printStackTrace();

                resp.sendRedirect("/signin");

                return;

            }catch (RuntimeException e){

                e.printStackTrace();

                resp.sendRedirect("/signin");

                return;

            }catch (Exception e){

                e.printStackTrace();

                resp.sendRedirect("/signin");

                return;

            }

        }

        // 继续处理请求:

        chain.doFilter(req, resp);

    }

    @Override

    public void destroy() {

    }

    public String prefixFrom(String str){

        String[] list=str.split(":");

        return list.length>=1?list[0]:null;

    }

    public String suffixFrom(String str){

        String[] list=str.split(":");

        return list.length>=2?list[list.length-1]:list[0];

    }

}


  • 1

Reply