Advertisement
7isenko

123

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