我想在登录过程中添加用户ip验证.如果用户的IP地址不在数据库中,则应用程序应拒绝身份验证.
问题:鉴于下面的设置,结果是auth.authenticationProvider()没有替换默认的DaoAuthenticationProvider,而是将UserIpAuthenticationProvider添加为列表中的第一个AuthenticationProvider.
在用户名/密码组合不正确的情况下,框架最终调用UserDetailsService.loadUserByUsername()两次,一次来自UserIpAuthenticationProvider,另一次来自内部DaoAuthenticationProvider,它抛出最终的BadCredentialsException().
问题:是否有任何可以在Spring Boot中设置的设置,以便Spring Security不会添加它自己的内部实例DaoAuthenticationProvider,而只使用我的UserIpAuthenticationProvider,它已经拥有所有必要的功能(可能通过某种方式替换AuthenticationManagerBuilder能够覆盖userDetailsService()方法?).
public <T extends UserDetailsService> DaoAuthenticationConfigurer<AuthenticationManagerBuilder,T> userDetailsService(
T userDetailsService) throws Exception {
this.defaultUserDetailsService = userDetailsService;
return apply(new DaoAuthenticationConfigurer<AuthenticationManagerBuilder,T>(userDetailsService));
}
Run Code Online (Sandbox Code Playgroud)
配置:根据我的理解,UserDetailsService应该提供有关用户的所有必要详细信息,以便AuthenticationProvider可以决定身份验证是否成功.
由于从数据库加载了所有必要的信息,因此扩展DaoAuthenticationProvider并在覆盖additionalAuthenticationChecks()方法中添加额外的验证似乎很自然(白名单中的IP列表在数据库中,因此它们作为用户对象的一部分加载IpAwareUser).
@Named
@Component
class UserIpAuthenticationProvider extends DaoAuthenticationProvider {
@Inject
public UserIpAuthenticationProvider(UserDetailsService userDetailsService)
{
...
}
@SuppressWarnings("deprecation")
protected void additionalAuthenticationChecks(UserDetails userDetails,
UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
super.additionalAuthenticationChecks(userDetails, authentication);
WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails();
IpAwareUser ipAwareUser = (IpAwareUser) userDetails;
if (!ipAwareUser.isAllowedIp(details.getRemoteAddress()))
{
throw new DisabledException("Login restricted from ip: " + details.getRemoteAddress());
}
}
} …Run Code Online (Sandbox Code Playgroud) 使用标准 Hamcrest匹配器的以下assert语句是否有较短的版本?
Collection<Element> collection = ...
assertThat(collection, is(anyOf(nullValue(Collection.class),
emptyCollectionOf(Element.class))));
Run Code Online (Sandbox Code Playgroud)
我意识到有一种创建自定义匹配器的方法,希望可能已经有了解决该问题的方法,而无需进行任何其他代码更改。