我写了一个应用程序作为学习
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 authenticate(String email, String password, HttpServletRequest request,
HttpServletResponse response){
if (email != null && password != null){
try {
SignedJWT token = authUserPassword.authenticate(email, password);
if (token != null){
return new ResponseEntity(String.format(defaultTokenResponse, token.serialize()),
HttpStatus.OK);
} else {
return new ResponseEntity(HttpStatus.UNAUTHORIZED);
}
} catch (BadCredentialsException badCredentials) {
return new ResponseEntity(HttpStatus.UNAUTHORIZED);
}
} else {
return new ResponseEntity(HttpStatus.UNAUTHORIZED);
}
}
}
测试类:
@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