Spring MVC:使用API​​登录google +

时间:2015-03-25 15:36:56

标签: java spring google-api google-plus google-api-java-client

我正在开发一个Spring-MVC应用程序,我希望在其中集成Google+登录功能。在此之前,通过一些帮助形成了很好的人,我设法实现了Google日历功能。

现在,当我尝试使用Google+登录时,我有两个选项,可以使用PHP代码,也可以使用Javascript和其他一些后端选项。

我的观点是,Google Calendar实现还需要用户授权,但我能够完全用Java做到这一点,而我在Java中无法做到这一点,因为我找不到任何相关代码。我只想调用java方法,它在浏览器中打开一个新选项卡,用户点击接受,然后我被重定向到URI(类似于谷歌日历,我将在下面发布)

任何人都可以帮助我理解为什么我发现的唯一代码在嵌入式服务器中运行,如果没有它我就无法运行。非常感谢。

日历代码:

public void authorizeAndTest(){

        try {
            httpTransport = new NetHttpTransport();
            dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);
            Credential credential = authorize();

            client = new com.google.api.services.calendar.Calendar.Builder(httpTransport,JSON_FACTORY,credential).setApplicationName(APPLICATION_NAME).build();
            showCalenders();
            addCalendarsUsingBatch();
            Calendar calendar = addCalendar();
            updateCalendar(calendar);
            addEvent(calendar);
            showEvents(calendar);
            deleteCalendarInBatch();
            deleteCalendar(calendar);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 private static Credential authorize() throws Exception{

        AuthorizationCodeFlow codeFlow = new GoogleAuthorizationCodeFlow(httpTransport,JSON_FACTORY,
                "clientid",
                "clientsecret", Collections.singleton(CalendarScopes.CALENDAR));


 return new AuthorizationCodeInstalledApp(codeFlow,new LocalServerReceiver()).authorize("user@gmail.com");
        }

现在上面的代码就像一个魅力,我只是调用我的控制器方法,它调用authorizeAndTest,没有任何问题,它打开一个选项卡,我点击接受,然后启动该过程。

欢迎使用Google+登录:以下代码来自示例:

 public static void main(String[] args) throws Exception {
    Server server = new Server(4567);
    ServletHandler servletHandler = new ServletHandler();
    SessionHandler sessionHandler = new SessionHandler();
    sessionHandler.setHandler(servletHandler);
    server.setHandler(sessionHandler);
    servletHandler.addServletWithMapping(ConnectServlet.class, "/connect");
    servletHandler.addServletWithMapping(DisconnectServlet.class, "/disconnect");
    servletHandler.addServletWithMapping(PeopleServlet.class, "/people");
    servletHandler.addServletWithMapping(MainServlet.class, "/");
    server.start();
    server.join();
  }

public static class MainServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
      // This check prevents the "/" handler from handling all requests by default
      if (!"/".equals(request.getServletPath())) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;
      }

      response.setContentType("text/html");
      try {
        // Create a state token to prevent request forgery.
        // Store it in the session for later validation.
        String state = new BigInteger(130, new SecureRandom()).toString(32);
        request.getSession().setAttribute("state", state);
        // Fancy way to read index.html into memory, and set the client ID
        // and state values in the HTML before serving it.
        response.getWriter().print(new Scanner(new File("index.html"), "UTF-8")
            .useDelimiter("\\A").next()
            .replaceAll("[{]{2}\\s*CLIENT_ID\\s*[}]{2}", CLIENT_ID)
            .replaceAll("[{]{2}\\s*STATE\\s*[}]{2}", state)
            .replaceAll("[{]{2}\\s*APPLICATION_NAME\\s*[}]{2}",
                APPLICATION_NAME)
            .toString());
        response.setStatus(HttpServletResponse.SC_OK);
      } catch (FileNotFoundException e) {
        // When running the quickstart, there was some path issue in finding
        // index.html.  Double check the quickstart guide.
        e.printStackTrace();
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        response.getWriter().print(e.toString());
      }
    }
  }

所以,据我所知,我不能在Controller中调用类,并且对index.html的依赖是一个问题,所以我修改了一下代码。

GoogleSignin.java

  public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            // This check prevents the "/" handler from handling all requests by default
            if (!"/".equals(request.getServletPath())) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            }

            response.setContentType("text/html");
            try {
   String state = new BigInteger(130, new SecureRandom()).toString(32);
                request.getSession().setAttribute("state", state);
   response.setStatus(HttpServletResponse.SC_OK);
            } catch (Exception e) {
                // When running the quickstart, there was some path issue in finding
                // index.html.  Double check the quickstart guide.
                e.printStackTrace();
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                response.getWriter().print(e.toString());
            }
        }

  public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.setContentType("application/json");


            String tokenData = (String) request.getSession().getAttribute("token");
            System.out.println("Tokendata is "+tokenData);
            if (tokenData != null) {
                response.setStatus(HttpServletResponse.SC_OK);
                response.getWriter().print(GSON.toJson("Current user is already connected."));
                return;
            }

            if (!request.getParameter("state").equals(request.getSession().getAttribute("state"))) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.getWriter().print(GSON.toJson("Invalid state parameter."));
                return;
            }

            System.out.println("Request is "+request.toString());
            ByteArrayOutputStream resultStream = new ByteArrayOutputStream();
            getContent(request.getInputStream(), resultStream);
            String code = new String(resultStream.toByteArray(), "UTF-8");

            try {
                GoogleTokenResponse tokenResponse =
                        new GoogleAuthorizationCodeTokenRequest(TRANSPORT, JSON_FACTORY,
                                CLIENT_ID, CLIENT_SECRET, code, "postmessage").execute();

                GoogleIdToken idToken = tokenResponse.parseIdToken();
                String gplusId = idToken.getPayload().getSubject();
                System.out.println("Response from google plus is "+gplusId);

                request.getSession().setAttribute("token", tokenResponse.toString());
                response.setStatus(HttpServletResponse.SC_OK);
                response.getWriter().print(GSON.toJson("Successfully connected user."));
            } catch (TokenResponseException e) {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.getWriter().print(GSON.toJson("Failed to upgrade the authorization code."));
            } catch (IOException e) {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.getWriter().print(GSON.toJson("Failed to read token data from Google. " +
                        e.getMessage()));
            }
        }

控制器代码如下:

@RequestMapping(value = "/authorize")
    public String googleReplyManagment(HttpServletRequest request, HttpServletResponse response){
        //OAuth oAuth = new OAuth();
        //oAuth.authorizeAndTest();
        response.setContentType("application/json");

        GoogleSignIn googleSignIn = new GoogleSignIn();
        try {
            googleSignIn.doGet(request,response);
            googleSignIn.doPost(request,response);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/";
    }

我收到以下错误:

错误代码:

java.lang.NullPointerException
    at com.journaldev.spring.utility.GoogleSignIn.doPost(GoogleSignIn.java:127)
    at com.journaldev.spring.controller.PersonController.googleReplyManagment(PersonController.java:1453)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)

我能做些什么,任何帮助都会很好。非常感谢。

0 个答案:

没有答案