How to authenticate a mobile App without username and password?

前端 未结 3 1698
清歌不尽
清歌不尽 2021-02-06 16:50

I\'m building a Webapp that uses OpenId to authenticate users, like Stackoverlfow does. There will be a mobile App too, e.g. Android or iPhone. These Apps have to authenticate o

3条回答
  •  野性不改
    2021-02-06 17:18

    I have done the following to achieve this:

    • When the App first starts, I test if there is an authentication token and if it is still valid
    • If not, I use [startActivityForResult][1] to open my login activity
    • The LoginActivity uses a WebView and opens the "authenticate app" page (e.g. https://www.yourdomain.com/authapp) from the web application.
    • If the user is not logged into the webapp, he has to do this now. Upon successful login, he gets redirected to the "authenticate app" page
    • The "authenticate app" page contains the text "would you like the mobile app to access you data" and a "grant" and "cancel" button.
    • If the user hits "grant" the web app generats a authentication token, writes it to the databse and redirects to a response page, attaching the generated authentication token to the URL (e.g. https://www.yourdomain.com/authresponse?auth_token=dshf84z4388f4h)
    • The mobile application extracts the token from the URL and uses it for authentication when talking to the server.

      The WebLogin Activity looks like this: (note: you have to override "shouldOverrideUrlLoading" to stay in the same WebView. Otherwise, a new browser is open when you receive some redirect)

      public class WebLogin extends Activity {

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

      WebView webview = new WebView(this);
      webview.setWebViewClient(new WebViewClient() {  
      
          @Override  
          public boolean shouldOverrideUrlLoading(WebView view, String url){
              view.loadUrl(url);
              return true;  
          }  
      
          @Override
          public void onPageFinished(WebView view, String url) {
      
              if(StringUtils.contains(url, "?auth_token=")){
      
                  // extract and save token here
      
                  setResult(RESULT_OK);
                  finish();
              }
          }
      });
      
      webview.loadUrl("https://www.yourdomain.com/authapp");
      webview.getSettings().setJavaScriptEnabled(true);
      setContentView(webview);
      

      } }

    Note, I use https to make this save. If you use plain http, one could read and steal the token of a user.

    [1]: http://developer.android.com/reference/android/app/Activity.html#startActivityForResult(android.content.Intent, int)

提交回复
热议问题