如何在ASP.NET Web Api中使用安全性(身份验证和授权) [英] How to use security (Authentication & Authorization) in ASP.NET Web Api

查看:214
本文介绍了如何在ASP.NET Web Api中使用安全性(身份验证和授权)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个Android应用程序,它将使用SQL Server(数据库)存储该应用程序的数据.此外,该应用程序还将使用ASP Web API在客户端和服务器之间发送和接收XML或JSON.

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.

我目前对如何使应用程序安全地进行身份验证以及如何保持用户登录而不需要继续在http请求中发送用户的凭据感到困惑.

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.

推荐答案

  1. 通过访问Web API控制器(如果使用Asp.Net Web API网站的某些示例,则为/Token)从客户端(此处为Android)登录(用户名,密码在BasicNameValuePair中提供).如果成功,则访问令牌将得到响应,并将您保存在客户端(SharedPreference或数据库)中
  2. 然后,只需发送访问令牌(不再需要用户名和密码)即可请求其他API控制器.

当然,此处应使用 https 以获得更好的安全性.

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;
}

在makeHTTPRequest内部,用于请求访问令牌:

Inside makeHTTPRequest, for request access token:

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

这篇关于如何在ASP.NET Web Api中使用安全性(身份验证和授权)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆