自定义会员资格提供者不会重定向 [英] Custom Membership Provider won't redirect

查看:95
本文介绍了自定义会员资格提供者不会重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设置了一个自定义的成员资格和角色提供者,该提供者当前无法正常工作.我怀疑我错过了一些东西,但是根据我所有的研究,我仍然无法弄清它是什么.

I have setup a custom membership and role provider that is not currently working as it should. I suspect that I have missed something but with all my research I have not been able to work out what it is.

发生的问题是,当我输入正确的登录详细信息时,登录页面将重新加载而不是重定向.我怀疑它正在重定向,但由于某种原因,它不记得授权已被批准,因此它会将用户发送回登录页面.然后,这只会在一个令人讨厌的循环中不断重复自身.

The problem that is occurring is that when I enter the correct login details the login page reloads rather than redirecting. I suspect that it is redirecting but for some reason it doesn't recall that the authorisation has been approved, so as a result it sends the user back to the login page. This then just continuously repeats itself in an annoying loop.

这是我的web.config

This is my web.config

<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-BoomtickVenueEvents-20130313220611;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-BoomtickVenueEvents-20130313220611.mdf" providerName="System.Data.SqlClient" />
<add name="BoomtickVenueEventsDBContext" connectionString="Data Source=EAN-PC;Initial Catalog=BoomtickVenueEventsDB;Integrated Security=True;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
</connectionStrings>
...
<system.web>
<globalization uiCulture="en-AU" culture="en-AU" />
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<authentication mode="Forms">
  <forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
<membership defaultProvider="CustomMembershipProvider" userIsOnlineTimeWindow="15">
  <providers>
    <add name="CustomMembershipProvider" type="BoomtickVenueEvents.Providers.VOMembershipProvider" 
         connectionStringName="AuthenticationService"
         enablePasswordRetrieval="false"
         enablePasswordReset="true"
         requiresQuestionAndAnswer="false"
         applicationName="/"
         requiresUniqueEmail="false"
         maxInvalidPasswordAttempts="5"
         minRequiredPasswordLength="7"
         minRequiredNonalphanumericCharacters="0"
         passwordAttemptWindow="10" />
  </providers>
</membership>
<roleManager defaultProvider="CustomRoleProvider" enabled="true" cacheRolesInCookie="false">
  <providers>
    <clear />
    <add name="CustomRoleProvider" type="BoomtickVenueEvents.Providers.VORoleProvider" />
  </providers>
</roleManager>
<pages>
  <namespaces>
    <add namespace="System.Web.Helpers" />
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Optimization" />
    <add namespace="System.Web.Routing" />
    <add namespace="System.Web.WebPages" />
  </namespaces>
</pages>

我的自定义会员资格提供者如下

My Custom Membership Provider is as follows

using EventOracle.Data.Interfaces;
using EventOracle.Domain.Models;
using System;
using System.ServiceModel;
using System.Web.Security;

namespace BoomtickVenueEvents.Providers
{
    public class VOMembershipProvider : MembershipProvider
    {
        private static ISecurityProviderService _voData;

        #region Constructors
        /// <summary>
        /// Constructor that connects to the Database Service and sets a refference point to the service
        /// </summary>
        public VOMembershipProvider()
        {
            ChannelFactory<ISecurityProviderService> VODataFactory;
            NetTcpBinding tcpBinding = new NetTcpBinding();

            // Set the allowable message sizes
            tcpBinding.MaxReceivedMessageSize = System.Int32.MaxValue;
            //tcpBinding.ReaderQuotas.MaxArrayLength = System.Int32.MaxValue;

            // Set a string to the URL of the server
            string sURL = "net.tcp://localhost:50001/SecurityProviderService";

            try
            {
                // Instantiate the channel factory using the string pointing to the server location
                VODataFactory = new ChannelFactory<ISecurityProviderService>(tcpBinding, sURL);

                // Start the channel factory
                _voData = VODataFactory.CreateChannel();
            }
            catch (Exception ex)
            {
                // Display the error message to the user
                Console.WriteLine(ex.Message);
            }
        }
        #endregion // Constructors

        public override string ApplicationName
        {
            get
            {
                throw new System.NotImplementedException();
            }
            set
            {
                throw new System.NotImplementedException();
            }
        }

        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            throw new System.NotImplementedException();
        }

        public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
        {
            throw new System.NotImplementedException();
        }

        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        {
            throw new System.NotImplementedException();
        }

        public override bool DeleteUser(string username, bool deleteAllRelatedData)
        {
            throw new System.NotImplementedException();
        }

        public override bool EnablePasswordReset
        {
            get { throw new System.NotImplementedException(); }
        }

        public override bool EnablePasswordRetrieval
        {
            get { throw new System.NotImplementedException(); }
        }

        public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new System.NotImplementedException();
        }

        public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new System.NotImplementedException();
        }

        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            throw new System.NotImplementedException();
        }

        public override int GetNumberOfUsersOnline()
        {
            throw new System.NotImplementedException();
        }

        public override string GetPassword(string username, string answer)
        {
            throw new System.NotImplementedException();
        }

        public override MembershipUser GetUser(string username, bool userIsOnline)
        {
            User user = _voData.GetUser(username);
            if (user != null)
            {
                MembershipUser memUser = new MembershipUser("CustomMembershipProvider", 
                                                                username, user.UserId, user.Email,
                                                                string.Empty, string.Empty, true,
                                                                false, DateTime.MinValue, DateTime.MinValue,
                                                                DateTime.MinValue, DateTime.Now, DateTime.Now);
                return memUser;
            }
            return null;
        }

        public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
        {
            throw new System.NotImplementedException();
        }

        public override string GetUserNameByEmail(string email)
        {
            throw new System.NotImplementedException();
        }

        public override int MaxInvalidPasswordAttempts
        {
            get { throw new System.NotImplementedException(); }
        }

        public override int MinRequiredNonAlphanumericCharacters
        {
            get { throw new System.NotImplementedException(); }
        }

        public override int MinRequiredPasswordLength
        {
            get { throw new System.NotImplementedException(); }
        }

        public override int PasswordAttemptWindow
        {
            get { throw new System.NotImplementedException(); }
        }

        public override MembershipPasswordFormat PasswordFormat
        {
            get { throw new System.NotImplementedException(); }
        }

        public override string PasswordStrengthRegularExpression
        {
            get { throw new System.NotImplementedException(); }
        }

        public override bool RequiresQuestionAndAnswer
        {
            get { throw new System.NotImplementedException(); }
        }

        public override bool RequiresUniqueEmail
        {
            get { throw new System.NotImplementedException(); }
        }

        public override string ResetPassword(string username, string answer)
        {
            throw new System.NotImplementedException();
        }

        public override bool UnlockUser(string userName)
        {
            throw new System.NotImplementedException();
        }

        public override void UpdateUser(MembershipUser user)
        {
            throw new System.NotImplementedException();
        }

        public override bool ValidateUser(string username, string password)
        {
            return _voData.ValidateUser(username, password);
        }
    }
}

和我的AccountController如下

and my AccountController as follows

namespace BoomtickVenueEvents.Controllers
{
    [Authorize]
    [InitializeSimpleMembership]
    public class AccountController : Controller
    {

        private static ISecurityProviderService _voData;

        #region Constructors
        /// <summary>
        /// Constructor that connects to the Database Service and sets a refference point to the service
        /// </summary>
        public AccountController()
        {
            ChannelFactory<ISecurityProviderService> VODataFactory;
            NetTcpBinding tcpBinding = new NetTcpBinding();

            // Set the allowable message sizes
            tcpBinding.MaxReceivedMessageSize = System.Int32.MaxValue;
            //tcpBinding.ReaderQuotas.MaxArrayLength = System.Int32.MaxValue;

            // Set a string to the URL of the server
            string sURL = "net.tcp://localhost:50001/AuthoriseService";

            try
            {
                // Instantiate the channel factory using the string pointing to the server location
                VODataFactory = new ChannelFactory<ISecurityProviderService>(tcpBinding, sURL);

                // Start the channel factory
                _voData = VODataFactory.CreateChannel();
            }
            catch (Exception ex)
            {
                // Display the error message to the user
                Console.WriteLine(ex.Message);
            }
        }
        #endregion // Constructors

        //
        // GET: /Account/Login

        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        //
        // POST: /Account/Login

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid && Membership.ValidateUser(model.UserName, model.Password))
            {
                return RedirectToLocal(returnUrl);
            }

            // If we got this far, something failed, redisplay form
            ModelState.AddModelError("", "The user name or password provided is incorrect.");
            return View(model);
        }

        //
        // POST: /Account/LogOff

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            WebSecurity.Logout();

            return RedirectToAction("Index", "Home");
        }

请不要让我使用WCF来获取数据,但是,只要数据正确,我收集数据的方法就不是问题.另外,我还没有包括提供的角色,因为我还没有包括任何角色授权.

Please not that I am using WCF to get the data, however, the method by which I am collecting the data isn't the problem as long as the data is correct. Also I haven't included the role provide because I haven't included any role authorisations yet.

任何帮助将不胜感激.

推荐答案

不是正在发布表单cookie!我怀疑您将成员身份提供程序(负责验证凭据)与表单身份验证模块(负责发布cookie)混淆了.

You are not issuing the forms cookie! I suspect you are confusing the membership provider (which is responsible for validating credentials) with forms authentication module (which is responsible for issuing cookies).

最简单的解决方法:

if (ModelState.IsValid && Membership.ValidateUser(model.UserName, model.Password))
{
    FormsAuthentication.SetAuthCookie( model.UserName, false );
    return RedirectToLocal(returnUrl);
}

这篇关于自定义会员资格提供者不会重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆