Spring контроллер для входа в Spring Security - PullRequest
0 голосов
/ 17 марта 2020

Я пытаюсь реализовать проверку подлинности формы с помощью безопасности Spring в приложении angular -SringBoot. Я нашел этот пример на inte rnet:

код для конфигурации безопасности

   @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";
    }
}

В моем случае, я хочу реализовать контроллер входа в систему, который представляет собой запрос POST с userDTO как @RequestBody: этот ответ объект 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;
    }

Как правильно его реализовать?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...