私は認証のためにそのようなコードを使用します:
@PreAuthorize("isAnonymous()")
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String doLogin(HttpServletRequest request) {
try {
Authentication req = new UsernamePasswordAuthenticationToken(request.getParameter("name"),
request.getParameter("password"));
Authentication result = authenticationManager.authenticate(req);
SecurityContextHolder.getContext().setAuthentication(result);
logger.debug("Success login");
logger.debug(SecurityContextHolder.getContext().getAuthentication());
return "index";
} catch (AuthenticationException e) {
e.printStackTrace();
logger.debug("ACHTUNG! Success failed");
return "index";
}
}
ログインできます。動作します。ログに null 以外の認証オブジェクトが表示されます。次に、次のような保護されたページを閲覧しようとします。
@PreAuthorize("hasRole('user')")
@RequestMapping(value = "/user", method = RequestMethod.GET)
public String user(ModelMap modelMap) {
modelMap.addAttribute("user", SecurityContextHolder.getContext().getAuthentication().getCredentials().toString());
return "index";
}
そして、getAuthentication() のために NullPointerException をスローします。これは、SecurityContextHolder.MODE_GLOBAL の使用とは異なり、SecurityContextHolder.MODE_INHERITABLETHREADLOCAL および SecurityContextHolder.MODE_INHERITABLETHREADLOCAL を使用すると発生します。
私は何を間違っていますか?SecurityContextHolder の MODE_GLOBAL 動作は必要ありません。
UPD:問題が発生することもあれば、同じセッションで発生しないこともあります。