[英]How to secure my web api in mvc 4
HTTP://本地主機:1075 / API /客戶/ GETCUSTOMER ID = 1
1,上面的URL讓我得到特定用戶配置文件信息的結果..以下是控制器代碼。該Web api是為Android應用程序調用和設計的。但是即使我從瀏覽器或郵遞員工具中調用它也能得到結果。 那么安全在哪里? 如果有人知道此網址,則他可以訪問我們的所有敏感信息。 請建議我如何保護我的網絡API ...
public customerCollection Getcustomer(int id)
{
db.Configuration.ProxyCreationEnabled = false;
var customer = (from c in db.customers
where c.customerID == id
select c).ToArray();
var result = new customerCollection();
if (customer == null)
{
result.status = "failed";
}
result.status = "success";
result.customerArray = customer;
return result;
}
回應是
{
"customerArray": [
{
"customerID": 1,
"cname": "Yogesh",
"cmobile": "9970714878",
"cemail": "yogeshkhurpe11@gmail.com",
"cpassword": "yogesh",
"addressLine1": "balaji hostel",
"addressLine2": "Jadhav nagar",
"area": "Vadgoan",
"pincode": "411041",
"cimage": "Na",
"cdate": "2017-06-28T14:16:03",
"cstatus": "active",
"orders": []
}
],
"status": "success"
}
這是使用身份驗證的分步方法。
您應該在WebAPI中創建Authorize屬性,以首先對傳入的請求進行授權。
首先,將要使用您的API的用戶將使用用戶名和密碼對自己進行身份驗證,一旦此過程完成且用戶已獲得授權,則應向用戶返回令牌以進行進一步的請求。 該令牌可以是加密時間或GUID,也可以是您希望了解的特定用戶(為之生成令牌)的任何內容。 您可以將該令牌保存到數據庫中以備將來使用。
現在,下一次用戶嘗試訪問您的API時,他將在該api請求的標頭部分中發送令牌。 如果令牌有效,則應返回結果,否則應返回錯誤,指出令牌無效。
謝謝希望對您有所幫助!
嘗試以下邏輯。 首先在WebAPI中創建一個Authorize屬性。 使用api函數上方的Authorize屬性來保護api的
public class AuthenticationFilter : AuthorizationFilterAttribute
{
/// <summary>
/// read requested header and validated
/// </summary>
/// <param name="actionContext"></param>
public override void OnAuthorization(HttpActionContext actionContext)
{
var identity = FetchFromHeader(actionContext);
if(identity != null)
{
//get the user based on the identity
var user=TokenService.getUserFromToken(identity);
if (user)
{
CurrentThread.SetPrincipal(new GenericPrincipal(new GenericIdentity(user), null), null, null);
}
else
{
actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
return;
}
}
else
{
actionContext.Response = new HttpResponseMessage(HttpStatusCode.BadRequest);
return;
}
base.OnAuthorization(actionContext);
}
/// <summary>
/// retrive header detail from the request
/// </summary>
/// <param name="actionContext"></param>
/// <returns></returns>
private string FetchFromHeader(HttpActionContext actionContext)
{
string requestToken = null;
var authRequest = actionContext.Request.Headers.Authorization;
if (authRequest != null && !string.IsNullOrEmpty(authRequest.Scheme) && authRequest.Scheme == "Basic")
requestToken = authRequest.Parameter;
return requestToken;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.