簡體   English   中英

如何在Android中獲取JWT和Access Token oAuth for Facebook登錄

[英]How to get JWT and Access Token oAuth for Facebook Login in android

我正在我的Android應用程序中實現Facebook登錄,因為我需要JWT和Access Token oAuth。 獲取令牌需要采取哪些步驟。

@ rahul-kohli和我的申請有類似的問題。 我們有點擔心在Android上存儲facebook訪問令牌的安全性,並決定不使用SDK。 據報道,有些手機被黑客攻擊,因為這些訪問令牌被懶惰的Android開發人員遺留下來。

我們在這個鏈接的幫助下弄明白了。

我們用django rest api框架建立了后端。 您應該通過類似的API獲取您的jwt令牌。 我們將此用於我們的工作。

我們使用Web視圖來調用facebook身份驗證和授權。 檢查上面的鏈接以獲取用於Web視圖的確切URI。

用facebook的url調用其他類:

Intent intent = new Intent (LoginActivity.this, WebViewActivity.class);
intent.putExtra("url",getString(R.string.facebook_auth_url) +"&" +getString(R.string.facebook_redirect_url));   
startActivity(intent);

這將提示Facebook頁面對用戶進行身份驗證。 在成功驗證后,Facebook會將訪問代碼作為附加到重定向URI的參數傳遞。

下面的類調用facebook url,然后該url將您重定向到m.facbook~url,進一步顯示facebook登錄和身份驗證頁面的權限。

它會將您重定向到您的網站,即您之前提供的重定向網址。 進一步在django中驗證代碼

package <your package name>;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import <YOUR_PACKAGE_NAME>.R;

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

import java.util.HashMap;
import java.util.Map;
public class WebViewActivity extends AppCompatActivity {
    private String accessCode="";
    private String serverUrl ="http://<url>";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);
        String url= getIntent().getStringExtra("url");
        System.out.println("url: " + url);

        WebView webview = new WebView(this);
        webview =(WebView) findViewById(R.id.webview);
        webview.setWebViewClient(new MyBrowser());
        webview.loadUrl(url);
    }
    void serverPingJson() throws JSONException {
    // this function sends the access code to the API server to get the JWT token 
        String serverUrl= getString(R.string.api_url)+"authentication/sociallogin/social/jwt_user/facebook/";
        String sendMessage="{ \"clientId\" : \""+ getString(R.string.facebbok_client_id)+"\",\n" +
            "    \"code\" : \""+jwtToken+"\",\n" +
            "    \"redirectUri\" : \""+serverUrl+"\"\n" +
            "}";
        JSONObject jsonObject= new JSONObject(sendMessage);
        JsonObjectRequest postRequest = new JsonObjectRequest(Request.Method.POST, serverUrl,jsonObject,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    // You should see the JWT token in your response here
                    // extract the token and proceed from here on.
                    System.out.println("response 678: "+response.toString())
                    //Redirect to next section or page after you get your token as a reply.
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    error.printStackTrace();
                }
            });
        Volley.newRequestQueue(getBaseContext()).add(postRequest);
    }

    private class MyBrowser extends WebViewClient {
        //This class lets you get the access code
        //Once you authenticate you should get an access code from facebook
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            if(url.contains(serverUrl+"?code=")){
                accessCode=url.replace(serverUrl+"?code=","");
                try {
                    serverPingJson();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            return false;
        }
    }
}

我也在使用Facebook登錄開發應用程序。 如Tobi所述,官方文檔非常有用。

以下是獲取訪問令牌的代碼(來自官方文檔)

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    FacebookSdk.sdkInitialize(this.getApplicationContext());
    callbackManager = CallbackManager.Factory.create();

    accessTokenTracker = new AccessTokenTracker() {
        @Override
        protected void onCurrentAccessTokenChanged(
            AccessToken oldAccessToken,
            AccessToken currentAccessToken) {
                // Set the access token using 
                // currentAccessToken when it's loaded or set.
        }
    };
    // If the access token is available already assign it.
    accessToken = AccessToken.getCurrentAccessToken();
}

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

@Override
public void onDestroy() {
    super.onDestroy();
    accessTokenTracker.stopTracking();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM