Advertisement
7isenko

@PostMapping("/login")

Mar 26th, 2020
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.05 KB | None | 0 0
  1. @PostMapping("/login")
  2.     public ResponseEntity<String> login(@RequestParam(name = "username", required = true) String username, @RequestParam(name = "password", required = true) String password) {
  3.         try {
  4.             if (userRepository.findByUsername(username) == null) {
  5.                 User user = new User(username, passwordEncoder.encode(password));
  6.                 userRepository.save(user);
  7.             }
  8.             UsernamePasswordAuthenticationToken authReq = new UsernamePasswordAuthenticationToken(username,password);
  9.             Authentication auth = authenticationManager.authenticate(authReq);
  10.             SecurityContext sc = SecurityContextHolder.getContext();
  11.             sc.setAuthentication(auth);
  12.             HttpHeaders headers = new HttpHeaders();
  13.             headers.add("Location","/main");
  14.             return new ResponseEntity<>(headers, HttpStatus.FOUND);
  15.             }
  16.  
  17.             catch (AuthenticationException e) {
  18.             return new ResponseEntity<>(("Wrong password"), HttpStatus.UNAUTHORIZED);
  19.         }
  20.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement