简体   繁体   English

Android中的基本认证登录

[英]Basic Authentication Login in Android

First of all: I'm new to programming and this is a school project.首先:我是编程新手,这是一个学校项目。

My Problem: I've got a basic login mask using strings to save the users credentials.我的问题:我有一个使用字符串保存用户凭据的基本登录掩码。 The credentials, if true, are saved via SharedPrefences.凭据(如果为真)通过 SharedPrefences 保存。 Now I want to compare the users input to the Basic Authentication credentials of my webserver http://fost19.tk/ (user: fost19, pw: 12345) to log the user into the app or give him an error message.现在我想将用户输入与我的网络服务器http://fost19.tk/ (用户:fost19,密码:12345)的基本身份验证凭据进行比较,以将用户登录到应用程序或给他一条错误消息。 Everything is working so far, but I'm stuck at connecting to my webserver and comparing the credentials.到目前为止一切正常,但我坚持连接到我的网络服务器并比较凭据。

I've read some questions on the internet, but to be honest I am completely lost right now, which is the best method to achieve this in the current android build.我在互联网上阅读了一些问题,但老实说我现在完全迷失了,这是在当前 android 版本中实现这一目标的最佳方法。 I'm aware that I need to decrypt the given credentials from my webserver, but I don't know how to do this in Java and I don't know which "plugins" need to be added to my project.我知道我需要从我的网络服务器解密给定的凭据,但我不知道如何在 Java 中执行此操作,也不知道需要将哪些“插件”添加到我的项目中。

Thanks for your help: :)谢谢你的帮助: :)

In the next step you probably want to download the content from your website and process it in the app.在下一步中,您可能希望从您的网站下载内容并在应用程序中进行处理。 First of all, your app needs the permission Internet.首先,您的应用程序需要 Internet 权限。 Add the following line to your manifest file below the application tag:将以下行添加到应用程序标记下方的清单文件中:

<uses-permission android:name="android.permission.INTERNET" />

Your website requires http authentication.您的网站需要 http 身份验证。 To do this, you need to include your username and password in the headers of your request.为此,您需要在请求的标题中包含您的用户名和密码。 However, Android does not allow syncronous network traffic.但是,Android 不允许同步网络流量。 Therefore we download the content from the website in the background and can then update the user interface via a callback.因此,我们在后台从网站下载内容,然后可以通过回调更新用户界面。 You can add my class DownloadContent to your project:您可以将我的 class 下载内容添加到您的项目中:

import android.os.AsyncTask;
import android.util.Base64;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import javax.net.ssl.HttpsURLConnection;

public class DownloadContent extends AsyncTask<String, Void, String> {
private final Callback callback;
private final String username, password;

private DownloadContent(@NonNull String username, @NonNull String password, @NonNull Callback callback) {
    this.callback = callback;
    this.username = username;
    this.password = password;
}

public static void run(@NonNull String username, @NonNull String password, @NonNull Callback callback) {
    DownloadContent loader = new DownloadContent(username, password, callback);
    // runs doInBackground asynchronous
    loader.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}

@Override
protected String doInBackground(String... strings) {
    try {
        String credentials = username + ":" + password;
        URL url = new URL ("https://vertretungsplanbbscux.000webhostapp.com/auth/index.html");
        // encode to 64 encoded string (necessary for authorization header)
        String base64 = Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
        // perform a post request
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        // append encoded username and password as authorization header
        connection.setRequestProperty  ("Authorization", "Basic " + base64);
        InputStream stream = connection.getInputStream();
        BufferedReader reader = new BufferedReader (new InputStreamReader(stream));
        String inputLine;
        StringBuilder response = new StringBuilder();
        // read html of website
        while ((inputLine = reader.readLine()) != null)
            response.append(inputLine);
        reader.close();
        return response.toString();
    } catch(Exception e) {
        e.printStackTrace();
    }
    // return null if an error has occurred
    return null;
}

@Override
protected void onPostExecute(@Nullable String content) {
    // called after doInBackground has finished, synchronous again
    if (content == null) {
        callback.onNotLoaded();
    } else {
        callback.onLoaded(content);
    }
}

public interface Callback {
    void onLoaded(String content);
    void onNotLoaded();
}
}

Here is how you can access the content:以下是访问内容的方法:

DownloadContent.run("fost19", "12345", new DownloadContent.Callback() {
        @Override
        public void onLoaded(String content) {
            Log.d("DownloadContent", content);
            //TODO display content in user interface
        }

        @Override
        public void onNotLoaded() {
            Log.d("DownloadContent", "could not fetch content from website");
            // TODO show error message
        }
    });

I hope that I could help you with your substitution plan app.我希望我可以帮助您使用替代计划应用程序。

Edit1: You should only use a secure connection (https). Edit1:您应该只使用安全连接(https)。 So instead of using your.tk address, I used the actual secure address from your website.因此,我没有使用 your.tk 地址,而是使用了您网站上的实际安全地址。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM