I am developing a sample application using Spring MVC 3.1. In this application I am using REST APIs and to use REST APIs I am using Rest Template.
My First page is simple login form, where the user enters a username and password. In the controller, I get these username and password, encode them and send get request for basic authentication.
If the status code is 200 then user is authenticated otherwise it is not.
But I am always getting status code 301.
My Controller code is as follows:
@RequestMapping(value = "/loginForm", method = RequestMethod.POST)
public String login(@ModelAttribute("loginForm") LoginForm loginForm,
BindingResult result, ModelMap model) {
String userName = loginForm.getUserName();
String password = loginForm.getPassword();
// Basic Authentication
String token = userName + ":" +password;
BASE64Encoder enc = new sun.misc.BASE64Encoder();
String encodedAuthorization = enc.encode(token.getBytes());
String authHeader = "Basic " + encodedAuthorization;
System.out.println("authHeader :::::: " + authHeader);
// Prepare acceptable media type
List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
acceptableMediaTypes.add(MediaType.APPLICATION_XML);
HttpHeaders headers = new HttpHeaders();
headers.setAccept(acceptableMediaTypes);
headers.setContentType(MediaType.APPLICATION_XML);
headers.set("Authorization", authHeader);
HttpEntity<String> entity = new HttpEntity<String>(headers);
ResponseEntity<String> responseEntity = restTemplate.exchange(uri,
HttpMethod.GET, entity, String.class);
HttpHeaders header = responseEntity.getHeaders();
HttpStatus code = responseEntity.getStatusCode();
System.out.println("Header :::::: " + header);
System.out.println("Code :::::: " + code);
// Validation on fields
validator.validate(loginForm, result);
if (result.hasErrors()) {
return "login";
}
// Checkign status is 200 or not
if ((Integer.parseInt(code.toString())!= 200)) {
model.addAttribute("formError", "true");
return "login";
}
model.addAttribute(loginForm);
return "redirect:dateEntry";
}
Where am I wrong?