我想通过 Ajax 使用 Web 服务。使用ajax调用web服务时最好的安全方法是什么?我想防止应用程序的远程调用。
例如,我有以下网络服务:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class Users : System.Web.Services.WebService
{
[WebMethod]
public List<User> GetUsers()
{
List<User> listUsers = new List<User>();
User user = new User();
user.Id = 1;
user.Name = "John";
User user2 = new User();
user2.Id = 2;
user2.Name = "Martin";
listUsers.Add(user);
listUsers.Add(user2);
return listUsers;
}
}
}
我使用 jquery ajax 调用 Web 服务:
<script type="text/javascript">
$(function () {
getUsers();
function getUsers() {
$.ajax({
type: "POST",
url: "Webservices/Users.asmx/GetUsers",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var users = response.d;
$.each(users, function (index, user) {
console.log(user.Name);
});
},
failure: function (msg) {
}
});
}
});
</script>
最佳答案
没有最好的方法,答案总是 it depends
,尽管这非常无益。您可以使用forms authentication例如。如果您的Web应用程序使用的Web服务和Web服务属于同一个ASP.NET application
,浏览器可以为每次调用 Web 服务无缝发送表单例份验证票证 (cookie)。
在配置文件中,您可以拥有
<authorization>
<deny users="?" />
</authorization>
这将拒绝匿名用户的访问,并且也将覆盖网络服务。换句话说,除非用户登录并获得带有票证的有效 cookie,否则无法使用服务。当然,你必须HTTPS
。否则,中间的任何人都可以获取 header 中的 cookie 并调用您的服务。
最后,不可能确保没有人在您的应用程序之外绝对意义上调用 Web 服务。上述方法确保中间没有人调用您的服务。但是,无法确保有效的用户直接在应用程序外部调用服务,因为 Web 服务调用者是 JavaScript,并且用户通过查看脚本甚至查看在 JavaScript 中构建的任何安全性都可以轻松弄清楚。往返于浏览器的流量。任何懂点技术的最终用户都可以重放请求或修改请求并使用有效凭据提交到您的 Web 服务。
编辑:-
以下是您需要查找的启用 FormsAuthentication 的更多详细信息。
(1) 在 Web.config
,在<system.web>
下,确保你有这个。
<authentication mode="Forms">
<forms loginUrl="Login.aspx" defaultUrl="~/" />
</authentication>
<authorization>
<deny users="?" />
</authorization>
这将确保所有未经身份验证(匿名)的用户都被重定向到 Login.aspx。
(2) 实现 Login.aspx
使用您的登录逻辑来获取用户 ID 和密码,并根据数据库或其他内容验证它们。一旦身份验证成功,即用户输入的ID和密码与数据库中的内容匹配,则可以在登录按钮中单击处理程序,设置票证。
protected void Button1_Click(object sender, EventArgs e)
{
// Do all your login logic here
// once user ID and password entered by the user are okay, call this
string ticket = FormsAuthentication.Encrypt(
new FormsAuthenticationTicket("userId", false, 15));
HttpCookie FormsCookie = new HttpCookie(
FormsAuthentication.FormsCookieName, ticket) { HttpOnly = true };
HttpContext.Current.Response.Cookies.Add(FormsCookie);
}
(3) 添加PrincipalPermissionAttribute
像这样的网络方法。
public class Users : System.Web.Services.WebService
{
[PrincipalPermissionAttribute(SecurityAction.Demand)]
[WebMethod]
public List<User> GetUsers()
{
// Same code as what you have now
}
}
如果您现在转到任何页面,您将被重定向到 login.aspx,您需要在其中输入用户 ID 和密码并登录。登录时,将创建表单例份验证 cookie 并将其写入响应。从那时起,对您的应用程序的所有请求都将带入 cookie(浏览器将为您执行此操作)。在没有登录的情况下,如果直接访问Web服务,您仍然会被重定向到登录页面。正如我在原始答案中提到的,登录用户仍然可以直接访问网络服务。如果 JavaScript 可以做某事,用户也可以做同样的事情。
顺便说一句,Web 服务 (asmx) 是一项已弃用的技术。
关于jquery - Asp.net Webservice - 使用 jquery AJAX 安全调用 Web 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17511838/