我写了一个应用程序作为学习Spring的一部分,但是当我测试身份验证时,我收到401状态而不是200.我正在寻找错误的原因,在我看来,行身份验证身份验证= authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(电子邮件,密码));返回null.但是,我不知道如何解决这个问题.
@Component
public class AuthenticationServiceUsernamePassword {
private static final Logger LOGGER = LoggerFactory.getLogger(AuthenticationServiceUsernamePassword.class);
@Autowired
@Qualifier("customAuthenticationManager")
private AuthenticationManager authenticationManager;
@Autowired
private TokenManager tokenManager;
public SignedJWT authenticate(final String email,final String password){
try {
Authentication authentication = authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken(email,password));
SecurityContextHolder.getContext()
.setAuthentication(authentication);
if (authentication.getPrincipal() != null) {
return tokenManager.createNewToken((PrincipalUser) authentication.getPrincipal());
}
} catch (AuthenticationException authException) {
LOGGER.debug("Authentication Failed for user:\"" + email + ".\" Reason " + authException.getClass());
}
return null;
}
}
调节器
@Controller
public class AuthController {
@Value("${jwt.result}")
private String defaultTokenResponse;
@Autowired
private AuthenticationServiceUsernamePassword authUserPassword;
@RequestMapping(value = "/authentication",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity
测试类:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
@WebAppConfiguration
public class ConnectControllerTest {
protected MockMvc mockMvc;
@Autowired
private WebApplicationContext context;
@Autowired
private Filter springSecurityFilterChain;
@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(context)
.addFilters(springSecurityFilterChain)
.defaultRequest(get("/"))
.build();
}
@Test
public void shouldTestAuthentication() throws Exception {
String result = mockMvc.perform(post("/authentication")
.param("email","user@test.pl").param("password","password"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.token").exists())
.andReturn().getResponse().getContentAsString();
}
}
如果有人对其余代码感兴趣,请点击链接:repository
最佳答案
好.首先是第一件事
问题在这里
public SignedJWT authenticate(final String email,final String password){
try {
System.out.println("test => "+email+" : "+password);
Authentication authentication = authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken(email,password));
SecurityContextHolder.getContext().setAuthentication(authentication);
if (authentication.getPrincipal() != null) {
return tokenManager.createNewToken((PrincipalUser) authentication.getPrincipal());
}
} catch (AuthenticationException authException) {
authException.printStackTrace();
LOGGER.debug("Authentication Failed for user:\"" + email + ".\" Reason " + authException.getClass());
}
System.out.println("return nulll");
return null;
}
如果运行测试用例,则会抛出以下错误
org.springframework.security.authentication.BadCredentialsException: Bad credentials
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.additionalAuthenticationChecks(DaoAuthenticationProvider.java:98)
at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:166)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:174)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:199)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter$AuthenticationManagerDelegator.authenticate(WebSecurityConfigurerAdapter.java:504)
at com.github.springjwt.security.jwt.service.AuthenticationServiceUsernamePassword.authenticate(AuthenticationServiceUsernamePassword.java:30)
at com.github.springjwt.web.api.controller.AuthController.authenticate(AuthController.java:31)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImp
这意味着您的测试用例的用户名和密码与UserRepository类用户详细信息不匹配
在您的UserRepository类中
您需要设置正确的哈希密码及其设置为null的盐值.
当您调用authenticate.authenticate时,它会在内部获取密码和哈希值,并将其与传递的值进行匹配.
P.S:我在本地运行代码后得出了这个结论