的ASP.NET Web API认证NET、ASP、API、Web

2023-09-02 21:08:39 作者:嗯哼嗯哼蹦嚓嚓

我期待在使用的ASP.NET Web API 从客户端应用程序验证用户身份。我看过网站上的所有视频,并阅​​读this论坛帖子。

[授权] 属性正确返回 401未授权状态。不过,我需要知道如何让用户在登录到API。

我想从一个Android应用程序的API提供用户凭据,获得用户登录,然后让所有后续API调用pre-验证。

解决方案   

允许用户在登录到该API

您需要与请求一起发送有效的窗体身份验证cookie。此cookie通常是由服务器通过调用 [FormsAuthentication.SetAuthCookie 方法验证( LogOn支持动作)时发送(见MSDN).

因此​​,客户端需要执行2个步骤:

通过发送用户名和密码,发送一个HTTP请求到 LogOn支持的行动。在转弯这个动作会调用 FormsAuthentication.SetAuthCookie 方法(如果证书有效),这反过来将设置窗体身份验证Cookie在响应中。 在发送一个HTTP请求到 [授权] 沿其检索的第一次请求窗体身份验证Cookie发送的保护作用。

让我们看一个例子。假设你已经在你的web应用程序中定义2 API控制器:

第一个负责处理身份验证:

 公共类的AccountController:ApiController
{
    公共BOOL帖子(LogOnModel模型)
    {
        如果(model.Username ==约翰和安培;&安培; model.Password ==秘密)
        {
            FormsAuthentication.SetAuthCookie(model.Username,假);
            返回true;
        }

        返回false;
    }
}
 
在ASP.NET Core Web API上使用Swagger提供API文档

和第二个包含保护的操作只有授权用户才可以看到:

  [授权]
公共类UsersController中:ApiController
{
    公共字符串获得()
    {
        返回这是只有授权用户可以看到一个绝密材料;
    }
}
 

现在,我们可以写一个客户端应用程序消耗这个API。这里有一个简单的控制台应用程序示例(请确保您已安装了 Microsoft.AspNet.WebApi.Client Microsoft.Net.Http 的NuGet包):

 使用系统;
使用System.Net.Http;
使用的System.Threading;

类节目
{
    静态无效的主要()
    {
        使用(VAR的HttpClient =新的HttpClient())
        {
            VAR响应= httpClient.PostAsJsonAsync(
                HTTP://本地主机:26845 / API /账户,
                新{用户名=约翰,密码=秘密},
                CancellationToken.None
            )。结果;
            response.EnsureSuccessStatus code();

            布尔成功= response.Content.ReadAsAsync<布尔>()结果。
            如果(成功)
            {
                VAR秘密= httpClient.GetStringAsync(HTTP://本地主机:26845 / API /用户);
                Console.WriteLine(secret.Result);
            }
            其他
            {
                Console.WriteLine(对不起,您所提供错误的凭据);
            }
        }
    }
}
 

和这里的2 HTTP请求如何看待的电线:

认证请求:

  POST / API /帐户HTTP / 1.1
内容类型:应用程序/ JSON;字符集= UTF-8
主持人:本地主机:26845
内容长度:39
连接:保持活动

{用户名:约翰,密码:秘密}
 

验证响应:

  HTTP / 1.1 200 OK
服务器:ASP.NET开发服务器/ 10.0.0.0
日期:星期三,2012 13时24分41秒格林尼治标准​​时间6月13日
的X ASPNET-版本:4.0.30319
设置Cookie:.ASPXAUTH =为了简洁,删除;路径= /;仅Http
缓存控制:无缓存
杂注:无缓存
到期日:-1
内容类型:应用程序/ JSON;字符集= UTF-8
内容长度:4
连接:关闭

真正
 

请求保护的数据:

  GET / API /用户HTTP / 1.1
主持人:本地主机:26845
饼干:.ASPXAUTH =为了简洁,删除
 

响应为受保护的数据:

  HTTP / 1.1 200 OK
服务器:ASP.NET开发服务器/ 10.0.0.0
日期:周三2012 GMT 13时24分41秒6月13日
的X ASPNET-版本:4.0.30319
缓存控制:无缓存
杂注:无缓存
到期日:-1
内容类型:应用程序/ JSON;字符集= UTF-8
内容长度:66
连接:关闭

这是一个绝密的材料只有授权用户才可以看到
 

I am looking to authenticate a user from a client application while using the ASP.NET Web API. I have watched all the videos on the site and also read this forum post.

Putting the [Authorize] attribute correctly returns a 401 Unauthorized status. However, I need to know how to allow a user to log in to the API.

I want to provide user credentials from an Android application to the API, get the user logged in, and then have all subsequent API calls pre-authenticated.

解决方案

allow a user to log in to the API

You need to send a valid Forms Authentication cookie along with the request. This cookie is usually sent by the server when authenticating (LogOn action) by calling the [FormsAuthentication.SetAuthCookie method (see MSDN).

So the client needs to perform 2 steps:

Send an HTTP request to a LogOn action by sending the username and password. In turns this action will call the FormsAuthentication.SetAuthCookie method (in case the credentials are valid) which in turn will set the forms authentication cookie in the response. Send an HTTP request to an [Authorize] protected action by sending along the forms authentication cookie it retrieved in the first request.

Let's take an example. Suppose that you have 2 API controllers defined in your web application:

The first one responsible for handling authentication:

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

and the second one containing protected actions that only authorized users can see:

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

Now we could write a client application consuming this API. Here's a trivial console application example (make sure you have installed the Microsoft.AspNet.WebApi.Client and Microsoft.Net.Http NuGet packages):

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

And here's how the 2 HTTP requests look on the wire:

Authentication request:

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

Authentication response:

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

Request for protected data:

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

Response for protected data:

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"

 
精彩推荐
图片推荐