【发布时间】:2019-04-28 23:49:55
【问题描述】:
我创建了一个简单的 spring web mvc 应用程序,但我遇到了一个问题。身份验证后,我尝试获取身份验证对象,但由于某种原因,它的凭据为空。
在这个项目中,我有一个自定义的 AuthenticationProvider,如下所示:
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
@Autowired
private UserService userService;
@Autowired
private RoleService roleService;
@PostConstruct
public void init() {
roleService.AddStandardRolesIfNeeded();
userService.AddUserWithAdminRoleIfNotExists("a");
}
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
Object credentials = authentication.getCredentials();
if(!(credentials instanceof String)) {
return null;
}
String username = authentication.getName();
String password = credentials.toString(); //password isn't null here
User user = userService.findByUsernameAndPassword(username, password);
if(user == null) {
throw new BadCredentialsException("Authentication failed for " + username);
}
List<GrantedAuthority> authorities = new ArrayList<>();
for(Role role : user.getRoles()) {
authorities.add(new SimpleGrantedAuthority(role.getName()));
}
Authentication auth = new
UsernamePasswordAuthenticationToken(username, password, authorities);
return auth;
}
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}
我感兴趣的是它是在 Spring Security 中故意完成的,还是我遗漏了一些东西。
【问题讨论】:
-
为什么要按用户名和密码搜索?您应该只按用户名搜索。
-
然后在 authenticate() 方法中比较密码?
标签: java spring-mvc spring-security