这是我想要做的:使用 Google OAuth2(授权代码流)对 http://localhost:8080/token 的 GET 请求进行身份验证。如果经过身份验证,则会返回自定义 JWT 令牌作为响应。
所有其他 url(例如 /hello1、/hello2、hello3 等)都使用 Authorization 标头中存在的 JWT 令牌进行身份验证。这与 /token 端点给出的令牌相同。
我能够让这两种身份验证机制分别工作,但是当我使用以下配置将它们结合起来时它不起作用。
我有两个 WebSecurityConfigs 如下:
@Configuration
@EnableWebSecurity
public class WebSecurityInfoOAuth2 extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.requestMatchers().antMatchers("/token", "/oauth/**", "/oauth2/**")
.and()
.authorizeRequests()
.antMatchers("/oauth/**", "/oauth2/**").permitAll()
.anyRequest().authenticated()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.oauth2Login()
.userInfoEndpoint()
.userService(oauthUserService)
.and()
.successHandler(new AuthenticationSuccessHandler() {
...NOT SHOWN...
});
}
}
和
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityInfoJWT extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf().disable()
.requestMatchers().antMatchers("/hello1", "/hello2", "/hello3")
.and()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}
}
现在,/token 端点工作正常。它返回一个令牌。
但这是我看到的两个问题:
它会将我重定向到所有 URL 的 OAuth2 社交登录(即使是配置中不存在的 URL),尽管我希望它只对 /token 这样做
即使存在 Authorization 标头,对 /hello1 的请求也会重定向到社交登录。我在 jwtRequestFilter 中设置了一个断点,但控件甚至没有到那里。
如何确保 WebSecurityInfoJWT 配置用于 /hello1 ?