I wrote an application as part of learning Spring, but when I test authentication I receive 401 status instead of 200. I was looking for the cause of the error and it seems to me that the line Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(email, password));
returns null
. However, I do not know how to solve this problem.
@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
@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<String> 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>(String.format(defaultTokenResponse, token.serialize()),
HttpStatus.OK);
} else {
return new ResponseEntity<String>(HttpStatus.UNAUTHORIZED);
}
} catch (BadCredentialsException badCredentials) {
return new ResponseEntity<String>(HttpStatus.UNAUTHORIZED);
}
} else {
return new ResponseEntity<String>(HttpStatus.UNAUTHORIZED);
}
}
}
Test class:
@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();
}
}
If anyone would be interested in the rest of the code here is the link: repository