/* * This method is called by the filter chain to filter the request. * 所有的请求都会经过这个方法,我们可以在这里进行token的解析和用户的认证 */ @Override protectedvoiddoFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { Stringtoken= getTokenFromRequest(request); logger.info("Token: " + token);
/* * This method is used to extract the token from the request. * 从请求中提取token */ private String getTokenFromRequest(HttpServletRequest request) { StringbearerToken= request.getHeader("Authorization"); if (bearerToken != null && bearerToken.startsWith("Bearer ")) { return bearerToken.substring(7); } returnnull; }
/* * This method is used to create an authentication object. * 创建一个认证对象 */ private UsernamePasswordAuthenticationToken getAuthentication(Map<String, Object> claims) { // Implement token parsing and authentication creation logic returnnewUsernamePasswordAuthenticationToken(claims, null, newArrayList<>()); } }
Web配置
将过滤器注册到Spring容器中。
跨域配置。
publicclassSecurityConfig {
/** * Configures the security filter chain that carries out authentication and authorization. * @param http the HttpSecurity object to configure * @return the SecurityFilterChain object * @throws Exception if an error occurs during configuration */ @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http)throws Exception { http .csrf(AbstractHttpConfigurer::disable) .authorizeHttpRequests(auth -> auth .requestMatchers("/api/user/login").permitAll() .anyRequest().authenticated() ) .cors(cors -> cors.configurationSource(corsConfigurationSource())) .addFilterBefore(newJwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); return http.build(); }