通常,最好将您的问题分解为多个 StackOverflow 问题,因为您更有可能找到知道单个问题答案的人而不是两者。
我们如何避免为身份验证失败创建会话?
默认情况下,Spring Security 会将最后一个未经身份验证的请求保存到会话,以便在您进行身份验证后它可以自动再次发出请求。例如,在浏览器中,如果您请求 example.com/a/b/c 并且未通过身份验证,它将将 example.com/a/b/c 保存到 HttpSession,然后让用户进行身份验证。在您通过身份验证后,它会自动为您提供 example.com/a/b/c 的结果。这提供了良好的用户体验,因此您的用户无需再次键入 URL。
在 REST 服务的情况下,这不是必需的,因为客户端会记住需要重新请求哪个 URL。您可以通过修改配置以使用 NullRequestCache 来阻止保存,如下所示:
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.requestCache()
.requestCache(new NullRequestCache())
.and()
.httpBasic();
}
您可以通过提供自己的 AuthenticationProvider 来提供自定义身份验证。例如:
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.AuthorityUtils;
public class RestAuthenticationProvider implements AuthenticationProvider {
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
String username = token.getName();
String password = (String) token.getCredentials();
// validate making REST call
boolean success = true;
// likely your REST call will return the roles for the user
String[] roles = new String[] { "ROLE_USER" };
if(!success) {
throw new BadCredentialsException("Bad credentials");
}
return new UsernamePasswordAuthenticationToken(username, null, AuthorityUtils.createAuthorityList(roles));
}
public boolean supports(Class<?> authentication) {
return (UsernamePasswordAuthenticationToken.class
.isAssignableFrom(authentication));
}
}
然后,您可以使用以下内容配置您的 RestAuthenticationProvider:
@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
...
@Bean
public RestAuthenticationProvider restAuthenticationProvider() {
return new RestAuthenticationProvider();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth, AuthenticationProvider provider) throws Exception {
auth
.authenticationProvider(provider);
}
}