支持Spring Authorization Server(0.2.3+)中的并发全栈MVC(会话)身份验证以及无状态J



创建授权服务器时,我有一个相对简单的AS。它支持:

  • 用户注册(WebMVC(
  • 表单登录(WebMVC(
  • 忘记密码(WebMVC(
  • 管理RegisteredClient(WebMVC(-一个某人可以管理其API客户端的地方,这些客户端交换访问令牌以访问其他资源服务器

我还有一些API@RestController端点;然而,我注意到我无法向他们发出JWT身份验证请求,因为身份验证过程对他们不起作用,因为我得到的是基于会话的.formlogin((风格的登录页面内容显示,显示的是200 OK,而不是我所期望的401、403或200 OK,但使用RESTful application/json结构的答案。

如何同时支持基于会话的WebMVC流以及依赖JWT身份验证的REST控制器端点?

import org.junit.jupiter.api.Order;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
@EnableWebSecurity
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class DefaultSecurityConfiguration {
public static final int FILTER_PRECEDENCE = -5;
@Bean
@Order(FILTER_PRECEDENCE)
SecurityFilterChain defaultSecurityFilterChain(final HttpSecurity http) throws Exception {
return http.authorizeRequests(authorizeRequests ->
authorizeRequests
.mvcMatchers("/favicon.ico", "/favicon-16x16.png", "/favicon-32x32.png", "/mstile-150x150.png", "/apple-touch-icon.png", "/", "/assets/**", "/login/**", "/webjars/**", "/register", "/register-form", "/actuator/health", "/reset-password", "/reset-password-2", "/error")
.permitAll()
).formLogin(oauth2 ->
oauth2
.loginPage("/login")
.loginProcessingUrl("/login")
.defaultSuccessUrl("/")
.failureUrl("/login?error=1")
.permitAll()
)
.build();
}
}

这是我的AuthorizationServerConfiguration的过滤器链配置:

@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public SecurityFilterChain authServerSecurityFilterChain(final HttpSecurity http) throws Exception {
final OAuth2AuthorizationServerConfigurer<HttpSecurity> authorizationServerConfigurer =
new OAuth2AuthorizationServerConfigurer<>();
final RequestMatcher endpointsMatcher = authorizationServerConfigurer
.getEndpointsMatcher();

http
.requestMatcher(endpointsMatcher)
.authorizeRequests(authorizeRequests ->
authorizeRequests.anyRequest().authenticated()
)
.csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher))
.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt)
.apply(authorizationServerConfigurer);
return http.formLogin(Customizer.withDefaults()).build();
}

而且,为了好玩,这里有一个我期望工作的示例REST端点:

@Validated
@RestController
@RequiredArgsConstructor
@RequestMapping("/oauth/account")
public class AccountController {
public static final String ACCOUNT_ID_IS_REQUIRED = "Account Id is required.";
private final UserDetailRepository userDetailRepository;
private final AccountService accountService;
/**
* Return List of all account and clients of logged in user
*
* @param authentication
* @return
*/
@GetMapping
public List<AccountResponseDTO> findAllUserAccounts(final Authentication authentication) {
final User user = this.userDetailRepository.findByUsername(authentication.getName()).get();
return this.accountService.findAccountsByUserId(user.getId());
}

除了简单之外,我还很好奇为什么在自定义同意服务器的示例中,在两个不同的安全过滤器中重复声明.formLogin((。我已经玩了很多次了,我对安全过滤器覆盖有点困惑。

如果我在.formLogin((中有差异,我会观察到默认值或间歇性故障。如果我在值更高的@Order上删除.formLogin,那么登录就不起作用,但我得到了一个有效的REST端点。如果我在这两个地方都有.formLogin((,我就有了一个工作良好的WebMVC方面;然而,我的REST控制器Authentications只返回JWT的承载值,而不是Authentication Principal。这里发生了一些奇怪的事情——任何帮助都将不胜感激!

考虑配置3个安全过滤器链。第一个用于auth,第二个用于具有承载令牌的调用,最后一个用于所有其他MVC请求:

@Bean
@Order(1)
@SuppressWarnings("unused")
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
OAuth2AuthorizationServerConfigurer<HttpSecurity> authorizationServerConfigurer =
new OAuth2AuthorizationServerConfigurer<>();
RequestMatcher endpointsMatcher = authorizationServerConfigurer.getEndpointsMatcher();
return http
.requestMatcher(endpointsMatcher)
.authorizeRequests(authorizeRequests ->
authorizeRequests.anyRequest().authenticated()
)
.csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher))
.apply(authorizationServerConfigurer)
.oidc(oidc -> oidc
.clientRegistrationEndpoint(Customizer.withDefaults())
)
.and()
.formLogin(Customizer.withDefaults()).build();
}
@Bean
@Order(2)
@SuppressWarnings("unused")
public SecurityFilterChain resourceServerOauthFilterChain(HttpSecurity http) throws Exception {
http
.requestMatcher(request -> {
String headerValue = request.getHeader("Authorization");
return headerValue != null && headerValue.startsWith("Bearer");
})
.authorizeRequests()
.anyRequest().authenticated()
.and()
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.oauth2ResourceServer().jwt(Customizer.withDefaults());
return http.build();
}
@Bean
@Order(3)
@SuppressWarnings("unused")
SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
return http.authorizeRequests(authorizeRequests ->
authorizeRequests
.mvcMatchers("/favicon.ico", "/favicon-16x16.png", "/favicon-32x32.png", "/mstile-150x150.png", "/apple-touch-icon.png", "/", "/assets/**", "/login/**", "/webjars/**", "/register", "/register-form", "/actuator/health", "/reset-password", "/reset-password-2", "/error")
.permitAll().anyRequest().authenticated()
)
.formLogin(oauth2 ->
oauth2
.loginPage("/login")
.loginProcessingUrl("/login")
.defaultSuccessUrl("/")
.failureUrl("/login?error=1")
.permitAll()
)
.build();
}

至于你的第二个问题,我认为每个过滤链都有自己的过滤集。由于登录也是作为过滤器实现的,因此应该将其添加到相应的过滤器链中。

更新:订单注释的导入似乎不正确:导入org.unit.jupiter.api.Order;

最新更新