如何使用spring授权授权我的Google身份验证

时间:2014-10-15 10:11:36

标签: spring spring-mvc spring-security

以下是获取Google身份验证详细信息的代码。我成功进行身份验证,现在我想使用我的谷歌身份验证使用spring security进行授权。这是我的java类

@Configuration
@EnableOAuth2Client
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 = "mobiquityinc.com";

    // 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;

    }

}

这是我的安全xml文件

    <b:beans xmlns:b="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:oauth="http://www.springframework.org/schema/security/oauth2"
       xmlns:sec="http://www.springframework.org/schema/security"
       xsi:schemaLocation="http://www.springframework.org/schema/beans

       http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
       http://www.springframework.org/schema/security
       http://www.springframework.org/schema/security/spring-security-3.2.xsd
       http://www.springframework.org/schema/security/oauth2
       http://www.springframework.org/schema/security/spring-security-oauth2-1.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-3.1.xsd">

<sec:http use-expressions="true" entry-point-ref="clientAuthenticationEntryPoint">
    <sec:http-basic/>
    <sec:logout/>
    <sec:anonymous enabled="false"/>

    <sec:intercept-url pattern="/**" access="isFullyAuthenticated()"/>

    <!-- This is the crucial part and the wiring is very important -->
    <!-- 
        The order in which these filters execute are very important. oauth2ClientContextFilter must be invoked before 
        oAuth2AuthenticationProcessingFilter, that's because when a redirect to Google is required, oAuth2AuthenticationProcessingFilter 
        throws a UserRedirectException which the oauth2ClientContextFilter handles and generates a redirect request to Google.
        Subsequently the response from Google is handled by the oAuth2AuthenticationProcessingFilter to populate the 
        Authentication object and stored in the SecurityContext
    -->
    <sec:custom-filter ref="oauth2ClientContextFilter" after="EXCEPTION_TRANSLATION_FILTER"/>
    <sec:custom-filter ref="oAuth2AuthenticationProcessingFilter" before="FILTER_SECURITY_INTERCEPTOR"/>
</sec:http>

<b:bean id="oAuth2AuthenticationProcessingFilter" class="org.springframework.security.oauth2.client.filter.OAuth2ClientAuthenticationProcessingFilter">
    <b:constructor-arg name="defaultFilterProcessesUrl" value="/orgchart/oauthRedirect"/>
    <b:property name="restTemplate" ref="googleRestTemplate"/>
    <b:property name="tokenServices" ref="tokenServices"/>
</b:bean>

<!--
    These token classes are mostly a clone of the Spring classes but have the structure modified so that the response
    from Google can be handled.
-->
<b:bean id="tokenServices" class="com.rst.oauth2.google.security.GoogleTokenServices">
    <b:property name="checkTokenEndpointUrl" value="https://www.googleapis.com/oauth2/v1/tokeninfo"/>
    <b:property name="clientId" value="${google.client.id}"/>
    <b:property name="clientSecret" value="${google.client.secret}"/>
    <b:property name="accessTokenConverter">
        <b:bean class="com.rst.oauth2.google.security.GoogleAccessTokenConverter">
            <b:property name="userTokenConverter">
                <b:bean class="com.rst.oauth2.google.security.DefaultUserAuthenticationConverter"/>
            </b:property>
        </b:bean>
    </b:property>
</b:bean>

<!-- 
    This authentication entry point is used for all the unauthenticated or unauthorised sessions to be directed to the 
    /googleLogin URL which is then intercepted by the oAuth2AuthenticationProcessingFilter to trigger authentication from 
    Google.
-->
<b:bean id="clientAuthenticationEntryPoint" class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
    <b:property name="loginFormUrl" value="/orgchart/oauthRedirect"/>
</b:bean>

</b:beans>

我如何进行授权......任何帮助都会受到赞赏,因为我长期坚持这个问题

0 个答案:

没有答案