使用OAuth2的Google授权

时间:2018-10-22 04:47:38

标签: java spring-boot oauth google-oauth jetty-8

我正在使用Google OAuth2授权我的Web应用程序使用Google Analytics(分析)API。我使用以下依赖关系来实现这一目标。

    <dependency>
        <groupId>com.google.apis</groupId>
        <artifactId>google-api-services-analytics</artifactId>
        <version>v3-rev159-1.25.0</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.google.oauth-client/google-oauth-client-jetty -->
    <dependency>
        <groupId>com.google.oauth-client</groupId>
        <artifactId>google-oauth-client-jetty</artifactId>
        <version>1.26.0</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.google.oauth-client/google-oauth-client-java6 -->
    <dependency>
        <groupId>com.google.oauth-client</groupId>
        <artifactId>google-oauth-client-java6</artifactId>
        <version>1.26.0</version>
    </dependency>

在测试时,我发现Jetty服务器总是在我们给定的端口(即我给定的8080)上启动服务器。

如果该端口已经由我的应用程序启动,那么它将产生错误。

有人可以建议一种方法吗?我已经在互联网上搜索了一个解决方案,但徒劳无功。

下面给出了调用服务器的代码部分

/** Authorizes the installed application to access user's protected data. */
private static Credential authorize() throws Exception {
    // load client secrets
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(
            JSON_FACTORY, new InputStreamReader(
                    test.class.getResourceAsStream("/client_secrets.json")));

    // set up authorization code flow
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            httpTransport, JSON_FACTORY, clientSecrets,
            Collections.singleton(AnalyticsScopes.ANALYTICS_READONLY)).setAccessType("offline").setDataStoreFactory(
            dataStoreFactory).build();
    // authorize
    LocalServerReceiver localServerReceiver=new LocalServerReceiver.Builder().setHost("localhost").setPort(8080).setCallbackPath("/google/connect/return").setLandingPages(null,null).build();
    return new AuthorizationCodeInstalledApp(flow, localServerReceiver).authorize("user12009");
}

那是LocalServerReceiver。

我已附上错误日志:

Caused by: java.net.BindException: Address already in use (Bind failed)
at java.net.PlainSocketImpl.socketBind(Native Method)
at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:387)
at java.net.ServerSocket.bind(ServerSocket.java:375)
at java.net.ServerSocket.<init>(ServerSocket.java:237)
at org.mortbay.jetty.bio.SocketConnector.newServerSocket(SocketConnector.java:80)
at org.mortbay.jetty.bio.SocketConnector.open(SocketConnector.java:73)
at org.mortbay.jetty.AbstractConnector.doStart(AbstractConnector.java:283)
at org.mortbay.jetty.bio.SocketConnector.doStart(SocketConnector.java:147)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at org.mortbay.jetty.Server.doStart(Server.java:235)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)

发生此错误,因为我的应用程序已使用该端口。有什么方法可以配置不需要再次启动端口的Jetty服务器?还是有人可以建议采用其他任何方法来实现这一目标?

1 个答案:

答案 0 :(得分:0)