Authentification API Web ASP.NET

Je cherche à authentifier un utilisateur à partir d’une application client tout en utilisant l’ API Web ASP.NET . J’ai regardé toutes les vidéos sur le site et lu également ce message sur le forum .

Mettre l’atsortingbut [Authorize] correctement renvoie un statut 401 Unauthorized . Cependant, je dois savoir comment autoriser un utilisateur à se connecter à l’API.

Je souhaite fournir des informations d’identification d’utilisateur d’une application Android à l’API, obtenir la connexion de l’utilisateur, puis faire en sorte que tous les appels API ultérieurs soient authentifiés.

permettre à un utilisateur de se connecter à l’API

Vous devez envoyer un cookie d’authentification par formulaire valide avec la demande. Ce cookie est généralement envoyé par le serveur lors de l’authentification (action LogOn ) en appelant la méthode [FormsAuthentication.SetAuthCookie (voir MSDN )).

Le client doit donc effectuer 2 étapes:

  1. Envoyez une requête HTTP à une action LogOn en envoyant le nom d’utilisateur et le mot de passe. À son tour, cette action appelle la méthode FormsAuthentication.SetAuthCookie (au cas où les informations d’identification sont valides), ce qui à son tour définira le cookie d’authentification des formulaires dans la réponse.
  2. Envoyez une requête HTTP à une action protégée [Authorize] en envoyant le cookie d’authentification par formulaire récupéré lors de la première requête.

Prenons un exemple. Supposons que vous ayez 2 contrôleurs API définis dans votre application Web:

Le premier responsable de la gestion de l’authentification:

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

et le second contenant des actions protégées que seuls les utilisateurs autorisés peuvent voir:

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

Maintenant, nous pourrions écrire une application client utilisant cette API. Voici un exemple d’application de console sortingviale (assurez-vous d’avoir installé les packages Microsoft.AspNet.WebApi.Client et 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().Result; if (success) { var secret = httpClient.GetSsortingngAsync("http://localhost:26845/api/users"); Console.WriteLine(secret.Result); } else { Console.WriteLine("Sorry you provided wrong credentials"); } } } } 

Et voici comment les 2 requêtes HTTP regardent le fil:

Demande d’authentification:

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

Réponse d’authentification:

 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 

Demande de données protégées:

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

Réponse pour les données protégées:

 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" 

Je prends Android comme exemple.

 public abstract class HttpHelper { private final static Ssortingng TAG = "HttpHelper"; private final static Ssortingng API_URL = "http://your.url/api/"; private static CookieStore sCookieStore; public static Ssortingng invokePost(Ssortingng action, List params) { try { Ssortingng 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.toSsortingng()); } return null; } public static Ssortingng invokePost(Ssortingng action) { return invokePost(action, null); } public static Ssortingng invokeGet(Ssortingng action, List params) { try { SsortingngBuilder sb = new SsortingngBuilder(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.toSsortingng()); HttpGet httpGet = new HttpGet(sb.toSsortingng()); return invoke(httpGet); } catch (Exception e) { Log.e(TAG, e.toSsortingng()); } return null; } public static Ssortingng invokeGet(Ssortingng action) { return invokeGet(action, null); } private static Ssortingng invoke(HttpUriRequest request) throws ClientProtocolException, IOException { Ssortingng result = null; DefaultHttpClient httpClient = new DefaultHttpClient(); // restore cookie if (sCookieStore != null) { httpClient.setCookieStore(sCookieStore); } HttpResponse response = httpClient.execute(request); SsortingngBuilder builder = new SsortingngBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader( response.getEntity().getContent())); for (Ssortingng s = reader.readLine(); s != null; s = reader.readLine()) { builder.append(s); } result = builder.toSsortingng(); Log.d(TAG, "result is ( " + result + " )"); // store cookie sCookieStore = ((AbstractHttpClient) httpClient).getCookieStore(); return result; } 

Attention s’il vous plaît: i.localhost ne peut pas être utilisé. L’appareil Android a l’hôte local. Si vous déployez l’API Web dans IIS, l’authentification par formulaire doit être ouverte.

Utilisez ce code et accédez à la firebase database

 [HttpPost] [Route("login")] public IHttpActionResult Login(LoginRequest request) { CheckModelState(); ApiResponse response = new ApiResponse(); LoginResponse user; var count = 0; RoleName roleName = new RoleName(); using (var authManager = InspectorBusinessFacade.GetAuthManagerInstance()) { user = authManager.Authenticate(request); } reponse(ok) }