Мы разрабатываем мобильное приложение с jQuery mobile и хотим программно аутентифицировать пользователя на серверной части Spring 3.1.x, правильно настроенной с помощью Spring Security.
На серверную часть отправляется запрос POST (с использованием $.post jQuery), содержащий имя пользователя и пароль, затем сервер проверяет правильность учетных данных и регистрирует пользователя.
Похоже, что сервер правильно установил аутентификацию в SecurityContext, однако, когда мы делаем второй запрос к серверу ($.get на страницу, требующую входа в систему), детали безопасности, похоже, не запоминаются, и анонимный токен вроде в контексте.
Это метод в контроллере, который обрабатывает вход в систему (проверка пароля удалена для краткости):
@RequestMapping(value = "/login", method = RequestMethod.POST, produces = "application/json")
@ResponseBody
public Map<String, String> login(@RequestParam String username, @RequestParam String password, HttpServletRequest request) {
Map<String, String> response = new HashMap<String, String>();
User u = userService.findByAccountName(username);
if (u != null && u.hasRole("inspector")) {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
try {
Authentication auth = authenticationManager.authenticate(token);
SecurityContextHolder.getContext().setAuthentication(auth);
response.put("status", "true");
return response;
} catch (BadCredentialsException ex) {
response.put("status", "false");
response.put("error", "Bad credentials");
return response;
}
} else {
response.put("status", "false");
response.put("error", "Invalid role");
return response;
}
}
Это другой метод, в котором мы получаем данные о пользователе вне контекста:
@RequestMapping(value = "/project", method = RequestMethod.GET)
@ResponseBody
public String getProjects(HttpSession session) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
User u = userService.findByAccountName(((UserDetails) authentication.getPrincipal()).getUsername());
...
Конфигурация безопасности Spring:
<global-method-security pre-post-annotations="enabled"/>
<http use-expressions="true" auto-config="true">
<form-login login-processing-url="/static/j_spring_security_check" login-page="/"
authentication-failure-url="/?login_error=t"/>
...
<intercept-url pattern="/api/**" access="permitAll"/>
...
<remember-me key="biKey" token-validity-seconds="2419200"/>
<logout logout-url="/logout"/>
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="udm">
<password-encoder hash="md5"/>
</authentication-provider>
</authentication-manager>
Это должно работать в соответствии с документацией по безопасности spring и другими онлайн-ресурсами. Любые идеи о том, что может быть не так?