Spring Security OAuth2客户端过滤器后如何添加验证

时间:2020-05-31 19:00:16

标签: spring-security spring-oauth2

我尝试开发一个Web应用程序(反应),该Web应用程序从rest api中获取数据。可以使用Google登录名登录用户。成功登录google之后,我想验证该用户是否位于db(存储我的用户的某些表)上。如果该用户不是我的用户,我想响应错误或路由其他页面。首先,我开始开发使用Srping安全性的服务器端oauth2-client。我添加了此过滤器

@Component
public class CustomAuthenticationFilter extends OncePerRequestFilter {
    private static final Logger logger = LoggerFactory.getLogger(CustomAuthenticationFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        logger.info("Custom authentication has been called");
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        logger.info("Authentication context : {}", authentication);

        if (!isInMyUserTable(authentication)) {
            SecurityContextHolder.clearContext();
            BasicAuthenticationEntryPoint entryPoint = new BasicAuthenticationEntryPoint();
            entryPoint.commence(request, response, new UsernameNotFoundException("You are not my user."));
            return;
        }

        filterChain.doFilter(request, response);
    }

    private boolean isInMyUserTable(Authentication authentication) {
        //validate that is user in my table
        return false;
    }
}

和配置

@EnableWebSecurity
public class HelloLoginSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    customAuthenticationFilter customAuthenticationFilter;
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/**").authorizeRequests()
                .antMatchers("/hello").permitAll()
                .anyRequest().authenticated()
                .and()
                .oauth2Login()
                .and()
                .addFilterAfter(customAuthenticationFilter, OAuth2LoginAuthenticationFilter.class);
    }
}

使用此过滤器,我可以阻止用户,但是我无法响应该错误。该页面停留在Google登录页面上。

这是验证使用oauth2登录的用户的正确方法吗? 如何响应错误或如何将用户路由到另一个页面? 我应该在客户端处理所有令牌吗? 通过此配置,将使用jsessionId。如果我想享受无状态的休息服务,该怎么办。

0 个答案:

没有答案