7
votes

Comment mettre en œuvre «Connexion avec LinkedIn» avec «OAuth 2.0» sous Android

Dans OAuth1.0 "Connexion avec Linkedin" Fonctionne bien, mais avant quelques jours, Linkedin apporte des modifications à sa politique, veuillez consulter le lien ci-dessous pour plus de détails, https://engineering.linkedin.com/blog/2018/12/developer -mises-à-jour-du-programme

J'ai également essayé des exemples de GitHub et d'autres références mais malheureusement cela ne fonctionne pas pour moi, j'ai également essayé le lien ci-dessous mais cela ne remplissait pas exactement les conditions requises.

Autorisation Oauth 2.0 pour LinkedIn dans Android

Vous pouvez également consulter le lien ci-dessous, peut-il donner un résultat, je sais aussi que le SDK Linkedin ne fonctionne pas ici comme ils l'ont déclaré ici, https://developer.linkedin.com/docs/android-sdk Nous devons appeler l'URL manuelle et ouvrir dans Webview.

https://docs.microsoft.com/en-us/linkedin/consumer/integrations/self-serve/sign-in-with-linkedin?context=linkedin/consumer/context

Je vérifie également 3-4 applications qui prenaient auparavant en charge LinkedIn pour l'authentification, mais maintenant elles l'ont supprimée, mais je vérifie une application à savoir "Nuzzel" en ce sens que j'ai trouvé Linked dans l'authentification et que cela fonctionne bien, cela signifie qu'il y a un moyen de Fais-le proprement. Lien vers l'application Nuzzel: - https://play.google. com / store / apps / details? id = com.nuzzel.android & hl = en_GB

Merci


3 commentaires

Avez-vous une solution?


Oui, mais non, je suis très surpris du processus.


Bonjour, veuillez consulter cet article. ( medium.com/swlh/linkedin-authentication-android- 784‌ 8f4025a65 ) Vous pouvez utiliser le SDK LinkedInManager pour vous connecter facilement à LinkedIn. Veuillez renvoyer les commentaires.


4 Réponses :


0
votes

Voici mon code, pour implémenter la connexion avec "0Auth2.0"

class NewLinkedInIntegration extends Activity {

    private static final String API_KEY = "your client id";
    private static final String SECRET_KEY = "your secret key";
    private static final String STATE = "DCEeFWf45A53sdfKef424";

    private static final String REDIRECT_URI = "your url";
    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 = "=";

    String profileUrl = "https://api.linkedin.com/v2/me?projection=(id,firstName,lastName,profilePicture(displayImage~:playableStreams))";
    String accessToken;
    String linkedInUserEmailAddress;
    SharedPreferences sharedPreferences;
    String emailAddress = "https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))";
    private WebView webView;
    TransparentDialog mProgressBarHandler;
    private ProgressDialog pd;
    String deviceId, location, country;
    String linkedInUserId, linkedInUserFirstName, linkedInUserLastName, linkedInUserProfile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_linked);
        //get the webView from the layout
        webView = (WebView) findViewById(R.id.main_activity_web_view);
        deviceId = getIntent().getStringExtra("deviceId");
        location = getIntent().getStringExtra("location");
        country = getIntent().getStringExtra("country");
        //Request focus for the webview
        webView.requestFocus(View.FOCUS_DOWN);
        webView.clearHistory();
        webView.clearCache(true);
        sharedPreferences = MyApplication.preference;
        pd = ProgressDialog.show(this, "", "Loadingg...", true);
        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;
            }
        });
        String authUrl = getAuthorizationUrl();
        Log.i("Authorize", "Loading Auth Url: " + authUrl);
        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 + "&scope=r_liteprofile%20r_emailaddress%20w_member_social";
    }


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

        @Override
        protected void onPreExecute() {
            pd = ProgressDialog.show(NewLinkedInIntegration.this, "", "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());
                            JSONObject resultJson = new JSONObject(result);
                            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");
                                Calendar calendar = Calendar.getInstance();
                                calendar.add(Calendar.SECOND, expiresIn);
                                long expireDate = calendar.getTimeInMillis();
                                SharedPreferences preferences = NewLinkedInIntegration.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) {
                SharedPreferences preferences = NewLinkedInIntegration.this.getSharedPreferences("user_info", 0);
                accessToken = preferences.getString("accessToken", null);
                try {
                    if (accessToken != null) {
                        new GetProfileRequestAsyncTask().execute(profileUrl);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }

    public void sendGetRequest(String urlString, String accessToken) throws Exception {
        URL url = new URL(urlString);
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("Authorization", "Bearer " + accessToken);
        con.setRequestProperty("cache-control", "no-cache");
        con.setRequestProperty("X-Restli-Protocol-Version", "2.0.0");
        BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
        StringBuilder jsonString = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            jsonString.append(line);
        }
        JSONObject jsonObject = new JSONObject(jsonString.toString());
        Log.d("Complete json object", jsonObject.toString());
        try {
            linkedInUserId = jsonObject.getString("id");
            String country = jsonObject.getJSONObject("firstName").getJSONObject("preferredLocale").getString("country");
            String language = jsonObject.getJSONObject("firstName").getJSONObject("preferredLocale").getString("language");
            String getFirstnameKey = language + "_" + country;
            linkedInUserFirstName = jsonObject.getJSONObject("firstName").getJSONObject("localized").getString(getFirstnameKey);
            linkedInUserLastName = jsonObject.getJSONObject("firstName").getJSONObject("localized").getString(getFirstnameKey);
            linkedInUserProfile = jsonObject.getJSONObject("profilePicture").getJSONObject("displayImage~").getJSONArray("elements").getJSONObject(0).getJSONArray("identifiers").getJSONObject(0).getString("identifier");

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    private void sendGetRequestForEmail(String urlString, String accessToken) throws Exception {
        URL url = new URL(urlString);
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("Authorization", "Bearer " + accessToken);
        con.setRequestProperty("cache-control", "no-cache");
        con.setRequestProperty("X-Restli-Protocol-Version", "2.0.0");
        BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
        StringBuilder jsonString = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            jsonString.append(line);
        }
        JSONObject jsonObject = new JSONObject(jsonString.toString());
        linkedInUserEmailAddress = jsonObject.getJSONArray("elements").getJSONObject(0).getJSONObject("handle~").getString("emailAddress");
        Log.d("email json object", jsonObject.toString());
        sendRequestToServerForLinkwedInIntegration();


    }

    public void sendRequestToServerForLinkwedInIntegration() {

        if (AppUtils.isInternetOn(NewLinkedInIntegration.this)) {

            JSONObject userJsonObject = new JSONObject();
            try {
                userJsonObject.put(NetworkKeys.EMAIL, linkedInUserEmailAddress);
                userJsonObject.put(NetworkKeys.USERNAME, linkedInUserFirstName + " " + linkedInUserLastName);
                userJsonObject.put(NetworkKeys.CONTACTNO, "");
                userJsonObject.put(NetworkKeys.UID, linkedInUserId);
                userJsonObject.put(NetworkKeys.PROVIDER, "LinkedIn");
                userJsonObject.put(NetworkKeys.IMAGE, linkedInUserProfile);
                userJsonObject.put(NetworkKeys.DEVICE_TOKEN, deviceId);
                userJsonObject.put(NetworkKeys.LOCATION, location);
                userJsonObject.put(NetworkKeys.COUNTRY, country);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            String url = Constants.WebServices.SOCIAL_MEDIA_LOGIN;
            CallWebService.getInstance(NewLinkedInIntegration.this, true).hitJSONObjectVolleyWebServicemanageclubdetailsWithoutAccessToken(Request.Method.POST, url, deviceId, userJsonObject, new CallBackInterfaceVolley() {
                @Override
                public void onJsonObjectSuccess(JSONObject object) {
                    pd.dismiss();
                    try {
                        boolean success = object.getBoolean(NetworkKeys.SUCCESS);

                        if (success) {
                            JSONObject userInfoJsonObject = object.getJSONObject(NetworkKeys.USERJSONOBJECT);
                            String userId = userInfoJsonObject.getString(NetworkKeys.SIGN_IN_USERID);
                            String userEmail = userInfoJsonObject.getString(NetworkKeys.SIGN_IN_USER_EMAIL);
                            String userImage = userInfoJsonObject.getString(NetworkKeys.SIGN_IN_USER_IMAGE);
                            String userName = userInfoJsonObject.getString(NetworkKeys.SIGN_IN_USER_NAME);
                            String userCity = userInfoJsonObject.getString(NetworkKeys.USER_CITY);
                            String contactNo = userInfoJsonObject.getString(NetworkKeys.CONTACT_NO);
                            String userCountry = userInfoJsonObject.getString(NetworkKeys.USER_COUNTRY);
                            String isNotificationOn = userInfoJsonObject.getString(NetworkKeys.ISNOTIFICATION);
                            String userLocation = userInfoJsonObject.getString(NetworkKeys.SIGN_IN_USER_LOCATION);
                            String signInUserType = userInfoJsonObject.getString(NetworkKeys.SIGN_IN_USER_PROVIDER);
                            String userAuthToken = userInfoJsonObject.getString(NetworkKeys.SIGN_IN_USER_AUTHTOKEN);
                            SharedPreferences.Editor editor = sharedPreferences.edit();
                            editor.putString(NetworkKeys.SIGN_IN_USERID, userId);
                            editor.putString(NetworkKeys.SIGN_IN_USER_EMAIL, userEmail);
                            editor.putString(NetworkKeys.SIGN_IN_USER_IMAGE, userImage);
                            editor.putString(NetworkKeys.SIGN_IN_USER_NAME, userName);
                            editor.putString(NetworkKeys.USER_CITY, userCity);
                            editor.putString(NetworkKeys.USER_COUNTRY, userCountry);
                            editor.putString(NetworkKeys.SIGN_IN_USER_MOBILE, contactNo);
                            editor.putString(NetworkKeys.SIGN_IN_USER_LOCATION, userLocation);
                            editor.putString(NetworkKeys.SIGN_IN_USER_PROVIDER, signInUserType);
                            editor.putString(NetworkKeys.ISNOTIFICATION, isNotificationOn);
                            editor.putString(NetworkKeys.SIGN_IN_USER_AUTHTOKEN, userAuthToken);
                            editor.putBoolean(NetworkKeys.IS_USER_LOGIN_FROM_SOCIAL_MEDIA, true);
                            editor.putBoolean(NetworkKeys.SIGN_IN_USER_SUCCESSFULLY, true);
                            editor.apply();
                            Intent intent = new Intent(NewLinkedInIntegration.this, CardSelctionActivity.class);
                            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                            finish();
                        } else {
                            pd.dismiss();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onJsonArrarSuccess(JSONArray array) {

                }

                @Override
                public void onFailure(String str) {
                    pd.dismiss();
                }
            });
        } else {
            AppUtils.showToast(NewLinkedInIntegration.this, getResources().getString(R.string.internet_connection));
        }
    }


    private class GetProfileRequestAsyncTask extends AsyncTask<String, Void, JSONObject> {

        @Override
        protected void onPreExecute() {
            pd = ProgressDialog.show(NewLinkedInIntegration.this, "", "Loading..", true);
        }

        @Override
        protected JSONObject doInBackground(String... urls) {
            if (urls.length > 0) {
                try {
                    sendGetRequest(profileUrl, accessToken);
                    sendGetRequestForEmail(emailAddress, accessToken);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(JSONObject data) {
            if (pd != null && pd.isShowing()) {
                pd.dismiss();
            }
            if (data != null) {

                try {
                    String welcomeTextString = String.format("Welcome %1$s %2$s, You are a %3$s", data.getString("firstName"), data.getString("lastName"), data.getString("headline"));

                } catch (JSONException e) {
                    Log.e("Authorize", "Error Parsing json " + e.getLocalizedMessage());
                }
            }
        }

    }
}

Si vous souhaitez obtenir de l'aide, consultez le lien ci-dessous expliquant comment vous connecter avec Linkedin avec l'authentification 2.0. Jetez un œil

intégration de linkedin avec l'implémentation oauth20 -v2-in-complete dans Android


4 commentaires

Pourquoi vous postez lorsque la réponse précédente a été supprimée par mode en tant que réponse de lien seulement.


Pouvez-vous s'il vous plaît me dire la raison pour laquelle le mode a supprimé ma réponse


Aryan Dhankar, bien que ce lien puisse répondre à la question, il est préférable d'inclure les parties essentielles de la réponse ici et de fournir le lien pour référence. Les réponses qui ne sont guère plus qu'un lien peuvent être supprimées.


ok.Merci Mais mon lien comprend le code de travail de connexion LinkedIn avec auth2.0. Et j'ai pensé que cela serait également utile pour d'autres développeurs, qui tentent de mettre en œuvre la connexion avec LinkedIn. si je mets mon code ici, est-ce que ce serait légal ou légitime, je demande



3
votes

Après un petit effort, je l'ai fait fonctionner, mais son implémentation à chaque fois que vous démarrez un nouveau projet vous fera perdre beaucoup de temps.

J'ai donc créé une version légère library pour le même.

Ajoutez simplement la dépendance au fichier build.gradle au niveau de votre application

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == LINKEDIN_REQUEST_CODE && data != null) {
            if (resultCode == RESULT_OK) {
                //Successfully signed in
                LinkedInUser user = data.getParcelableExtra("social_login");

                //acessing user info
                Log.i("LinkedInLogin", user.getFirstName());

            } else {

                if (data.getIntExtra("err_code", 0) == LinkedInBuilder.ERROR_USER_DENIED) {
                    //Handle : user denied access to account

                } else if (data.getIntExtra("err_code", 0) == LinkedInBuilder.ERROR_FAILED) {

                    //Handle : Error in API : see logcat output for details
                    Log.e("LINKEDIN ERROR", data.getStringExtra("err_message"));
                }
            }
        }

    }

Lancez la demande de connexion.

XXX

Gérez la réponse:

LinkedInBuilder.getInstance(MainActivity.this)
        .setClientID("<YOUR_CLIENT_ID_HERE>")
        .setClientSecret("<YOUR_CLIENT_SECRET_HERE>")
        .setRedirectURI("<YOUR_REDIRECT_URL_HERE>")
        .authenticate(LINKEDIN_REQUEST_CODE);

J'utilise cette bibliothèque dans plusieurs applications de production, je vais donc essayer de la garder à jour que possible. Vous pouvez trouver d'autres détails ici .


2 commentaires

La fonctionnalité de déconnexion n'est pas ajoutée. Y a-t-il un moyen de se déconnecter?


Auparavant, il existait un moyen d'invalider le jeton d'authentification, mais cela ne fonctionne plus. LinkedIn n'autorise pas non plus les applications tierces à déconnecter l'utilisateur, consultez cette réponse pour plus d'informations stackoverflow.com/a/7765590/2035645 < / a>



1
votes

J'ai créé une petite bibliothèque pour implémenter l'authentification LinkedIn via OAuth2

Bibliothèque - https: //github.com/Sumudu-Sahan/LinkedInManager

  1. Ajoutez la dépendance maven ci-dessous au fichier build.gradle au niveau de votre projet

    tous les projets { dépôts { ... maven {url 'https://jitpack.io'} } }

  2. ajoutez la dépendance maven ci-dessous au fichier build.gradle au niveau de votre application

    dépendances { implémentation 'com.github.Sumudu-Sahan: LinkedInManager: 1.00.02' }

  3. Hériter de votre activité, fragment de LinkedInManagerResponse

    La classe publique MainActivity étend AppCompatActivity implémente LinkedInManagerResponse

  4. Lancez l'instance d'objet LinkedInRequestManager pour le processus de connexion

    LinkedInRequestManager linkedInRequestManager = new LinkedInRequestManager (Activity, LinkedInManagerResponse, "CLIENT ID", "CLIENT SECRET", "REDIRECTION URL");

  5. Commencez à vous authentifier avec la déclaration ci-dessous

linkedInRequestManager.showAuthenticateView(LinkedInRequestManager.MODE_BOTH_OPTIONS);

Modes disponibles

LinkedInRequestManager.MODE_EMAIL_ADDRESS_ONLY
LinkedInRequestManager.MODE_LITE_PROFILE_ONLY
LinkedInRequestManager.MODE_BOTH_OPTIONS


3 commentaires

Belle explication Bro


Nous pouvons nous connecter avec le code, mais vous n'avez pas fourni de fonctionnalité de déconnexion


Salut @Ajeett, veuillez vérifier avec la dernière version des dépendances (V1.01.00)



0
votes

Inspiré par @Shantanu, j'ai restructuré / mis à jour son SDK "non officiel" pour Android, vous pouvez l'utiliser à partir de [ce dépôt GitHub] ( https://github.com/AbdAllahAbdElFattah13/LinkedIn-SDK-Android .

Il est maintenant basé sur Kotlin et suit les principes d'architecture propre pour une meilleure compréhension et des modifications.

Nous l'utilisons également dans nos applications de production, il devrait donc fonctionner correctement. :)


0 commentaires