web:framework:spring:oauth2

Différences

Ci-dessous, les différences entre deux révisions de la page.

Lien vers cette vue comparative

Les deux révisions précédentes Révision précédente
web:framework:spring:oauth2 [2024/04/16 13:14] – [Services et authentification] jcheronweb:framework:spring:oauth2 [2024/04/16 13:58] (Version actuelle) jcheron
Ligne 343: Ligne 343:
 } }
 </sxh> </sxh>
 +==== 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)
 +}
 +</sxh>
 +=== Controller ===
 +
 +<sxh kotlin>
 +@RestController
 +@RequestMapping("/api/auth")
 +@Validated
 +class AuthController {
 +
 +    @Autowired
 +    lateinit var authService: AuthService
 +
 +    @Autowired
 +    lateinit var authenticationManager: AuthenticationManager
 +
 +    @PostMapping("/login")
 +    @Throws(IllegalAccessException::class)
 +    fun login(@RequestBody userLogin: AuthDTO.LoginRequest): ResponseEntity<*> {
 +        val authentication: Authentication =
 +            authenticationManager
 +                .authenticate(
 +                    UsernamePasswordAuthenticationToken(
 +                        userLogin.username,
 +                        userLogin.password
 +                    )
 +                )
 +        SecurityContextHolder.getContext().authentication = authentication
 +        val userDetails = authentication.getPrincipal() as AuthUser
 +        log.info("Token requested for user :{}", authentication.getAuthorities())
 +        val token = authService.generateToken(authentication)
 +        val response: AuthDTO.Response = AuthDTO.Response("User logged in successfully", token)
 +        return ResponseEntity.ok<Any>(response)
 +    }
 +
 +    companion object {
 +        private val log: Logger = LoggerFactory.getLogger(AuthController::class.java)
 +    }
 +}
 +</sxh>
  • web/framework/spring/oauth2.txt
  • Dernière modification : il y a 3 semaines
  • de jcheron