Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
158 views
in Technique[技术] by (71.8m points)

android - How to use security (Authentication & Authorization) in ASP.NET Web Api

I am developing an Android application which will use a SQL server(database) to store the application's data. In addition, the application will use the ASP web API to send and receive XML or JSON between the client and the server.

I am currently confused about how to make the application do the authentication securely and how to keep the user logged in without the need to keep sending the user's credentials in the http requests.

Therefore, I need your recommendation about how to secure my application and to provide me with a tutorial links if possible.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  1. Login (Username, Password shored in BasicNameValuePair) from your Client (here Android) by access Web API controller (perhaps /Token if you use some samples from Asp.Net Web API website). If success, the access token will be responsed and you will save in your client (SharedPreference or database)
  2. Then, just need to send the access token (no need username, password anymore) to request other API controllers.

Of course, https should be used here for better security.

Sample codes for getting the access token (login phase):

public static Object getAccessToken(String address, String grant_type, String username, String password) throws Exception {
    List<NameValuePair> params = new ArrayList<>();
    params.add(new BasicNameValuePair("grant_type", grant_type));
    params.add(new BasicNameValuePair("username", username));
    params.add(new BasicNameValuePair("password", password));

    // Making HTTP request
    httpResponse = makeHTTPRequest(address, params);
    if (httpResponse != null) {
        statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_BAD_REQUEST) {
            return httpResponse.getStatusLine().toString();
        }

        // Get JSON String (jsonString) from Input Stream (is)
        getJSONFromInputStream();
        if (jsonString.isEmpty()) {
            return null;
        }
        // Parse the JSON String to a JSON Object
        jObj = new JSONObject(jsonString);
    }
    // Return JSON Object
    return jObj;
}

Inside makeHTTPRequest, for request access token:

httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
httpPost.setEntity(new UrlEncodedFormEntity(parameters));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...