使用 Spring 安全 + Spring 会话设置身份验证为真
Setting authentication true with Spring Security + Spring Session
我有一个 Spring 安全 + Spring 会话 + Spring 引导项目和一个带有自定义登录 POST 方法的控制器。我有自己的方法来验证客户的凭据。验证成功后,访问会话并将标识设置为 true 的最佳做法是什么?
我已经试过了,但没有结果:
@PostMapping("/login")
public ResponseEntity loginSubmit(@RequestBody LoginForm form) {
Errors errors = authenticationService.validateLoginForm(form);
if (!errors.hasErrors()) {
CustomerDTO result = authenticationService.findCustomerByEmailAndPassword(form);
boolean success = (result != null && result.getId() != null);
SecurityContextHolder.getContext().getAuthentication().setAuthenticated(success);
return new ResponseEntity(result, HttpStatus.OK);
} else {
return new ResponseEntity(errors.getAllErrors(), HttpStatus.OK);
}
}
我应该怎么做呢?
与其编写您自己的端点,我建议通过实施您自己的 org.springframework.security.authentication.AuthenticationProvider
来集成到 Spring 安全框架中
或者干脆这样做
public void login(HttpServletRequest req, String user, String pass) {
UsernamePasswordAuthenticationToken authReqz = new UsernamePasswordAuthenticationToken(user, pass);
Authentication auth = authManager.authenticate(authReq);
SecurityContext sc = SecurityContextHolder.getContext();
sc.setAuthentication(auth);
HttpSession session = req.getSession(true);
session.setAttribute(SPRING_SECURITY_CONTEXT_KEY, sc);
}
可以找到详细的解释here
我有一个 Spring 安全 + Spring 会话 + Spring 引导项目和一个带有自定义登录 POST 方法的控制器。我有自己的方法来验证客户的凭据。验证成功后,访问会话并将标识设置为 true 的最佳做法是什么?
我已经试过了,但没有结果:
@PostMapping("/login")
public ResponseEntity loginSubmit(@RequestBody LoginForm form) {
Errors errors = authenticationService.validateLoginForm(form);
if (!errors.hasErrors()) {
CustomerDTO result = authenticationService.findCustomerByEmailAndPassword(form);
boolean success = (result != null && result.getId() != null);
SecurityContextHolder.getContext().getAuthentication().setAuthenticated(success);
return new ResponseEntity(result, HttpStatus.OK);
} else {
return new ResponseEntity(errors.getAllErrors(), HttpStatus.OK);
}
}
我应该怎么做呢?
与其编写您自己的端点,我建议通过实施您自己的 org.springframework.security.authentication.AuthenticationProvider
来集成到 Spring 安全框架中或者干脆这样做
public void login(HttpServletRequest req, String user, String pass) {
UsernamePasswordAuthenticationToken authReqz = new UsernamePasswordAuthenticationToken(user, pass);
Authentication auth = authManager.authenticate(authReq);
SecurityContext sc = SecurityContextHolder.getContext();
sc.setAuthentication(auth);
HttpSession session = req.getSession(true);
session.setAttribute(SPRING_SECURITY_CONTEXT_KEY, sc);
}
可以找到详细的解释here