如何在Spring MVC应用程序中拦截访问令牌?

时间:2019-07-07 06:58:11

标签: spring spring-mvc spring-security single-sign-on spring-oauth2

在用户使用来自OAuth2提供程序的单点登录进行身份验证后,我想从Spring MVC Web应用程序的每个请求中拦截访问令牌。我的演示应用程序代码当前如下所示:

application.yml:

security:
  oauth2:
    client:
      clientId: metlife_monitor
      clientSecret: password
      accessTokenUri: http://localhost:8668/sso-server/oauth/token
      userAuthorizationUri: http://localhost:8668/sso-server/oauth/authorize
      tokenName: oauth_token
    resource:
      userInfoUri: http://localhost:8688/api/me

SpringBoot Application.java:

@SpringBootApplication
@EnableOAuth2Sso
@EnableJdbcHttpSession
public class App1Application  extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .antMatcher("/**")
                .authorizeRequests()
                .antMatchers("/", "/login**", "/login2**", "/error**", "/webjars/**").permitAll()
                .anyRequest().authenticated()
                .and().logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("http://localhost:8668/sso-server/logout")
                .invalidateHttpSession(true)
                .deleteCookies("client-session", "JSESSIONID")
                .permitAll()
                .and().csrf().disable()
        ;

    }
    public static void main(String[] args) {
        SpringApplication.run(App1Application.class, args);
    }

}

DashboardController.java:

@Controller
public class DashboardController {
    @GetMapping("/")
    public ModelAndView home() {
        ModelAndView modelAndView = new ModelAndView("index");
        return modelAndView;
    }

    @GetMapping("/protected")
    public ModelAndView protectedView() {
        ModelAndView modelAndView = new ModelAndView("protected");
        return modelAndView;
    }
}

1 个答案:

答案 0 :(得分:0)

注册OncePerRequestFilter,然后在doFilterInternal方法上从请求中提取令牌。

@Component
public class TokenInterceptorFilter extends OncePerRequestFilter {

  @Autowired
  private AuthenticationStorage storage;

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

    // Extract the token from the request

    filterChain.doFilter(request, response);
  }

}