Ale*_*ili 1 java spring-mvc spring-security
我创建了一个简单的 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);
}
}
Run Code Online (Sandbox Code Playgroud)
我感兴趣的是它是否是在春季安全中有意完成的,或者我遗漏了什么。
由于认证成功后凭据将被删除,因此您必须添加eraseCredentials(false)到AuthenticationManagerBuilder配置中。像下面的代码:
@Autowired
private CustomAuthenticationProvider customAuthProvider;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(customAuthProvider).eraseCredentials(false);
}
Run Code Online (Sandbox Code Playgroud)
这已经晚了,但我认为这是根据问题的正确答案。
| 归档时间: |
|
| 查看次数: |
4805 次 |
| 最近记录: |