spring security config v1

This commit is contained in:
jleroy2023
2025-07-16 11:35:28 +02:00
parent bb927ff282
commit c3902ffc2f
10 changed files with 227 additions and 7 deletions

View File

@@ -0,0 +1,43 @@
package fr.eni.demo.controller;
import fr.eni.demo.bll.JwtService;
import fr.eni.demo.bo.User;
import lombok.Getter;
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.AuthenticationException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/auth")
public class AuthenticationController {
private final AuthenticationManager authManager;
private final JwtService jwtService;
public AuthenticationController(AuthenticationManager authManager, JwtService jwtService) {
this.authManager = authManager;
this.jwtService = jwtService;
}
@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody User user) {
try {
Authentication auth = authManager.authenticate(
new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPasword())
);
String token = jwtService.generateToken(user.getUsername());
return ResponseEntity.ok(token);
} catch (AuthenticationException e) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
}
}