개발자라면 한번쯤은 보러오는 곳
모각윙 6주차 본문
728x90
반응형
Last Dance
마지막 모각윙.
앞으로 윙커톤을 어떻게 개발하고 진행할 것인지에 대한 회의를 했다.
로그인 개발
JWT를 이용해 토큰 로그인을 하는 Spring + Kotlin 을 구현했다.
Postman으로 login을 확인해봤을때 토큰이 request되는모습을 볼 수 있다.
Controller Code
@RestController
@RequestMapping("api/users")
class AuthController(private val userService: UserService) {
@PostMapping("signup")
fun singup(@RequestBody body: SignupDTO): ResponseEntity<User> {
val user = User()
user.email = body.email
user.name = body.name
user.nickname = body.nickname
user.password = body.password
return ResponseEntity.ok(this.userService.save(user))
}
@PostMapping("login")
fun login(@RequestBody body: LoginDTO, response: HttpServletResponse): ResponseEntity<Any>{
val user = this.userService.findByEmail(body.email)
?: return ResponseEntity.badRequest().body(Message("user not found!"))
if (!user.comparePassword(body.password)){
return ResponseEntity.badRequest().body(Message("password is wrong!"))
}
val issuer = user.id.toString()
val jwt = Jwts.builder()
.setIssuer(issuer)
.setExpiration(Date(System.currentTimeMillis() + 60 * 24 * 1000))
.signWith(SignatureAlgorithm.HS512, "secret").compact()
val cookie = Cookie("jwt", jwt)
cookie.isHttpOnly = true
response.addCookie(cookie)
return ResponseEntity.ok(Message(jwt))
}
@GetMapping("user")
fun user(@CookieValue("jwt") jwt: String?): ResponseEntity<Any> {
try {
if (jwt == null) {
return ResponseEntity.status(401).body(Message("unauth"))
}
val body = Jwts.parser().setSigningKey("secret").parseClaimsJws(jwt).body
return ResponseEntity.ok(this.userService.getById(body.issuer.toInt()))
} catch (e: Exception) {
return ResponseEntity.status(401).body(Message("unauth"))
}
}
@PostMapping("logout")
fun logout(response: HttpServletResponse): ResponseEntity<Any> {
val cookie = Cookie("jwt", "")
cookie.maxAge = 0
response.addCookie(cookie)
return ResponseEntity.ok(Message("success"))
}
}
728x90
반응형
Comments