-->

Use asp.net authentication with servicestack

2020-06-05 01:29发布

问题:

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 even memberships, roles and application rights in a servicestack - application?

回答1:

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() 
            }
        ));