在用户使用来自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;
}
}
答案 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);
}
}