spring cloud : e-commerce(user-service) - spring security login(jwt)

This commit is contained in:
haerong22
2021-09-22 19:38:03 +09:00
parent f6dfe1190e
commit 357cc76e1a
8 changed files with 62 additions and 6 deletions

View File

@@ -25,14 +25,20 @@ spring:
uri: lb://ORDER-SERVICE
predicates:
- Path=/order-service/**
- id: catalog-service
uri: lb://CATALOG-SERVICE
predicates:
- Path=/catalog-service/**
- id: user-service
uri: lb://USER-SERVICE
predicates:
- Path=/user-service/**
filters:
- RemoveRequestHeader=Cookie
- RewritePath=/user-service/(?<segment>.*), /$\{segment}
- id: first-service
uri: lb://MY-FIRST-SERVICE
predicates:
@@ -41,6 +47,7 @@ spring:
# - AddRequestHeader=first-request, first-request-header2
# - AddResponseHeader=first-response, first-response-header2
- CustomFilter
- id: second-service
uri: lb://MY-SECOND-SERVICE
predicates:

View File

@@ -30,6 +30,7 @@ dependencies {
implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client'
implementation group: 'org.modelmapper', name: 'modelmapper', version: '2.4.4'
implementation group: 'io.jsonwebtoken', name: 'jjwt', version: '0.9.1'
runtimeOnly group: 'com.h2database', name: 'h2', version: '1.3.176'
compileOnly 'org.projectlombok:lombok'

View File

@@ -20,7 +20,7 @@ import java.util.List;
@RestController
@RequiredArgsConstructor
@RequestMapping("/user-service")
@RequestMapping("/")
public class UserController {
private final Greeting greeting;

View File

@@ -1,10 +1,19 @@
package com.example.userservice.security;
import com.example.userservice.dto.UserDto;
import com.example.userservice.service.UserService;
import com.example.userservice.vo.RequestLogin;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.Environment;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import javax.servlet.FilterChain;
@@ -13,9 +22,21 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
@Slf4j
public class AuthenticationFilter extends UsernamePasswordAuthenticationFilter {
private final UserService userService;
private final Environment env;
public AuthenticationFilter(AuthenticationManager authenticationManager,
UserService userService, Environment env) {
super.setAuthenticationManager(authenticationManager);
this.userService = userService;
this.env = env;
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request,
HttpServletResponse response) throws AuthenticationException {
@@ -39,5 +60,17 @@ public class AuthenticationFilter extends UsernamePasswordAuthenticationFilter {
HttpServletResponse response,
FilterChain chain,
Authentication authResult) throws IOException, ServletException {
String username = ((User) authResult.getPrincipal()).getUsername();
UserDto userDetails = userService.getUserDetailByEmail(username);
String token = Jwts.builder()
.setSubject(userDetails.getUserId())
.setExpiration(new Date(System.currentTimeMillis() +
Long.parseLong(env.getProperty("token.expiration_time"))))
.signWith(SignatureAlgorithm.HS512, env.getProperty("token.secret"))
.compact();
response.addHeader("token", token);
response.addHeader("userId", userDetails.getUserId());
}
}

View File

@@ -39,10 +39,7 @@ public class WebSecurity extends WebSecurityConfigurerAdapter {
}
private AuthenticationFilter getAuthenticationFilter() throws Exception {
AuthenticationFilter authenticationFilter = new AuthenticationFilter();
authenticationFilter.setAuthenticationManager(authenticationManager());
return authenticationFilter;
return new AuthenticationFilter(authenticationManager(), userService, env);
}

View File

@@ -11,4 +11,6 @@ public interface UserService extends UserDetailsService {
void createUser(UserDto userDto);
UserDto getUserByUserId(String userId);
List<UserEntity> gerUserByAll();
UserDto getUserDetailByEmail(String username);
}

View File

@@ -60,4 +60,12 @@ public class UserServiceImpl implements UserService {
true, true, true, true,
new ArrayList<>());
}
@Override
public UserDto getUserDetailByEmail(String email) {
UserEntity userEntity = userRepository.findByEmail(email)
.orElseThrow(() -> new UsernameNotFoundException(email));
return mapper.map(userEntity, UserDto.class);
}
}

View File

@@ -26,4 +26,12 @@ eureka:
defaultZone: http://127.0.0.1:8761/eureka #등록 위치
greeting:
message: Welcome to Simple E-commerce.
message: Welcome to Simple E-commerce.
logging:
level:
com.example.userservice: DEBUG
token:
expiration_time: 86400000
secret: user_token