S SmartDocs
Chuỗi bài: Java java 56 dòng · Cập nhật 2026-04-09

JwtAuthenticationFilter.java

Java/Baasid/src/main/java/com/baasid/security/JwtAuthenticationFilter.java

package com.baasid.security;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.lang.NonNull;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * 每個 HTTP 請求最多執行一次的 Servlet Filter:從 {@code Authorization} 標頭解析 JWT,
 * 驗證成功後將使用者身分寫入 {@link org.springframework.security.core.context.SecurityContext},
 * 供後續 {@link org.springframework.security.web.SecurityFilterChain} 與 Controller 使用。
 * <p>
 * {@link UsernamePasswordAuthenticationToken} 的 principal 設為使用者 {@link UUID}(與 {@link com.baasid.controller.GoodsController} 一致)。
 */
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final JwtUtil jwtUtil;

    public JwtAuthenticationFilter(JwtUtil jwtUtil) {
        this.jwtUtil = jwtUtil;
    }

    @Override
    protected void doFilterInternal(@NonNull HttpServletRequest request,
                                    @NonNull HttpServletResponse response,
                                    @NonNull FilterChain filterChain) throws ServletException, IOException {

        String header = request.getHeader("Authorization");

        if (header != null && header.startsWith("Bearer ")) {
            String token = header.substring(7); // "Bearer ".length()

            if (jwtUtil.isValid(token)) {
                UUID userId = jwtUtil.getUserId(token);
                String account = jwtUtil.getAccount(token);

                var authentication = new UsernamePasswordAuthenticationToken(
                        userId, account, List.of() // 此專案未使用角色 / 權限,傳空列表
                );
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }

        filterChain.doFilter(request, response);
    }
}

Bài viết liên quan