ASP.NET uwierzytelnianie Web API

Szukam uwierzytelnienia użytkownika z aplikacji klienckiej podczas korzystania z ASP.NET Web API . Obejrzałem wszystkie filmy na stronie, a także przeczytałem ten post na forum .

Poprawne umieszczenie atrybutu [Authorize] zwraca status 401 Unauthorized. Muszę jednak wiedzieć, jak zezwolić użytkownikowi na zalogowanie się do API.

Chcę podać dane uwierzytelniające użytkownika z aplikacji na Androida do API, zalogować użytkownika, a następnie mieć wszystkie kolejne wywołania API wstępnie uwierzytelnione.

Author: Ryan Kohn, 2012-06-13

3 answers

Pozwala użytkownikowi na zalogowanie się do API]}

Wraz z żądaniem należy wysłać ważny plik cookie uwierzytelniania formularzy. Ten plik cookie jest zwykle wysyłany przez serwer podczas uwierzytelniania (LogOn akcja) przez wywołanie metody [FormsAuthentication.SetAuthCookie (patrz MSDN ).

Więc klient musi wykonać 2 kroki:

  1. Wyślij żądanie HTTP do działania LogOn, wysyłając nazwę użytkownika i hasło. Z kolei ta akcja wywoła metodę FormsAuthentication.SetAuthCookie (W przypadku dane uwierzytelniające są ważne), które z kolei ustawią plik cookie uwierzytelniania formularzy w odpowiedzi.
  2. Wyślij żądanie HTTP do chronionego działania [Authorize], wysyłając plik cookie uwierzytelniania formularzy pobrany w pierwszym zapytaniu.
Weźmy przykład. Załóżmy, że masz 2 kontrolery API zdefiniowane w aplikacji internetowej:

Pierwszy odpowiedzialny za obsługę uwierzytelniania:

public class AccountController : ApiController
{
    public bool Post(LogOnModel model)
    {
        if (model.Username == "john" && model.Password == "secret")
        {
            FormsAuthentication.SetAuthCookie(model.Username, false);
            return true;
        }

        return false;
    }
}

I drugi zawierający chronione działania, które tylko autoryzowani użytkownicy mogą zobaczyć:

[Authorize]
public class UsersController : ApiController
{
    public string Get()
    {
        return "This is a top secret material that only authorized users can see";
    }
}

Teraz możemy napisać aplikację kliencką korzystającą z tego API. Oto trywialny przykład aplikacji konsolowej (upewnij się, że zainstalowałeś pakiety Microsoft.AspNet.WebApi.Client i Microsoft.Net.Http NuGet):

using System;
using System.Net.Http;
using System.Threading;

class Program
{
    static void Main()
    {
        using (var httpClient = new HttpClient())
        {
            var response = httpClient.PostAsJsonAsync(
                "http://localhost:26845/api/account", 
                new { username = "john", password = "secret" }, 
                CancellationToken.None
            ).Result;
            response.EnsureSuccessStatusCode();

            bool success = response.Content.ReadAsAsync<bool>().Result;
            if (success)
            {
                var secret = httpClient.GetStringAsync("http://localhost:26845/api/users");
                Console.WriteLine(secret.Result);
            }
            else
            {
                Console.WriteLine("Sorry you provided wrong credentials");
            }
        }
    }
}

A oto jak wyglądają 2 żądania HTTP na linku:

Żądanie uwierzytelnienia:

POST /api/account HTTP/1.1
Content-Type: application/json; charset=utf-8
Host: localhost:26845
Content-Length: 39
Connection: Keep-Alive

{"username":"john","password":"secret"}

Odpowiedź uwierzytelniająca:

HTTP/1.1 200 OK
Server: ASP.NET Development Server/10.0.0.0
Date: Wed, 13 Jun 2012 13:24:41 GMT
X-AspNet-Version: 4.0.30319
Set-Cookie: .ASPXAUTH=REMOVED FOR BREVITY; path=/; HttpOnly
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Content-Type: application/json; charset=utf-8
Content-Length: 4
Connection: Close

true

Prośba o dane chronione:

GET /api/users HTTP/1.1
Host: localhost:26845
Cookie: .ASPXAUTH=REMOVED FOR BREVITY

Odpowiedź na chronione dane:

HTTP/1.1 200 OK
Server: ASP.NET Development Server/10.0.0.0
Date: Wed, 13 Jun 2012 13:24:41 GMT
X-AspNet-Version: 4.0.30319
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Content-Type: application/json; charset=utf-8
Content-Length: 66
Connection: Close

"This is a top secret material that only authorized users can see"
 137
Author: Darin Dimitrov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-01 12:45:09

Za przykład biorę Androida.

public abstract class HttpHelper {

private final static String TAG = "HttpHelper";
private final static String API_URL = "http://your.url/api/";

private static CookieStore sCookieStore;

public static String invokePost(String action, List<NameValuePair> params) {
    try {
        String url = API_URL + action + "/";
        Log.d(TAG, "url is" + url);
        HttpPost httpPost = new HttpPost(url);
        if (params != null && params.size() > 0) {
            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            httpPost.setEntity(entity);
        }
        return invoke(httpPost);
    } catch (Exception e) {
        Log.e(TAG, e.toString());
    }

    return null;
}

public static String invokePost(String action) {
    return invokePost(action, null);
}

public static String invokeGet(String action, List<NameValuePair> params) {
    try {
        StringBuilder sb = new StringBuilder(API_URL);
        sb.append(action);
        if (params != null) {
            for (NameValuePair param : params) {
                sb.append("?");
                sb.append(param.getName());
                sb.append("=");
                sb.append(param.getValue());
            }
        }
        Log.d(TAG, "url is" + sb.toString());
        HttpGet httpGet = new HttpGet(sb.toString());
        return invoke(httpGet);
    } catch (Exception e) {
        Log.e(TAG, e.toString());
    }

    return null;
}

public static String invokeGet(String action) {
    return invokeGet(action, null);
}

private static String invoke(HttpUriRequest request)
        throws ClientProtocolException, IOException {
    String result = null;
    DefaultHttpClient httpClient = new DefaultHttpClient();

    // restore cookie
    if (sCookieStore != null) {
        httpClient.setCookieStore(sCookieStore);
    }

    HttpResponse response = httpClient.execute(request);

    StringBuilder builder = new StringBuilder();
    BufferedReader reader = new BufferedReader(new InputStreamReader(
            response.getEntity().getContent()));
    for (String s = reader.readLine(); s != null; s = reader.readLine()) {
        builder.append(s);
    }
    result = builder.toString();
    Log.d(TAG, "result is ( " + result + " )");

    // store cookie
    sCookieStore = ((AbstractHttpClient) httpClient).getCookieStore();
    return result;
}

Uwaga Proszę: i. localhost nie może być używany. Urządzenie z Androidem wygląda localhost jako host. ii. w przypadku wdrożenia web API w IIS należy otworzyć uwierzytelnianie formularza.

 12
Author: user2293998,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-26 13:52:58

Użyj tego kodu i uzyskaj dostęp do bazy danych

[HttpPost]
[Route("login")]
public IHttpActionResult Login(LoginRequest request)
{
       CheckModelState();
       ApiResponse<LoginApiResponse> response = new ApiResponse<LoginApiResponse>();
       LoginResponse user;
       var count = 0;
       RoleName roleName = new RoleName();
       using (var authManager = InspectorBusinessFacade.GetAuthManagerInstance())
       {
           user = authManager.Authenticate(request); 
       } reponse(ok) 
}
 0
Author: Sanila Salim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-05 10:06:12