Use asp.net authentication with servicestack

Deadly 提交于 2019-12-09 06:51:51

问题


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


来源:https://stackoverflow.com/questions/15068774/use-asp-net-authentication-with-servicestack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!