我有一个现有的 Web 应用程序,我将其移植到PhoneGap
. 我已经成功复制了这个,但我想知道跨域身份验证的最佳实践。我应该在这里提到现有的身份验证正在使用System.Web.Security
和我的 PhoneGap 应用程序正在与之通信的 Web 服务具有相同的性质。
目前,我已经设置了Login
功能,它将发布到我的登录方法:
[HttpPost]
public JsonResult Login(LoginModel viewModel)
{
string error = "";
if (!WebSecurity.IsAccountLockedOut(viewModel.UserName, 3, 60 * 60))
{
if (WebSecurity.Login(viewModel.UserName, viewModel.Password))
return Json(new { success = true });
error = "The user name or password provided is incorrect.";
}
else
error = "Too many failed login attempts. Please try again later.";
return Json(new { success = false, error });
}
这是从我的Javascript
function login(data, automated) {
$.ajax({
type: "POST",
url: "http://url/checkin/app/login",
content: "application/json; charset=utf-8",
dataType: "json",
data: data,
success: function(d) {
if (d.success == true) {
window.localStorage.setItem('UserName', data.UserName);
window.localStorage.setItem('Password', data.Password);
window.location = "index.html";
} else {
localStorage.clear();
if (!automated) {
app.showError(d.error);
}
}
},
error: function (xhr, textStatus, errorThrown) {
app.showError(errorThrown);
}
});
}
我希望这可以正常工作并且确实可以,success: true
如果凭据正确则返回。转到与服务的其他交互,这就是我感到困惑的地方。我不希望 Membership.GetUser()
工作:
[HttpPost]
public JsonResult CheckIn(int id)
{
var user = Membership.GetUser();
// Do stuff
}
这是如何工作的?更重要的是安全吗?我应该以不同的方式处理这个问题吗?
当我登录到网站的桌面版本(原始版本)时,在我的 cookie 中我有一个.ASPXAUTH
值,而我的 PhoneGap 应用程序则不是这样。这就是为什么我对它的工作原理感到困惑。
我的控制器上有一个Attribute
,当删除时,它会阻止应用程序登录。但是,我不确定这是允许跨域身份验证的原因吗?
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class InitializeSimpleMembershipAttribute : ActionFilterAttribute
{
private static SimpleMembershipInitializer _initializer;
private static object _initializerLock = new object();
private static bool _isInitialized;
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Ensure ASP.NET Simple Membership is initialized only once per app start
LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
}
private class SimpleMembershipInitializer
{
public SimpleMembershipInitializer()
{
Database.SetInitializer<UsersContext>(null);
try
{
using (var context = new UsersContext())
{
if (!context.Database.Exists())
{
// Create the SimpleMembership database without Entity Framework migration schema
((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
}
}
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
}
catch (Exception ex)
{
throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
}
}
}
}