保誠-保戶業務員媒合平台
pamapi/src/main/java/com/pollex/pam/web/rest/UserJWTController.java
@@ -3,8 +3,15 @@
import com.fasterxml.jackson.annotation.JsonProperty;
import com.pollex.pam.security.jwt.JWTFilter;
import com.pollex.pam.security.jwt.TokenProvider;
import com.pollex.pam.business.domain.TokenBlackList;
import com.pollex.pam.business.repository.TokenBlackListRepository;
import com.pollex.pam.business.web.vm.LoginVM;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
@@ -12,6 +19,7 @@
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
/**
@@ -24,6 +32,9 @@
    private final TokenProvider tokenProvider;
    private final AuthenticationManagerBuilder authenticationManagerBuilder;
    @Autowired
    TokenBlackListRepository tokenBlackListRepository;
    public UserJWTController(TokenProvider tokenProvider, AuthenticationManagerBuilder authenticationManagerBuilder) {
        this.tokenProvider = tokenProvider;
@@ -45,6 +56,25 @@
        return new ResponseEntity<>(new JWTToken(jwt), httpHeaders, HttpStatus.OK);
    }
    @PostMapping("/logout")
    public void logout(HttpServletRequest servletRequest) {
        String jwtToken = resolveToken(servletRequest);
        TokenBlackList blackList = new TokenBlackList(jwtToken);
        tokenBlackListRepository.save(blackList);
    }
    private String resolveToken(HttpServletRequest request) {
        String bearerToken = request.getHeader(JWTFilter.AUTHORIZATION_HEADER);
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        String jwt = request.getParameter(JWTFilter.AUTHORIZATION_TOKEN);
        if (StringUtils.hasText(jwt)) {
            return jwt;
        }
        return null;
    }
    /**
     * Object to return as body in JWT Authentication.
     */