Différences
Ci-dessous, les différences entre deux révisions de la page.
| Les deux révisions précédentes Révision précédente | |||
| web:framework:spring:oauth2 [2024/04/16 13:14] – [Services et authentification] jcheron | web:framework:spring:oauth2 [2024/04/16 13:58] (Version actuelle) – jcheron | ||
|---|---|---|---|
| Ligne 343: | Ligne 343: | ||
| } | } | ||
| </ | </ | ||
| + | ==== Authentification ==== | ||
| + | === DTO === | ||
| + | <sxh kotlin> | ||
| + | class AuthDTO { | ||
| + | @JvmRecord | ||
| + | data class LoginRequest(val username: String, val password: String) | ||
| + | |||
| + | @JvmRecord | ||
| + | data class Response(val message: String, val token: String) | ||
| + | } | ||
| + | </ | ||
| + | === Controller === | ||
| + | |||
| + | <sxh kotlin> | ||
| + | @RestController | ||
| + | @RequestMapping("/ | ||
| + | @Validated | ||
| + | class AuthController { | ||
| + | |||
| + | @Autowired | ||
| + | lateinit var authService: | ||
| + | |||
| + | @Autowired | ||
| + | lateinit var authenticationManager: | ||
| + | |||
| + | @PostMapping("/ | ||
| + | @Throws(IllegalAccessException:: | ||
| + | fun login(@RequestBody userLogin: AuthDTO.LoginRequest): | ||
| + | val authentication: | ||
| + | authenticationManager | ||
| + | .authenticate( | ||
| + | UsernamePasswordAuthenticationToken( | ||
| + | userLogin.username, | ||
| + | userLogin.password | ||
| + | ) | ||
| + | ) | ||
| + | SecurityContextHolder.getContext().authentication = authentication | ||
| + | val userDetails = authentication.getPrincipal() as AuthUser | ||
| + | log.info(" | ||
| + | val token = authService.generateToken(authentication) | ||
| + | val response: AuthDTO.Response = AuthDTO.Response(" | ||
| + | return ResponseEntity.ok< | ||
| + | } | ||
| + | |||
| + | companion object { | ||
| + | private val log: Logger = LoggerFactory.getLogger(AuthController:: | ||
| + | } | ||
| + | } | ||
| + | </ | ||