SecurityContextRepository

SecurityContextRepository

我正在尝试使用我在上面接过的代码进行Ajax登录,这是:

@Controller
@RequestMapping("/login")

public class AjaxLoginController {

@Autowired
@Qualifier("AuthenticationManager")
AuthenticationManager authenticationManager;

@Autowired
SecurityContextRepository repository;

@Autowired
RememberMeServices rememberMeServices;

@RequestMapping(method=RequestMethod.GET)
public void login() {}

@RequestMapping(method=RequestMethod.POST)
@ResponseBody
public String performLogin(
    @RequestParam("j_username") String username,
    @RequestParam("j_password") String password,
    HttpServletRequest request, HttpServletResponse response)
{
    UsernamePasswordAuthenticationToken token =
            new UsernamePasswordAuthenticationToken(username, password);
    try {
            Authentication auth = authenticationManager.authenticate(token);
            SecurityContextHolder.getContext().setAuthentication(auth);
            repository.saveContext(SecurityContextHolder.getContext(), request, response);
            rememberMeServices.loginSuccess(request, response, auth);
            return "{\"status\": true}";
    } catch (BadCredentialsException ex) {
            return "{\"status\": false, \"error\": \"Bad Credentials\"}";
    }
}
}


此示例具有用于自动装配的bean的xml配置,但是我的项目要求通过类配置来完成。我解决了第一个自动接线问题,将其添加到我的安全性类配置中:

@Bean
public AuthenticationManager AuthenticationManager() throws Exception {
    return authenticationManager();
}


现在,我正在尝试使用securityContextRepository进行操作,但是在论坛上找到的所有内容都是xml配置解决方案。
有谁知道如何将此类配置为Bean来解决此问题?谢谢。

最佳答案

HttpSessionSecurityContextRepositorySecurityContextRepository的默认实现。将此添加到配置中:

@Bean
public SecurityContextRepository securityContextRepository() {
    return new HttpSessionSecurityContextRepository();
}


请注意,bean的名称是securityContextRepository而不是repository,我认为这可以减少任何歧义。

10-06 01:21