【问题标题】:Spring security with google Oauth谷歌 Oauth 的 Spring 安全性
【发布时间】:2014-12-09 00:32:59
【问题描述】:

我一直在开发一个使用 Google oauth 和 Spring MVC 的 Web 应用程序。我已经实现了 google oauth,如果用户通过了 google oauth 的身份验证,用户将被定向到所需的 URL。为了实现这个功能,我使用了 google GogleAuthHelper 类。这是我的代码

  package com.mob.googleoauth;

import java.io.IOException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.json.JSONException;
import org.json.JSONObject;

import com.google.api.client.auth.oauth2.AuthorizationCodeRequestUrl;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.auth.oauth2.TokenResponseException;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeRequestUrl;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;

public final class GoogleAuthHelper {

    private static final String CLIENT_ID = "";
    private static final String CLIENT_SECRET = " ";
    /**
     * Callback URI that google will redirect to after successful authentication
     */
    private static final String CALLBACK_URI = "http://localhost:8080/orgchart/oauthRedirect";
    // private static final String HD = " ";

    // start google authentication constants
    private static final Iterable<String> SCOPE = Arrays
            .asList("https://www.googleapis.com/auth/userinfo.profile;https://www.googleapis.com/auth/userinfo.email"
                    .split(";"));
    private static final String USER_INFO_URL = "https://www.googleapis.com/oauth2/v1/userinfo";
    private static final JsonFactory JSON_FACTORY = new JacksonFactory();
    private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
    // end google authentication constants

    private String stateToken;

    private final GoogleAuthorizationCodeFlow flow;

    /**
     * Constructor initializes the Google Authorization Code Flow with CLIENT
     * ID, SECRET, and SCOPE
     */
    public GoogleAuthHelper() {

        System.out.println("google auth helper called");
        flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT,
                JSON_FACTORY, CLIENT_ID, CLIENT_SECRET, SCOPE).build();
        flow.newAuthorizationUrl().setApprovalPrompt("force").setAccessType("offline");
//      AuthorizationCodeRequestUrl authorizationUrl = flow
//              .newAuthorizationUrl().setRedirectUri(CALLBACK_URI)
//              .setApprovalPrompt("force").setAccessType("offline");
        generateStateToken();
    }

    /**
     * Builds a login URL based on client ID, secret, callback URI, and scope
     */
    public String buildLoginUrl() {
        System.out.println("building uri called");
        final GoogleAuthorizationCodeRequestUrl url = flow
                .newAuthorizationUrl();

        return url.setRedirectUri(CALLBACK_URI).setState(stateToken).build();
    }

    /**
     * Generates a secure state token
     */
    private void generateStateToken() {
        System.out.println("generated token called");
        SecureRandom sr1 = new SecureRandom();
        // System.out.println(sr1);
        stateToken = "google;" + sr1.nextInt();

    }

    /**
     * Accessor for state token
     */
    public String getStateToken() {
        System.out.println("gettoken called");
        return stateToken;
    }

    /**
     * Expects an Authentication Code, and makes an authenticated request for
     * the user's profile information
     * 
     * @return JSON formatted user profile information
     * @param authCode
     *            authentication code provided by google
     * @throws JSONException
     */
    @SuppressWarnings("unchecked")
    public List getUserInfoJson(final String authCode,HttpSession session) throws IOException,
            JSONException {
        List ls = new ArrayList();      
        try{
        System.out.println("getuserinfojson called");
        final GoogleTokenResponse response = flow.newTokenRequest(authCode)
                .setRedirectUri(CALLBACK_URI).execute();
        session.setAttribute("userToken", response.getAccessToken());
        final Credential credential = flow.createAndStoreCredential(response,
                null);
        final HttpRequestFactory requestFactory = HTTP_TRANSPORT
                .createRequestFactory(credential);
        // Make an authenticated request
        final GenericUrl url = new GenericUrl(USER_INFO_URL);
        final HttpRequest request = requestFactory.buildGetRequest(url);
        request.getHeaders().setContentType("application/json");
        final String jsonIdentity = request.execute().parseAsString();
        // System.out.println(jsonIdentity);
        JSONObject object = new JSONObject(jsonIdentity);

        String email = object.getString("email");
        String name = object.getString("name");
        String picture = object.getString("picture");


        ls.add(email);
        ls.add(name);
        ls.add(picture);
        }
        catch(NullPointerException e)
        {
            throw e;
        }
        catch (TokenResponseException e) {
            throw e;
        }
        return ls;

    }

}

ABove 在验证用户并重定向到给定 URL 的时候工作正常,但之后应用程序不安全。那是我的应用程序中的 URL 不安全。为此,我想将 spring 安全性与 google oauth 一起包括在内。有没有很好的详细示例可以做到这一点。我已经搜索了谷歌并没有成功。我想要一个很好的 Spring Security 和 google oauth 工作示例。 谢谢你的帮助

【问题讨论】:

    标签: java spring spring-mvc oauth


    【解决方案1】:

    这里我给你几个链接。这对我理解目的很有帮助。希望它也能帮助你。 在this link,您可以选择您想要的类别。考虑到 OAuth 的 Spring Security,你可以检查一下。

    http://docs.spring.io/spring-security/oauth/

    http://www.hsc.com/Portals/0/Uploads/Articles/WP_Securing_RESTful_WebServices_OAuth2635406646412464000.pdf

    http://porterhead.blogspot.in/2014/05/securing-rest-services-with-spring.html

    【讨论】:

      猜你喜欢
      • 2015-03-05
      • 2012-11-22
      • 2015-05-10
      • 2017-03-18
      • 2019-07-26
      • 2018-10-19
      • 2014-05-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多