angular - 用于在 Spring Security 中登录的弹簧控制器
问题描述
我正在尝试在 angular-SringBoot 应用程序中使用 Spring 安全性实现表单身份验证。我在网上找到了这个例子:
安全配置代码
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login")
.permitAll()
.antMatchers("/**")
.hasAnyRole("ADMIN", "USER")
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/home")
.failureUrl("/login?error=true")
.permitAll()
.and()
.logout()
.logoutSuccessUrl("/login?logout=true")
.invalidateHttpSession(true)
.permitAll()
.and()
.csrf()
.disable();
控制器代码
@Controller
public class LoginController
{
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String loginPage(@RequestParam(value = "error", required = false) String error,
@RequestParam(value = "logout", required = false) String logout,
Model model) {
String errorMessge = null;
if(error != null) {
errorMessge = "Username or Password is incorrect !!";
}
if(logout != null) {
errorMessge = "You have been successfully logged out !!";
}
model.addAttribute("errorMessge", errorMessge);
return "login";
}
@RequestMapping(value="/logout", method = RequestMethod.GET)
public String logoutPage (HttpServletRequest request, HttpServletResponse response) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null){
new SecurityContextLogoutHandler().logout(request, response, auth);
}
return "redirect:/login?logout=true";
}
}
就我而言,我想实现一个登录控制器,它是一个带有 userDTO 作为@RequestBody 的 POST 请求:响应 userDTO 对象
@RestController
@RequestMapping({"/api/user"})
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "/login",
method = RequestMethod.POST)
public @ResponseBody UserDTO login(@RequestBody UserDTO userDTO){
String message = userService.checkIfUserExistsAndGoodCredential(userDTO);
if (message.isEmpty()) {
userDTO = userService.findByEmailAndPassword(userDTO.getEmail(), userDTO.getPassword());
userDTO.setPassword("");
} else {
userDTO.setMessage(message);
}
return userDTO;
}
如何正确实施?
解决方案
推荐阅读
- vba - 带有 VBA 的 MS Access 不编辑该行
- sql - SQL Server 查询 - 最大化 SUM 的间隔值
- python-3.x - 从脚本中将图像添加到 python GUI
- java - 如何为 java SDK 客户端项目同时支持 maven 和 gradle
- fortran - 在 Gfortran 中使用可选参数时接口不明确
- intellij-idea - 无法识别的插件:org.jetbrains.plugins.cucumber.java.run.CucumberJvm3SMFormatter
- swift - 不能在属性初始化器中使用实例成员“getA”;属性初始化程序在“自我”可用之前运行
- csv - Cypher:如何在加载期间创建关系
- javascript - 如何使用 JavaScript / jQuery 在页面加载时显示 X 数量的子 div?
- ios - iOS-Charts 在 xAxis 中重置偏移量