小编mna*_*dev的帖子

如何处理 Spring Security 中过滤器抛出的自定义异常

我是 Spring Security 的新手。

我有一段代码,用于检查请求中是否传递了授权标头,如果缺少,则抛出异常。

public class TokenAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    private static final String BEARER = "Bearer";

    public TokenAuthenticationFilter(RequestMatcher requiresAuthenticationRequestMatcher) {
        super(requiresAuthenticationRequestMatcher);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException, IOException, ServletException {
        String username = request.getParameter("username");
        String authorization = request.getHeader("AUTHORIZATION");

        if (!request.getRequestURI().equals(UniversalConstants.LOGIN_PATH)) {
            if (authorization == null || authorization.length() == 0 || !authorization.startsWith(BEARER)) {
                throw new InvalidCredentialsException("Missing authentication token"); //<-----------------
            }

        }

        String password = request.getParameter("password");
        return getAuthenticationManager().authenticate(new UsernamePasswordAuthenticationToken(username, password));
    }
Run Code Online (Sandbox Code Playgroud)

我的目标是在全球范围内处理所有异常,因此我使用@ControllerAdvice。

注意:我知道 @ControllerAdvice 不适用于从 …

spring exception spring-security spring-boot

3
推荐指数
1
解决办法
6463
查看次数

标签 统计

exception ×1

spring ×1

spring-boot ×1

spring-security ×1