Use asp.net authentication with servicestack

后端 未结 1 409
逝去的感伤
逝去的感伤 2021-02-10 23:31

I have written a couple of ms lightswitch applications with forms authentication -> this creates aspnet_* tables in sql server. How can I use the defined users, passwords, maybe

相关标签:
1条回答
  • 2021-02-10 23:40

    I have not tested this but I think it should get you started. Gladly stand corrected on any of my steps.

    Things I think you will need to do..

    • In order to Authenticate against both 'systems' you'll need to set the Forms cookie and save your ServiceStack session.

    Instead of calling FormsAuthentication.Authentiate() do something like below. This won't work until you complete all the steps.

    var apiAuthService = AppHostBase.Resolve<AuthService>();
    apiAuthService.RequestContext = System.Web.HttpContext.Current.ToRequestContext();
    var apiResponse = apiAuthService.Authenticate(new Auth
    {
        UserName = model.UserName,
        Password = model.Password,
        RememberMe = false
    });
    
    • Create a subclass of IUserAuthRepository (for retrieving membership/user/roles from aspnet_* tables and filling ServiceStack AuthUser).

    CustomAuthRepository.cs (incomplete, but should get you started)

    public class CustomAuthRepository : IUserAuthRepository
    {
        private readonly MembershipProvider _membershipProvider;
        private readonly RoleProvider _roleProvider;
    
        public CustomAuthRepository()
        {
            _membershipProvider = Membership.Provider;
            _roleProvider = Roles.Provider;
        }
    
        public UserAuth GetUserAuthByUserName(string userNameOrEmail)
        {
            var user = _membershipProvider.GetUser(userNameOrEmail, true);
            return new UserAuth {FirstName = user.UserName, Roles = _roleProvider.GetRolesForUser(userNameOrEmail).ToList() //FILL IN REST OF PROPERTIES};
        }
    
        public bool TryAuthenticate(string userName, string password, out UserAuth userAuth)
        {
            //userId = null;
            userAuth = GetUserAuthByUserName(userName);
            if (userAuth == null) return false;
    
            if (FormsAuthentication.Authenticate(userName, password))
            {
                FormsAuthentication.SetAuthCookie(userName, false);
                return true;
            }
    
            userAuth = null;
            return false;
        }
    //MORE METHODS TO IMPLEMENT...
    }
    
    • Wire Authentication up for ServiceStack in AppHost configure method.

      var userRep = new CustomAuthRepository();
      
      container.Register<IUserAuthRepository>(userRep);
      
      Plugins.Add(
          new AuthFeature(() => new AuthUserSession(),
              new IAuthProvider[] {
                  new CredentialsAuthProvider() 
              }
          ));
      
    0 讨论(0)
提交回复
热议问题