gpt4 book ai didi

java - SecurityContextHolder.getContext().getAuthentication().getCredentials() 身份验证后返回 null

转载 作者:行者123 更新时间:2023-11-30 05:53:52 26 4
gpt4 key购买 nike

我创建了一个简单的 spring web mvc 应用程序,但有一个问题。身份验证后,我尝试获取身份验证对象,但由于某种原因,它的凭据为空。

enter image description here

在这个项目中,我有一个自定义的 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 中有意完成的还是我遗漏了一些东西。

最佳答案

由于身份验证成功后凭据将被删除,因此您必须将 eraseCredentials(false) 添加到 AuthenticationManagerBuilder 配置中。就像下面的代码:

@Autowired
private CustomAuthenticationProvider customAuthProvider;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(customAuthProvider).eraseCredentials(false);
}

这已经晚了,但我认为根据问题这是正确的答案。

关于java - SecurityContextHolder.getContext().getAuthentication().getCredentials() 身份验证后返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53496272/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com