首页 > 解决方案 > 用于在 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;
    }

如何正确实施?

标签: angularspring-security

解决方案


推荐阅读