Created
April 24, 2020 05:38
-
-
Save jwenjian/b763516ed76a7ebe0e6dbdf1f412de52 to your computer and use it in GitHub Desktop.
gRPC java server use username/password authentication to protect service invocation
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
@SpringBootApplication | |
public class GrpcDemoApplication implements CommandLineRunner { | |
@Autowired | |
private HelloServiceGrpc.HelloServiceImplBase helloServiceGrpc; | |
@Autowired | |
private UsernamePasswordAuthenticator usernamePasswordAuthenticator; | |
public static void main(String[] args) { | |
SpringApplication.run(GrpcDemoApplication.class, args); | |
} | |
@Override | |
public void run(String... args) throws Exception { | |
Server server = ServerBuilder.forPort(8003) | |
.intercept(usernamePasswordAuthenticator) | |
.addService(helloServiceGrpc) | |
.build() | |
.start(); | |
System.out.println("gRPC server started on port 8003"); | |
server.awaitTermination(); | |
} | |
} |
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
@Component | |
public class UsernamePasswordAuthenticator implements ServerInterceptor { | |
@Override | |
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> serverCall, Metadata metadata, ServerCallHandler<ReqT, RespT> serverCallHandler) { | |
String username = metadata.get(Metadata.Key.of("username", new StringMetaDataMarshaller())); | |
String passwordMeta = metadata.get(Metadata.Key.of("password", new StringMetaDataMarshaller())); | |
// hard coded username and password, just for prototype | |
if (Objects.equals("root", username) && Objects.equals("rootpwd", passwordMeta)) { | |
return serverCallHandler.startCall(serverCall, metadata); | |
} else { | |
serverCall.close(Status.UNAUTHENTICATED, metadata); | |
return serverCallHandler.startCall(serverCall, metadata); | |
} | |
} | |
class StringMetaDataMarshaller implements Metadata.AsciiMarshaller<String> { | |
@Override | |
public String toAsciiString(String s) { | |
return s; | |
} | |
@Override | |
public String parseAsciiString(String s) { | |
return s; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment