-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Jwt 토큰 생성 및 검증 - Jwt 토큰에서 사용자 정보 가져오기 - Jwt 인증 필터 생성 - Jwt 인증 필터 WebSecurityConfig에 등록 - UserDetails 관련 생성 - 테스트코드 Security 수정
- Loading branch information
Showing
11 changed files
with
240 additions
and
14 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
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,9 @@ | ||
package com.meme.ala.core.auth.jwt; | ||
|
||
import lombok.NoArgsConstructor; | ||
|
||
@NoArgsConstructor | ||
public class Authority { | ||
public static final String ROLE_USER="ROLE_USER"; | ||
public static final String ROLE_ADMIN="ROLE_ADMIN"; | ||
} |
22 changes: 21 additions & 1 deletion
22
src/main/java/com/meme/ala/core/auth/jwt/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 |
---|---|---|
@@ -1,4 +1,24 @@ | ||
package com.meme.ala.core.auth.jwt; | ||
|
||
public class JwtAuthenticationFilter { | ||
import lombok.RequiredArgsConstructor; | ||
import org.springframework.security.core.Authentication; | ||
import org.springframework.security.core.context.SecurityContextHolder; | ||
|
||
import javax.servlet.*; | ||
import javax.servlet.http.HttpServletRequest; | ||
import java.io.IOException; | ||
|
||
@RequiredArgsConstructor | ||
public class JwtAuthenticationFilter implements Filter { | ||
private final JwtTokenProvider jwtTokenProvider; | ||
|
||
@Override | ||
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { | ||
String token = jwtTokenProvider.resolveToken((HttpServletRequest) request); | ||
if (token != null && jwtTokenProvider.validateToken(token)) { | ||
Authentication authentication = jwtTokenProvider.getAuthentication(token); | ||
SecurityContextHolder.getContext().setAuthentication(authentication); | ||
} | ||
chain.doFilter(request, response); | ||
} | ||
} |
71 changes: 71 additions & 0 deletions
71
src/main/java/com/meme/ala/core/auth/jwt/JwtTokenProvider.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,71 @@ | ||
package com.meme.ala.core.auth.jwt; | ||
|
||
import io.jsonwebtoken.Claims; | ||
import io.jsonwebtoken.Jws; | ||
import io.jsonwebtoken.Jwts; | ||
import io.jsonwebtoken.SignatureAlgorithm; | ||
import lombok.RequiredArgsConstructor; | ||
import org.springframework.beans.factory.annotation.Value; | ||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; | ||
import org.springframework.security.core.Authentication; | ||
import org.springframework.security.core.userdetails.UserDetails; | ||
import org.springframework.security.core.userdetails.UserDetailsService; | ||
import org.springframework.stereotype.Component; | ||
|
||
import javax.annotation.PostConstruct; | ||
import javax.servlet.http.HttpServletRequest; | ||
import java.util.Base64; | ||
import java.util.Date; | ||
|
||
@RequiredArgsConstructor | ||
@Component | ||
public class JwtTokenProvider { | ||
@Value("${jwt.secret}") | ||
private String secretKey; | ||
private long tokenValidTime = 30 * 60 * 1000L; | ||
private final UserDetailsService userDetailsService; | ||
|
||
@PostConstruct | ||
protected void init() { | ||
secretKey = Base64.getEncoder().encodeToString(secretKey.getBytes()); | ||
} | ||
|
||
public String createToken(String email){ | ||
Date now=new Date(); | ||
Date expirationDate=new Date(now.getTime()+tokenValidTime); | ||
Claims claims= Jwts.claims().setSubject("alajwt"); | ||
claims.put("email",email); | ||
return Jwts.builder() | ||
.setClaims(claims) | ||
.setIssuedAt(now) | ||
.setExpiration(expirationDate) | ||
.signWith(SignatureAlgorithm.HS256,secretKey) | ||
.compact(); | ||
} | ||
|
||
public Authentication getAuthentication(String token) { | ||
UserDetails userDetails = userDetailsService.loadUserByUsername(this.getUserEmail(token)); | ||
return new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); | ||
} | ||
|
||
public String getUserEmail(String token){ | ||
return Jwts.parser() | ||
.setSigningKey(secretKey) | ||
.parseClaimsJws(token) | ||
.getBody() | ||
.get("email",String.class); | ||
} | ||
|
||
public String resolveToken(HttpServletRequest request){ | ||
return request.getHeader("X-AUTH_TOKEN"); | ||
} | ||
|
||
public boolean validateToken(String jwtToken){ | ||
try { | ||
Jws<Claims> claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwtToken); | ||
return !claims.getBody().getExpiration().before(new Date()); | ||
} catch (Exception e) { | ||
return false; | ||
} | ||
} | ||
} |
20 changes: 20 additions & 0 deletions
20
src/main/java/com/meme/ala/core/auth/jwt/UserDetailServiceImpl.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,20 @@ | ||
package com.meme.ala.core.auth.jwt; | ||
|
||
import com.meme.ala.domain.member.repository.MemberRepository; | ||
import lombok.RequiredArgsConstructor; | ||
import org.springframework.security.core.userdetails.UserDetails; | ||
import org.springframework.security.core.userdetails.UserDetailsService; | ||
import org.springframework.security.core.userdetails.UsernameNotFoundException; | ||
import org.springframework.stereotype.Service; | ||
|
||
@RequiredArgsConstructor | ||
@Service | ||
public class UserDetailServiceImpl implements UserDetailsService { | ||
private final MemberRepository memberRepository; | ||
|
||
@Override | ||
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { | ||
//TODO: 21.07.18 orElseThrow로 EntityNotFoundException::new 불가하여 null로 설정함 | ||
return new UserDetailsImpl(memberRepository.findByEmail(username).orElse(null)); | ||
} | ||
} |
56 changes: 56 additions & 0 deletions
56
src/main/java/com/meme/ala/core/auth/jwt/UserDetailsImpl.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,56 @@ | ||
package com.meme.ala.core.auth.jwt; | ||
|
||
import com.meme.ala.domain.member.model.entity.Member; | ||
import lombok.Data; | ||
import org.springframework.security.core.GrantedAuthority; | ||
import org.springframework.security.core.authority.SimpleGrantedAuthority; | ||
import org.springframework.security.core.userdetails.UserDetails; | ||
|
||
import java.util.ArrayList; | ||
import java.util.Collection; | ||
|
||
@Data | ||
public class UserDetailsImpl implements UserDetails { | ||
private Member member; | ||
|
||
public UserDetailsImpl(Member member){ | ||
this.member=member; | ||
} | ||
|
||
@Override | ||
public Collection<? extends GrantedAuthority> getAuthorities() { | ||
Collection<GrantedAuthority> authorities=new ArrayList<>(); | ||
authorities.add(new SimpleGrantedAuthority(member.getAuthority())); | ||
return authorities; | ||
} | ||
|
||
@Override | ||
public String getPassword() { | ||
return null; | ||
} | ||
|
||
@Override | ||
public String getUsername() { | ||
return member.getMemberSetting().getNickname(); | ||
} | ||
|
||
@Override | ||
public boolean isAccountNonExpired() { | ||
return true; | ||
} | ||
|
||
@Override | ||
public boolean isAccountNonLocked() { | ||
return true; | ||
} | ||
|
||
@Override | ||
public boolean isCredentialsNonExpired() { | ||
return true; | ||
} | ||
|
||
@Override | ||
public boolean isEnabled() { | ||
return true; | ||
} | ||
} |
43 changes: 42 additions & 1 deletion
43
src/main/java/com/meme/ala/core/config/WebSecurityConfig.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,4 +1,45 @@ | ||
package com.meme.ala.core.config; | ||
|
||
public class WebSecurityConfig { | ||
import com.meme.ala.core.auth.jwt.JwtAuthenticationFilter; | ||
import com.meme.ala.core.auth.jwt.JwtTokenProvider; | ||
import lombok.RequiredArgsConstructor; | ||
import org.springframework.context.annotation.Bean; | ||
import org.springframework.security.authentication.AuthenticationManager; | ||
import org.springframework.security.config.annotation.web.builders.HttpSecurity; | ||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; | ||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; | ||
import org.springframework.security.config.http.SessionCreationPolicy; | ||
import org.springframework.security.crypto.factory.PasswordEncoderFactories; | ||
import org.springframework.security.crypto.password.PasswordEncoder; | ||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; | ||
|
||
@RequiredArgsConstructor | ||
@EnableWebSecurity | ||
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { | ||
private final JwtTokenProvider jwtTokenProvider; | ||
|
||
@Bean | ||
public PasswordEncoder passwordEncoder() { | ||
return PasswordEncoderFactories.createDelegatingPasswordEncoder(); | ||
} | ||
|
||
@Bean | ||
@Override | ||
public AuthenticationManager authenticationManagerBean() throws Exception { | ||
return super.authenticationManagerBean(); | ||
} | ||
|
||
@Override | ||
protected void configure(HttpSecurity http) throws Exception { | ||
http | ||
.httpBasic().disable() | ||
.csrf().disable() | ||
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) | ||
.and() | ||
.authorizeRequests() | ||
.anyRequest().permitAll() | ||
.and() | ||
.addFilterBefore(new JwtAuthenticationFilter(jwtTokenProvider), | ||
UsernamePasswordAuthenticationFilter.class); | ||
} | ||
} |
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
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
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,2 +1,3 @@ | ||
spring.data.mongodb.uri=mongodb://localhost:27017 | ||
spring.data.mongodb.database=testdb | ||
spring.data.mongodb.database=testdb | ||
jwt.secret=alasecret |
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