簡體   English   中英

ASP.NET Web API登錄方法

[英]ASP.NET Web API Login method

我想使用ASP.NET Web API構建RESTful Web服務,第三方開發人員將使用它來訪問我的應用程序的數據。

在Visual Studio中,我決定創建一個新的ASP.NET項目。 我按照本教程,但我選擇了另一個模板:Web API模板。 我使用MySQL數據庫和標准用戶角色表,如教程中所述。

該模板帶有許多非常有趣的方法來注冊新用戶,但沒有默認的登錄請求。 我在不理解我在做什么的情況下寫了這篇文章:

    // POST api/Account/Login
    [Route("Login")]
    public IHttpActionResult Login(LoginBindingModel model)
    {
        ClaimsIdentity ci = new ClaimsIdentity();
        // ...
        // ...
        Authentication.SignIn(ci);
        return Ok();
    }

我已經閱讀了很多關於安全性的文章而沒有找到一個很好的樣本,文檔解釋了它的工作原理。 在Web API中實現簡單的登錄方法似乎非常困難。

你能解釋一下為什么這個模板中沒有登錄方法嗎? 你有一個登錄方法的樣本。 我應該將哪些內容發送回客戶端應用程序以驗證請求。 這是使用令牌嗎?

通常你所做的是在該方法中實現登錄邏輯,並返回一個令牌,然后在每次調用api時驗證該令牌。

您可以閱讀此內容以獲取更多信息

http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/

如果您已創建新的ASP.NET Web Application - > Web API - >更改身份驗證 - > Individual User Accounts 看看App_Start - > Startup.Auth.cs

它應該包含這樣的東西:

PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
    TokenEndpointPath = new PathString("/Token"),
    Provider = new ApplicationOAuthProvider(PublicClientId),
    AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
    AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
    // In production mode set AllowInsecureHttp = false
    AllowInsecureHttp = true
};

// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(OAuthOptions);

這意味着您可以發送訪問令牌請求,示例請求:

在此輸入圖像描述

然后,您可以驗證訪問令牌是否有效:

在此輸入圖像描述

使用此令牌,您現在可以訪問用戶有權訪問的所有受保護資源。

如果您要為第三方開發人員構建API,那么您需要使用OAuth 2.0流程來保護它,我已經編寫了詳細的帖子,因為@dariogriffo指示您實現資源所有者密碼憑據流,這對您的情況很有用。

您無需為登錄創建終點,您將使用Owin中間件配置API,以便在調用端點(例如“/ token”)時向用戶發出OAuth承載令牌,然后用戶繼續發送此令牌以及Authorization標頭中的每個請求。 詳細了解基於令牌的身份驗證

對於Others,幫助類,首先是:

namespace WeBAPITest
{



#region Using Statements:



using System.Net.Http;
using System.Collections.Generic;

using Newtonsoft.Json;



#endregion



public class HttpWebApi
{



#region Fields:



private static readonly HttpClient client = new HttpClient();



#endregion



#region Properties:



/// <summary>
/// The basr Uri.
/// </summary>
public string BaseUrl { get; set; }



/// <summary>
/// Username.
/// </summary>
protected internal string Username { get; set; }



/// <summary>
/// Password.
/// </summary>
protected internal string Password { get; set; }



/// <summary>
/// The instance of the Root Object Json Deserialised Class.
/// </summary>
internal Rootobject Authentication { get; set; }



/// <summary>
/// The Access Token from the Json Deserialised Login.
/// </summary>
public string AccessToken { get { return Authentication.access_token; } }



#endregion



public HttpWebApi(string baseurl)
{

    // Init Base Url:
    BaseUrl = baseurl;
}



/// <summary>
/// Get from the Web API.
/// </summary>
/// <param name="path">The BaseUrl + path (Uri.Host + api/Controller) to the Web API.</param>
/// <returns>A Task, when awaited, a string</returns>
public async System.Threading.Tasks.Task<string> Get(string path)
{

    if (Authentication.access_token == null)
    throw new System.Exception("Authentication is not completed.");

    // GET
    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", Authentication.access_token);
    return await client.GetStringAsync(BaseUrl + path);
}



/// <summary>
/// Logs In and populates the Authentication Variables.
/// </summary>
/// <param name="username">Your Username</param>
/// <param name="password">Your Password</param>
/// <returns>A Task, when awaited, a string</returns>
public async System.Threading.Tasks.Task<string> Login(string username, string password)
{

    // Set Username:
    Username = username;

    // Set Password:
    Password = password;

    // Conf String to Post:
    var Dic = new Dictionary<string, string>() { { "grant_type", "password" }, { "username", "" }, { "password", "" } };
    Dic["username"] = username;
    Dic["password"] = password;

    // Post to Controller:
    string auth = await Post("/Token", Dic);

    // Deserialise Response:
    Authentication = JsonConvert.DeserializeObject<Rootobject>(auth);

    return auth;
}



/// <summary>
/// Post to the Web API.
/// </summary>
/// <param name="path">The BaseUrl + path (Uri.Host + api/Controller) to the Web API.</param>
/// <param name="values">The new Dictionary<string, string> { { "value1", "x" }, { "value2", "y" } }</param>
/// <returns>A Task, when awaited, a string</returns>
public async System.Threading.Tasks.Task<string> Post(string path, Dictionary<string, string> values)
{

    // Add Access Token to the Headder:
    if (Authentication != null)
    if (Authentication.access_token != "")
        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", Authentication.access_token);

    // Encode Values:
    var content = new FormUrlEncodedContent(values);

    // Post and get Response:
    var response = await client.PostAsync(BaseUrl + path, content);

    // Return Response:
    return await response.Content.ReadAsStringAsync();
}



/// <summary>
/// Register a new User.
/// </summary>
/// <param name="username">Your Username, E-Mail</param>
/// <param name="password">Your Password</param>
/// <returns>A Task, when awaited, a string</returns>
public async System.Threading.Tasks.Task<string> Register(string username, string password)
{

    // Register: api/Account/Register
    var Dic = new Dictionary<string, string>() { { "Email", "" }, { "Password", "" }, { "ConfirmPassword", "" } };
    Dic["Email"] = username;
    Dic["Password"] = password;
    Dic["ConfirmPassword"] = password;

    return await Post("api/Account/Register", Dic);
}
}



/// <summary>
/// For Json Deserialisation.
/// </summary>
internal class Rootobject
{

/// <summary>
/// The Web Api Access Token. Gets added to the Header in each communication.
/// </summary>
public string access_token { get; set; }



/// <summary>
/// The Token Type
/// </summary>
public string token_type { get; set; }



/// <summary>
/// Expiry.
/// </summary>
public int expires_in { get; set; }



/// <summary>
/// The Username.
/// </summary>
public string userName { get; set; }



/// <summary>
/// Issued.
/// </summary>
public string issued { get; set; }



/// <summary>
/// Expiry.
/// </summary>
public string expires { get; set; }
}
}

特別為Visual Studio中的默認未經編輯的Web Api模板而設計。

然后:

HttpWebApi httpWebApi = new HttpWebApi("http://localhost/");
await httpWebApi.Login("email", "password");

richTextBox1.AppendText(await httpWebApi.Get("api/Account/UserInfo") + Environment.NewLine);

希望這有助於其他人!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM