SpringBoot项目登录并接入MFA二次认证
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
@RequestMapping("/auth")
public class AuthenticationController {
@Autowired
private AuthenticationService authenticationService;
@PostMapping("/login")
public String login(@RequestParam String username, @RequestParam String password, RedirectAttributes redirectAttributes) {
AuthenticationResult authenticationResult = authenticationService.authenticate(username, password);
if (authenticationResult.isAuthenticated()) {
// 登录成功,进行MFA二次验证
if (authenticationResult.requiresMfa()) {
// 保存用户信息以供MFA验证使用
redirectAttributes.addAttribute("userId", authenticationResult.getUserId());
// 重定向到MFA验证页面
return "redirect:/auth/mfa-challenge";
}
// 正常登录重定向
return "redirect:/dashboard";
} else {
// 登录失败,设置错误信息并重定向
redirectAttributes.addFlashAttribute("error", "登录失败");
return "redirect:/login";
}
}
// ... 其他控制器方法
}
在这个简化的代码示例中,我们假设AuthenticationService
已经实现了登录验证逻辑,并且AuthenticationResult
包含了是否需要MFA的信息。登录成功后,如果需要MFA,我们将用户ID存储在RedirectAttributes
中,并重定向到MFA验证页面。如果不需要MFA,则重定向到主面板。登录失败时,我们将错误信息存储在flash属性中,并重定向回登录页面。
评论已关闭