package com.example.nto.controller; import com.example.nto.entity.Employee; import com.example.nto.repository.EmployeeRepository; import lombok.AllArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.util.ArrayList; import java.util.List; @RestController public class AuthController { @Autowired private EmployeeRepository employeeRepository; @AllArgsConstructor private static class LoginBody { private String login; private String password; public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } } @Autowired private AuthenticationManager authenticationManager; /* Эндпоинт авторизации, кинь сюда логин и пароль, и возможно я дам тебе возможность авторизоваться. */ @PostMapping("/api/login/") private ResponseEntity login(HttpServletRequest request, @RequestBody LoginBody loginBody) { //, @RequestParam String login, @RequestParam String password) { Employee employee = employeeRepository.getByLogin(loginBody.login).get(); List authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority(employee.getRole())); UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken( loginBody.getLogin(), loginBody.getPassword(), authorities); Authentication authentication = authenticationManager.authenticate(authRequest); SecurityContext securityContext = SecurityContextHolder.getContext(); securityContext.setAuthentication(authentication); HttpSession session = request.getSession(true); session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext); return ResponseEntity.status(HttpStatus.OK).build(); } }