的Oauth 2.0的Andr​​oid授权LinkedIn [英] Oauth 2.0 authorization for LinkedIn in Android

查看:171
本文介绍了的Oauth 2.0的Andr​​oid授权LinkedIn的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即使有来自LinkedIn没有这种特定的Andr​​oid SDK(如Facebook和Twitter SDK为Android).Setting了LinkedIn授权使用OAuth 1.0仍然容易使用:

但其不一样的故事与Oauth2.0授权。没有太多有用的库或Android的具体例子。我试着用这些:

我已经阅读了的Oauth 2.0是更简单的实现比1.0。不过我不能这样做。

  

在对Android的实施Oauth2.0的LinkedIn任何指针?

解决方案

Oauth2.0认证为LinkedIn。

第1步:

  • 注册LinkedIn您的应用程序按照这个文件。并让您的API_KEY和api_secret。

步骤2:

MainActivity:

 公共类MainActivity延伸活动{

/ *常数授权过程* /

/ ****填补这个您的信息********* /
//这是我们的应用程序的公共API密钥
私有静态最后弦乐API_KEY =YOUR_API_KEY;
//这是我们的应用程序的私有API密钥
私有静态最后弦乐SECRET_KEY =YOUR_API_SECRET;
//这是我们要使用任何字符串。这将用于避免跨站请求伪造攻击。你可以在这里生成一个:http://strongpasswordgenerator.com/
私有静态最后弦乐状态=E3ZYKC1T6H2yP4z;
//这是网址LinkedIn验证过程将重定向到。我们可以把任何我们想要以http开头://或https://。
//我们使用由URL重定向时,我们将拦截。避免Uppercases。
私有静态最后弦乐REDIRECT_URI =HTTP://com.amalbit.redirecturl;
/ ************** /

//这些是用于构建URL的常量
私有静态最后弦乐AUTHORIZATION_URL =htt​​ps://www.linkedin.com/uas/oauth2/authorization;
私有静态最后弦乐ACCESS_TOKEN_URL =htt​​ps://www.linkedin.com/uas/oauth2/accessToken;
私有静态最后弦乐SECRET_KEY_PARAM =client_secret;
私有静态最后弦乐RESPONSE_TYPE_PARAM =RESPONSE_TYPE;
私有静态最后弦乐GRANT_TYPE_PARAM =grant_type;
私有静态最后弦乐GRANT_TYPE =authorization_ code;
私有静态最后弦乐RESPONSE_TYPE_VALUE =code;
私有静态最后弦乐CLIENT_ID_PARAM =CLIENT_ID;
私有静态最后弦乐STATE_PARAM =国家;
私有静态最后弦乐REDIRECT_URI_PARAM =redirect_uri;
/ * --------------------------------------- * /
私有静态最后弦乐QUESTION_MARK =?;
私有静态最后弦乐AMPERSAND =&放大器;;
私有静态最后字符串等于==;

私人的WebView web视图;
私人ProgressDialog PD;

@覆盖
保护无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_main);

    //从布局web视图
    web视图=(web视图)findViewById(R.id.main_activity_web_view);

    //要求重点用于web视图
    webView.requestFocus(View.FOCUS_DOWN);

    //显示一个进度对话框向用户
    PD = ProgressDialog.show(这一点,,this.getString(R.string.loading),TRUE);

    //设置自定义Web视图客户端
    webView.setWebViewClient(新WebViewClient(){
          @覆盖
          公共无效onPageFinished(web视图查看,字符串URL){
                //此方法将每次页面加载完成后执行。
                //唯一的,我们要做的就是驳回progressDialog,如果我们表现出任何。
              如果(PD =空&安培;!&安培; pd.isShowing()){
                  pd.dismiss();
              }
          }
        @覆盖
        公共布尔shouldOverrideUrlLoading(web视图查看,串authorizationUrl){
            //此方法将被调用时,验证proccess重定向到我们的RedirectUri。
            //我们将检查URL寻找我们RedirectUri。
            如果(authorizationUrl.startsWith(REDIRECT_URI)){
                Log.i(授权,);
                开放的我们的uri = Uri.parse(authorizationUrl);
                //我们需要从URL authorizationToken和国家的象征。我们必须检查服务返回状态令牌是我们发出的一样。
                //如果没有,则意味着该请求可以是跨站请求伪造的结果,必须被拒绝。
                字符串stateToken = uri.getQueryParameter(STATE_PARAM);
                如果(stateToken == NULL ||!stateToken.equals(州)){
                    Log.e(授权,国家令牌不匹配);
                    返回true;
                }

                //如果用户不允许授权我们的申请中,将authorizationToken为空。
                字符串authorizationToken = uri.getQueryParameter(RESPONSE_TYPE_VALUE);
                如果(authorizationToken == NULL){
                    Log.i(授权,用户不允许授权。);
                    返回true;
                }
                Log.i(授权,获得身份验证令牌:+ authorizationToken);

                //生成的URL请求访问令牌
                字符串accessTokenUrl = getAccessTokenUrl(authorizationToken);
                //我们做一个AsyncTask的请求
                新PostRequestAsyncTask()执行(accessTokenUrl);

            }其他{
                //默认行为
                Log.i(授权,重定向到:+ authorizationUrl);
                webView.loadUrl(authorizationUrl);
            }
            返回true;
        }
    });

    //获取授权网址
    串authUrl = getAuthorizationUrl();
    Log.i(授权,加载验证网址:+ authUrl);
    //将授权网址的web视图
    webView.loadUrl(authUrl);
}

/ **
 *方法生成的URL从服务获得访问令牌
 * @返回网址
 * /
私有静态字符串getAccessTokenUrl(字符串authorizationToken){
    返回ACCESS_TOKEN_URL
            + QUESTION_MARK
            + GRANT_TYPE_PARAM + EQUALS + GRANT_TYPE
            + AMPERSAND
            + RESPONSE_TYPE_VALUE + EQUALS + authorizationToken
            + AMPERSAND
            + CLIENT_ID_PARAM + EQUALS + API_KEY
            + AMPERSAND
            + REDIRECT_URI_PARAM + EQUALS + REDIRECT_URI
            + AMPERSAND
            + SECRET_KEY_PARAM + EQUALS + SECRET_KEY;
}
/ **
 *方法生成的URL从服务获得的授权令牌
 * @返回网址
 * /
私有静态字符串getAuthorizationUrl(){
    返回AUTHORIZATION_URL
            + QUESTION_MARK + RESPONSE_TYPE_PARAM + EQUALS + RESPONSE_TYPE_VALUE
            + AMPERSAND + CLIENT_ID_PARAM + EQUALS + API_KEY
            + AMPERSAND + STATE_PARAM + EQUALS +状态
            + AMPERSAND + REDIRECT_URI_PARAM + EQUALS + REDIRECT_URI;
}

@覆盖
公共布尔onCreateOptionsMenu(功能菜单){
    //充气菜单;这增加了项目操作栏,如果它是present。
    。getMenuInflater()膨胀(R.menu.main,菜单);
    返回true;
}

私有类PostRequestAsyncTask扩展的AsyncTask<字符串,太虚,布尔> {

    @覆盖
    在preExecute保护无效(){
        PD = ProgressDialog.show(MainActivity.this,,MainActivity.this.getString(R.string.loading),TRUE);
    }

    @覆盖
    保护布尔doInBackground(字符串...网址){
        如果(urls.length大于0){
            字符串URL =网址[0];
            HttpClient的HttpClient的=新DefaultHttpClient();
            HttpPost httpost =新HttpPost(URL);
            尝试{
                HTT presponse响应= httpClient.execute(httpost);
                如果(响应!= NULL){
                    //如果状态正常200
                    如果(response.getStatusLine()的getStatus code()== 200){
                        字符串结果= EntityUtils.toString(response.getEntity());
                        //将字符串结果到JSON对象
                        JSONObject的resultJson =新的JSONObject的(结果);
                        从JSON响应//提取数据
                        INT expiresIn = resultJson.has(expires_in)? resultJson.getInt(expires_in):0;

                        字符串accessToken = resultJson.has(access_token)? resultJson.getString(access_token):空;
                        Log.e(Tokenm,+ accessToken);
                        如果(expiresIn大于0&安培;&安培;!accessToken =空){
                            Log.i(授权,这是访问令牌:+ accessToken +,它会在到期+ expiresIn +秒);

                            //计算截止日期
                            台历挂历= Calendar.getInstance();
                            calendar.add(Calendar.SECOND,expiresIn);
                            长EXPIREDATE = calendar.getTimeInMillis();

                            ////同时存储到期和共享preferences访问令牌
                            共享preferences preferences = MainActivity.this.getShared preferences(USER_INFO,0);
                            共享preferences.Editor编辑器= preferences.edit();
                            editor.putLong(到期,EXPIREDATE);
                            editor.putString(accessToken,accessToken);
                            editor.commit();

                            返回true;
                        }
                    }
                }
            }赶上(IOException异常E){
                Log.e(授权,错误HTTP响应+ e.getLocalizedMessage());
            }
            赶上(ParseException的E){
                Log.e(授权,错误解析HTTP响应+ e.getLocalizedMessage());
            }赶上(JSONException E){
                Log.e(授权,错误解析HTTP响应+ e.getLocalizedMessage());
            }
        }
        返回false;
    }

    @覆盖
    保护无效onPostExecute(布尔状态){
        如果(PD =空&安培;!&安培; pd.isShowing()){
            pd.dismiss();
        }
        如果(状态){
            //如果一切正常,换到另一个活动。
            意图startProfileActivity =新的意图(MainActivity.this,ProfileActivity.class);
            MainActivity.this.startActivity(startProfileActivity);
        }
    }

};
}
 

而xmlLayout:

 < LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    的xmlns:工具=htt​​p://schemas.android.com/tool​​s
    机器人:layout_width =match_parent
    机器人:layout_height =match_parent
    机器人:paddingBottom会=@扪/ activity_vertical_margin
    机器人:以下属性来=@扪/ activity_horizo​​ntal_margin
    机器人:paddingRight =@扪/ activity_horizo​​ntal_margin
    机器人:paddingTop =@扪/ activity_vertical_margin
    工具:上下文=MainActivity。>

    <的WebView
        机器人:ID =@ + ID / main_activity_web_view
        机器人:layout_width =match_parent
        机器人:layout_height =match_parent/>

< / LinearLayout中>
 

令牌保存在共享preference文件。

  

简单的Andr​​oid项目回购 href="https://github.com/amalChandran/LinkedInAndroid20">。

Even though there is no such android specific sdk from linkedIn(like facebook and twitter sdk for android).Setting up linkedIn authorization with Oauth 1.0 was still easy using:

But its not the same story for authorization with Oauth2.0. Not too many usefull libraries or android specific examples. I tried using these:

I have read that Oauth 2.0 is much simpler to implement than the 1.0. Still I am not able to do so.

Any pointers towards implementing Oauth2.0 for LinkedIn in Android?

解决方案

Oauth2.0 authentication for LinkedIN.

Step 1:

  • Register your app with linkedIn by following this document. And get your api_key and api_secret.

Step 2:

MainActivity:

public class MainActivity extends Activity {

/*CONSTANT FOR THE AUTHORIZATION PROCESS*/

/****FILL THIS WITH YOUR INFORMATION*********/
//This is the public api key of our application
private static final String API_KEY = "YOUR_API_KEY";
//This is the private api key of our application
private static final String SECRET_KEY = "YOUR_API_SECRET";
//This is any string we want to use. This will be used for avoid CSRF attacks. You can generate one here: http://strongpasswordgenerator.com/
private static final String STATE = "E3ZYKC1T6H2yP4z";
//This is the url that LinkedIn Auth process will redirect to. We can put whatever we want that starts with http:// or https:// .
//We use a made up url that we will intercept when redirecting. Avoid Uppercases. 
private static final String REDIRECT_URI = "http://com.amalbit.redirecturl";
/*********************************************/

//These are constants used for build the urls
private static final String AUTHORIZATION_URL = "https://www.linkedin.com/uas/oauth2/authorization";
private static final String ACCESS_TOKEN_URL = "https://www.linkedin.com/uas/oauth2/accessToken";
private static final String SECRET_KEY_PARAM = "client_secret";
private static final String RESPONSE_TYPE_PARAM = "response_type";
private static final String GRANT_TYPE_PARAM = "grant_type";
private static final String GRANT_TYPE = "authorization_code";
private static final String RESPONSE_TYPE_VALUE ="code";
private static final String CLIENT_ID_PARAM = "client_id";
private static final String STATE_PARAM = "state";
private static final String REDIRECT_URI_PARAM = "redirect_uri";
/*---------------------------------------*/
private static final String QUESTION_MARK = "?";
private static final String AMPERSAND = "&";
private static final String EQUALS = "=";

private WebView webView;
private ProgressDialog pd;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //get the webView from the layout
    webView = (WebView) findViewById(R.id.main_activity_web_view);

    //Request focus for the webview
    webView.requestFocus(View.FOCUS_DOWN);

    //Show a progress dialog to the user
    pd = ProgressDialog.show(this, "", this.getString(R.string.loading),true);

    //Set a custom web view client
    webView.setWebViewClient(new WebViewClient(){
          @Override
          public void onPageFinished(WebView view, String url) {
                //This method will be executed each time a page finished loading.
                //The only we do is dismiss the progressDialog, in case we are showing any.
              if(pd!=null && pd.isShowing()){
                  pd.dismiss();
              }
          }
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String authorizationUrl) {
            //This method will be called when the Auth proccess redirect to our RedirectUri.
            //We will check the url looking for our RedirectUri.
            if(authorizationUrl.startsWith(REDIRECT_URI)){
                Log.i("Authorize", "");
                Uri uri = Uri.parse(authorizationUrl);
                //We take from the url the authorizationToken and the state token. We have to check that the state token returned by the Service is the same we sent.
                //If not, that means the request may be a result of CSRF and must be rejected.
                String stateToken = uri.getQueryParameter(STATE_PARAM);
                if(stateToken==null || !stateToken.equals(STATE)){
                    Log.e("Authorize", "State token doesn't match");
                    return true;
                }

                //If the user doesn't allow authorization to our application, the authorizationToken Will be null.
                String authorizationToken = uri.getQueryParameter(RESPONSE_TYPE_VALUE);
                if(authorizationToken==null){
                    Log.i("Authorize", "The user doesn't allow authorization.");
                    return true;
                }
                Log.i("Authorize", "Auth token received: "+authorizationToken);

                //Generate URL for requesting Access Token
                String accessTokenUrl = getAccessTokenUrl(authorizationToken);
                //We make the request in a AsyncTask
                new PostRequestAsyncTask().execute(accessTokenUrl);

            }else{
                //Default behaviour
                Log.i("Authorize","Redirecting to: "+authorizationUrl);
                webView.loadUrl(authorizationUrl);
            }
            return true;
        }
    });

    //Get the authorization Url
    String authUrl = getAuthorizationUrl();
    Log.i("Authorize","Loading Auth Url: "+authUrl);
    //Load the authorization URL into the webView
    webView.loadUrl(authUrl);
}

/**
 * Method that generates the url for get the access token from the Service
 * @return Url
 */
private static String getAccessTokenUrl(String authorizationToken){
    return ACCESS_TOKEN_URL
            +QUESTION_MARK
            +GRANT_TYPE_PARAM+EQUALS+GRANT_TYPE
            +AMPERSAND
            +RESPONSE_TYPE_VALUE+EQUALS+authorizationToken
            +AMPERSAND
            +CLIENT_ID_PARAM+EQUALS+API_KEY
            +AMPERSAND
            +REDIRECT_URI_PARAM+EQUALS+REDIRECT_URI
            +AMPERSAND
            +SECRET_KEY_PARAM+EQUALS+SECRET_KEY;
}
/**
 * Method that generates the url for get the authorization token from the Service
 * @return Url
 */
private static String getAuthorizationUrl(){
    return AUTHORIZATION_URL
            +QUESTION_MARK+RESPONSE_TYPE_PARAM+EQUALS+RESPONSE_TYPE_VALUE
            +AMPERSAND+CLIENT_ID_PARAM+EQUALS+API_KEY
            +AMPERSAND+STATE_PARAM+EQUALS+STATE
            +AMPERSAND+REDIRECT_URI_PARAM+EQUALS+REDIRECT_URI;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

private class PostRequestAsyncTask extends AsyncTask<String, Void, Boolean>{

    @Override
    protected void onPreExecute(){
        pd = ProgressDialog.show(MainActivity.this, "", MainActivity.this.getString(R.string.loading),true);
    }

    @Override
    protected Boolean doInBackground(String... urls) {
        if(urls.length>0){
            String url = urls[0];
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpost = new HttpPost(url);
            try{
                HttpResponse response = httpClient.execute(httpost);
                if(response!=null){
                    //If status is OK 200
                    if(response.getStatusLine().getStatusCode()==200){
                        String result = EntityUtils.toString(response.getEntity());
                        //Convert the string result to a JSON Object
                        JSONObject resultJson = new JSONObject(result);
                        //Extract data from JSON Response
                        int expiresIn = resultJson.has("expires_in") ? resultJson.getInt("expires_in") : 0;

                        String accessToken = resultJson.has("access_token") ? resultJson.getString("access_token") : null;
                        Log.e("Tokenm", ""+accessToken);
                        if(expiresIn>0 && accessToken!=null){
                            Log.i("Authorize", "This is the access Token: "+accessToken+". It will expires in "+expiresIn+" secs");

                            //Calculate date of expiration
                            Calendar calendar = Calendar.getInstance();
                            calendar.add(Calendar.SECOND, expiresIn);
                            long expireDate = calendar.getTimeInMillis();

                            ////Store both expires in and access token in shared preferences
                            SharedPreferences preferences = MainActivity.this.getSharedPreferences("user_info", 0);
                            SharedPreferences.Editor editor = preferences.edit();
                            editor.putLong("expires", expireDate);
                            editor.putString("accessToken", accessToken);
                            editor.commit();

                            return true;
                        }
                    }
                }
            }catch(IOException e){
                Log.e("Authorize","Error Http response "+e.getLocalizedMessage());  
            }
            catch (ParseException e) {
                Log.e("Authorize","Error Parsing Http response "+e.getLocalizedMessage());
            } catch (JSONException e) {
                Log.e("Authorize","Error Parsing Http response "+e.getLocalizedMessage());
            }
        }
        return false;
    }

    @Override
    protected void onPostExecute(Boolean status){
        if(pd!=null && pd.isShowing()){
            pd.dismiss();
        }
        if(status){
            //If everything went Ok, change to another activity.
            Intent startProfileActivity = new Intent(MainActivity.this, ProfileActivity.class);
            MainActivity.this.startActivity(startProfileActivity);
        }
    }

};
}

And the xmlLayout:

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <WebView
        android:id="@+id/main_activity_web_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

The token is saved in the sharedpreference file.

Simple android project repo here in github.

这篇关于的Oauth 2.0的Andr​​oid授权LinkedIn的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆