我对以下领域有疑问:春季会议和春季安全。
我有一个示例示例中提供的通过基本内存中身份验证通过Spring Security保护的应用程序。
我看到即使验证不成功,spring仍在创建会话ID,这意味着x-auth-token
即使没有提供基本的身份验证凭据详细信息,我也在Redis数据库的响应标头中看到。我们如何避免为身份验证失败创建会话?
想要使用spring安全性来保护资源,假设spring会话仅为受保护的资源创建会话。
假设登录API(/ signin-HTTP Post)针对第三方REST API验证(用户名和密码)凭据。
外部API验证凭据后,如何在成功身份验证后更新spring安全上下文?
应该提供对其他x-auth-token
需要确认的安全资源的访问,并应根据该信息提供对安全资源的访问。
在这种情况下,我们需要使用Spring Security吗?还是应该使用基本的过滤器和spring会话?推荐什么?
通常,最好将您的问题分解为多个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);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句