Spring Security 自定义LoginUrlAuthenticationEntryPoint 对OAuth接口不进行JWT验证

1,522 阅读1分钟

WebSecurityConfigurerAdapter中,需要配置authenticationEntryPoint。 如果不指定自定义authenticationEntryPoint,则默认调用LoginUrlAuthenticationEntryPoint。

public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
	// 自定义authentication验证,判断oauth或是普通接口
    @Bean
    public MyAuthenticationEntryPoint myAuthenticationEntryPoint() {
        return new MyAuthenticationEntryPoint("/login");
    }
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
    			...
                http.formLogin()
                // 关闭跨站请求防护
                ...
                // 配置ExceptionHandler
                .exceptionHandling()
                // 自定义无权限访问异常处理
                .accessDeniedHandler(myAccessDeniedHandler)
                // 自定义未登录访问异常处理
                .authenticationEntryPoint(myAuthenticationEntryPoint)
                // 添加JWT filter验证JWT
                .and()
                .addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
                ...
        }
    }

继承LoginUrlAuthenticationEntryPoint,修改commence接口,判断request的URI。若是OAuth接口,则跳转至登录界面,若是其他接口,则返回401。

public class MyAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint {
    /**
     * @param loginFormUrl URL where the login page can be found. Should either be
     *                     relative to the web-app context path (include a leading {@code /}) or an absolute
     *                     URL.
     */
    public MyAuthenticationEntryPoint(String loginFormUrl) {
        super(loginFormUrl);
    }

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        System.out.println(request.getRequestURI());
        if (request.getRequestURI().contains("/oauth/")) {
            super.commence(request, response, authException);
        } else {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            // 返回JSONResponse
            response.getWriter().println(JSONUtil.parse(JSONResponse.unauthorized("无Token或Token失效!请重新登录!")));
            response.getWriter().flush();
        }
    }