Created
December 18, 2019 02:36
-
-
Save thinhdanggroup/4a91991816635719765e0a7d21ae6a6d to your computer and use it in GitHub Desktop.
authenticate interceptor grpc
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
import io.grpc.*; | |
import lombok.extern.slf4j.Slf4j; | |
import org.lognet.springboot.grpc.GRpcGlobalInterceptor; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.core.annotation.Order; | |
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; | |
import org.springframework.security.core.context.SecurityContextHolder; | |
import org.springframework.util.StringUtils; | |
import static com.google.common.base.Strings.nullToEmpty; | |
/** | |
* Created by thinhda. | |
* Date: 2019-07-24 | |
*/ | |
@GRpcGlobalInterceptor | |
@Order(50) | |
@Slf4j | |
public class GRpcAuthenticationInterceptor implements ServerInterceptor { | |
@Autowired | |
private JwtTokenProvider tokenProvider; | |
@Autowired | |
private CustomUserDetailsService customUserDetailsService; | |
@Override | |
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) { | |
String authHeader = nullToEmpty(headers.get(Metadata.Key.of("Authorization", Metadata.ASCII_STRING_MARSHALLER))); | |
if (!authHeader.startsWith("Bearer ")) { | |
return next.startCall(call, headers); | |
} | |
try { | |
String token = authHeader.replace("Bearer ", ""); | |
if (StringUtils.hasText(token) && tokenProvider.validateToken(token)) { | |
UsernamePasswordAuthenticationToken authenticationToken = tokenProvider.getUserInfoFromJWT(token); | |
authenticationToken.setDetails(customUserDetailsService.loadUserByUsername(authenticationToken.getPrincipal().toString())); | |
SecurityContextHolder.getContext().setAuthentication(authenticationToken); | |
} | |
} catch (Exception e) { | |
SecurityContextHolder.clearContext(); | |
log.debug("Authentication request failed: {}", e.getMessage()); | |
throw Status.UNAUTHENTICATED.withDescription(e.getMessage()).withCause(e).asRuntimeException(); | |
} | |
return next.startCall(call, headers); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment