如何使用从GoogleAuthUtil获取的令牌和Web API 2默认模板项目

时间:2015-05-07 08:56:53

标签: android asp.net-mvc asp.net-web-api google-oauth asp.net-web-api2

我的目的是使用Google进行身份验证,然后通过身份验证访问我的资源服务器(使用Web API 2编写)。

我可以从Google获取我在Google的开发者控制台中创建的ClientID的身份验证令牌。这是执行它的代码(礼貌:http://www.riskcompletefailure.com/2013/11/client-server-authentication-with-id.html):

private class RetrieveIdTokenTask extends AsyncTask<String, Void, String>  {
    protected String doInBackground(String... params) {
        String account = params[0];
        String homeServerClient = "276706532100-mygoogleclient.apps.googleusercontent.com";
        try {
            String scope = "audience:server:client_id:" + homeServerClient;
            final String token = GoogleAuthUtil.getToken(LoginActivity.this, account, scope);
            return token;
        } catch (GooglePlayServicesAvailabilityException playEx) {
            // In this case you could prompt the user to upgrade.
        } catch (UserRecoverableAuthException userAuthEx) {
            // This should not occur for ID tokens.
        } catch (IOException transientEx) {
            // You could retry in this case.
        } catch (GoogleAuthException authEx) {
            // General auth error.
        }
        return null;
    }

    protected void onPostExecute(String result){
        Log.d("Token", result);
    }
}



@Override
public void onConnected(Bundle bundle) {
    // get the email address
    Person currentPerson = Plus.PeopleApi
            .getCurrentPerson(mGoogleApiClient);
    String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
    new RetrieveIdTokenTask().execute(email);

}

到目前为止一切顺利,但问题出在此处:

获得令牌之后,我在fiddler中使用它将它发送到ValuesController。默认模板中的ValuesController具有[Authorize]属性,我认为以下应该授权请求:

  1. 取消注释以下行并在Startup.Auth.cs中添加缺少的详细信息。

        app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
        {
            ClientId = "276706532100-mygoogleclient.apps.googleusercontent.com",
            ClientSecret = "nbQjjRnivx1hjmQnkuBEbhbj"
        });
    
  2. 在HTTP请求中发送令牌为&#34;授权&#34;头

  3. 但它没有工作,我继续获得401(未经授权)。以下是我的小提琴请求的样子:

    **URL :** 
    http://localhost:60864/api/values/
    
    **Header section:**
    User-Agent: Fiddler
    authorization: bearer eyJhbGc...REMOVED FOR BREVITY..iOiJSUzI1NiIsIzuhlgIE-ZC5mlmyNnpXEOP2qplbYCmw
    content-type: application/json
    Host: localhost:60864
    

    任何想法,我错过了什么?我感觉我要么是如此接近并且错过了最后一小步,要么我完全错了:)

    帮助!

0 个答案:

没有答案