在WebSecurityConfigurerAdapter
类中,我们有protected void configure(HttpSecurity http)
方法,我们在其中添加对请求的限制。我想要的是:
1.检索想要进入的用户
2.检查该用户是否存在于数据库中
3.检查该用户是否具有特殊属性,例如:login.endsWith('_login')
最佳答案
实现自定义 AuthenticationProvider 所需的一切。根据需要通过其他服务器进行验证码。
@Component
public class CustomAuthenticationProvider
implements AuthenticationProvider {
@Override
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
String name = authentication.getName();
String password = authentication.getCredentials().toString();
if (shouldAuthenticateAgainstThirdPartySystem()) {
// use the credentials
// and authenticate against the third-party system
return new UsernamePasswordAuthenticationToken(
name, password, new ArrayList<>());
} else {
return null;
}
}
@Override
public boolean supports(Class<?> authentication) {
return authentication.equals(
UsernamePasswordAuthenticationToken.class);
}
}
并注册您的身份验证提供商。
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomAuthenticationProvider authProvider;
@Override
protected void configure(
AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authProvider);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated()
.and()
.httpBasic();
}
}
Note : I am assuming you're using HTTP Basic Authentication, you can to change it to FormLogin or as per your need.
关于java - 如何向 HttpSecurity 添加自定义过滤器并检索用户? ( Spring 安全),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50870048/