-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #26 from real-world-study/hoony-lab-issue23
[hoony-lab-issue23] authentication: jwt token 기능
- Loading branch information
Showing
11 changed files
with
434 additions
and
110 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
29 changes: 22 additions & 7 deletions
29
src/main/java/com/study/realworld/config/SecurityConfig.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
47 changes: 47 additions & 0 deletions
47
src/main/java/com/study/realworld/config/auth/JwtAuthenticationFilter.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
package com.study.realworld.config.auth; | ||
|
||
import lombok.RequiredArgsConstructor; | ||
import lombok.extern.slf4j.Slf4j; | ||
import org.springframework.http.HttpHeaders; | ||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; | ||
import org.springframework.security.core.context.SecurityContextHolder; | ||
import org.springframework.stereotype.Component; | ||
import org.springframework.web.filter.OncePerRequestFilter; | ||
|
||
import javax.servlet.FilterChain; | ||
import javax.servlet.ServletException; | ||
import javax.servlet.http.HttpServletRequest; | ||
import javax.servlet.http.HttpServletResponse; | ||
import java.io.IOException; | ||
import java.util.Collections; | ||
|
||
@Slf4j | ||
@RequiredArgsConstructor | ||
@Component | ||
public class JwtAuthenticationFilter extends OncePerRequestFilter { | ||
|
||
private static final String DOFILTERMESSAGE = "{} {} : {}"; | ||
|
||
private final JwtProvider jwtProvider; | ||
|
||
@Override | ||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { | ||
log.info(DOFILTERMESSAGE, request.getMethod(), request.getRequestURI(), request.getHeader(HttpHeaders.AUTHORIZATION)); | ||
String header = request.getHeader(HttpHeaders.AUTHORIZATION); | ||
|
||
if(header != null) { | ||
String tokenPrefix = header.split(" ")[0]; | ||
String accessToken = header.split(" ")[1]; | ||
|
||
if("Token".equals(tokenPrefix)) { | ||
String email = jwtProvider.getSubjectFromToken(accessToken); | ||
final UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(email, accessToken, Collections.emptyList()); | ||
|
||
SecurityContextHolder.getContext().setAuthentication(authentication); | ||
} | ||
} | ||
|
||
filterChain.doFilter(request, response); | ||
} | ||
|
||
} |
69 changes: 69 additions & 0 deletions
69
src/main/java/com/study/realworld/config/auth/JwtProvider.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
package com.study.realworld.config.auth; | ||
|
||
import com.study.realworld.user.domain.User; | ||
import io.jsonwebtoken.Claims; | ||
import io.jsonwebtoken.JwtException; | ||
import io.jsonwebtoken.Jwts; | ||
import io.jsonwebtoken.SignatureAlgorithm; | ||
import org.springframework.beans.factory.annotation.Value; | ||
import org.springframework.stereotype.Component; | ||
|
||
import javax.crypto.spec.SecretKeySpec; | ||
import javax.xml.bind.DatatypeConverter; | ||
import java.security.Key; | ||
import java.util.Date; | ||
import java.util.HashMap; | ||
import java.util.Map; | ||
|
||
@Component | ||
public class JwtProvider { | ||
|
||
private String secret; | ||
private int accessTime; | ||
|
||
public JwtProvider(@Value("${jwt.secret}") String secret, | ||
@Value("${jwt.access-time}") int accessTime) { | ||
this.secret = secret; | ||
this.accessTime = accessTime; | ||
} | ||
|
||
public String generateJwtToken(User user) { | ||
return Jwts.builder() | ||
.setSubject(user.getEmail()) | ||
.setHeader(createHeader()) | ||
.setIssuedAt(new Date(System.currentTimeMillis())) | ||
.setExpiration(new Date(System.currentTimeMillis() + accessTime)) | ||
.signWith(createKey(), SignatureAlgorithm.HS512) | ||
.compact(); | ||
} | ||
|
||
public Claims getClaimsFromToken(String token) { | ||
try { | ||
return Jwts.parserBuilder() | ||
.setSigningKey(DatatypeConverter.parseBase64Binary(secret)) | ||
.build() | ||
.parseClaimsJws(token) | ||
.getBody(); | ||
} catch (JwtException | NullPointerException e) { | ||
throw new JwtException("Invalid token"); | ||
} | ||
} | ||
|
||
public String getSubjectFromToken(String token) { | ||
return this.getClaimsFromToken(token) | ||
.getSubject(); | ||
} | ||
|
||
private Map<String, Object> createHeader() { | ||
Map<String, Object> header = new HashMap<>(); | ||
header.put("alg", "HS512"); | ||
header.put("typ", "JWT"); | ||
return header; | ||
} | ||
|
||
private Key createKey() { | ||
byte[] secretKeyBytes = DatatypeConverter.parseBase64Binary(secret); | ||
return new SecretKeySpec(secretKeyBytes, SignatureAlgorithm.HS512.getJcaName()); | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
35 changes: 27 additions & 8 deletions
35
src/main/java/com/study/realworld/user/web/UserController.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,38 +1,57 @@ | ||
package com.study.realworld.user.web; | ||
|
||
import com.study.realworld.config.auth.JwtProvider; | ||
import com.study.realworld.user.domain.User; | ||
import com.study.realworld.user.dto.UserJoinRequest; | ||
import com.study.realworld.user.dto.UserLoginRequest; | ||
import com.study.realworld.user.dto.UserResponse; | ||
import com.study.realworld.user.service.UserService; | ||
import lombok.RequiredArgsConstructor; | ||
import lombok.extern.slf4j.Slf4j; | ||
import org.springframework.http.HttpHeaders; | ||
import org.springframework.http.ResponseEntity; | ||
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; | ||
import org.springframework.security.core.Authentication; | ||
import org.springframework.security.core.context.SecurityContextHolder; | ||
import org.springframework.web.bind.annotation.*; | ||
|
||
import javax.servlet.http.HttpServletRequest; | ||
|
||
@Slf4j | ||
@RequiredArgsConstructor | ||
@RequestMapping("/api") | ||
@RestController | ||
public class UserController { | ||
|
||
private final JwtProvider jwtProvider; | ||
private final UserService userService; | ||
|
||
@PostMapping("/users") | ||
public ResponseEntity<UserResponse> joinUser(@RequestBody UserJoinRequest request) { | ||
User user = userService.save(request); | ||
String token = null; | ||
String token = jwtProvider.generateJwtToken(user); | ||
|
||
return ResponseEntity.ok().body(UserResponse.of(user, token)); | ||
return ResponseEntity.ok() | ||
.body(UserResponse.of(user, token)); | ||
} | ||
|
||
@PostMapping("/users/login") | ||
public ResponseEntity<UserResponse> loginUser(@RequestBody UserLoginRequest request) { | ||
User user = userService.login(request); | ||
String token = null; | ||
String token = jwtProvider.generateJwtToken(user); | ||
|
||
return ResponseEntity.ok() | ||
.header(HttpHeaders.AUTHORIZATION, "Token " + token) | ||
.body(UserResponse.of(user, token)); | ||
} | ||
|
||
@GetMapping("/user") | ||
public ResponseEntity<UserResponse> getUser(HttpServletRequest servletRequest) { | ||
String email = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); | ||
User user = userService.findByEmail(email); | ||
String token = servletRequest.getHeader(HttpHeaders.AUTHORIZATION).split(" ")[1]; | ||
|
||
return ResponseEntity.ok().body(UserResponse.of(user, token)); | ||
return ResponseEntity.ok() | ||
.body(UserResponse.of(user, token)); | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.