2014-10-22 116 views
12

我想用第三方开发人员用来访问我的应用程序数据的ASP.NET Web API构建RESTful Web服务。ASP.NET Web API登录方法

在Visual Studio中,我决定创建一个新的ASP.NET项目。我跟着这个tutorial,但我选择了一个不同的模板: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中实现简单的登录方法似乎非常困难。

你能解释一下为什么在这个模板中没有登录方法。你有一个登录方法的样本。我应该发回客户端应用程序来验证请求。这是使用令牌吗?

+0

也许这篇文章会帮助你http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api – Monah 2014-10-22 09:00:43

+2

这篇文章是关于这个主题的极简主义文档的完美例子。 – 2014-10-22 12:26:54

回答

4

如果你要建立对第三方开发者的API,那么你需要使用OAuth 2.0流程,以确保它可以阅读更多的信息,我已经写了详细的岗位作为@dariogriffo指导你实现资源所有者密码凭证流,这对你的情况非常有用。

您不需要创建登录端点,您将使用Owin中间件配置API,以在调用诸如“/ token”之类的端点时向用户发出OAuth承载令牌,然后用户继续发送此令牌以及授权标头中的每个请求。阅读更多关于token based authentication

4

如果您已创建新的ASP.NET Web ApplicationWeb 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); 

这意味着,你可以发送一个请求访问令牌,例如要求:

enter image description here

然后,您可以验证访问代币作品:

enter image description here

使用此令牌,您现在可以访问用户有权访问的所有受保护资源。

0

他人,一个辅助类,首先:

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

特别设计的默认,未经编辑的网页API模板在Visual Studio中。

然后:

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

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

希望这有助于其他一些!