Use mixed authentication with Asp.Net MVC (Forms, FB connect, twitter, openId)

前端 未结 2 1303
广开言路
广开言路 2021-02-02 03:19

I\'m creating a new site and I want the users to be able to use several ways to sign in, basically the users should be able to create a new user on my site OR use Facebook conne

2条回答
  •  南方客
    南方客 (楼主)
    2021-02-02 03:57

    I blogged about something similar recently...Here's the approach I took

    public class User {
        public int UserID { get; set; }
        public string Name { get; set; }
        public string Page { get; set; }
    
        public virtual Authentication Authentication { get; set; }
    }
    
    public class Authentication {
        public int Id { get; set; }
        public string LoginId { get; set; }
        public string Provider { get; set; }
        public string Password { get; set; }
    
        public virtual User User { get; set; }
    }
    
    //login methods
    User StandardUserLogin(string username) {
        IDataContext db = new DataContext();
        var user = db.Users.SingleOrDefault(u => u.Authentication.LoginId == username);
        if (user != null) {
            if (user.Authentication.Password == password) {
                SetAuthenticationTicket(user);
                return user;
            }
        }
    }
    

    I would create a different login method for each type of login depending on how their authorization schemes work.

    User OpenIdUserLogin(string username) {
        IDataContext db = new DataContext();
        var user = db.Users.SingleOrDefault(u => u.Authentication.LoginId == username && u.Authentication.Provider == "openid");
        if (user == null) {
            //create new openid user
        }
    
        if (user.Authentication.LoginId == id) {
            SetAuthenticationTicket(user);
            return user;
            }
    }
    
    //openid's authentication method
    [ValidateInput(false)]
    public ActionResult Authenticate(string returnUrl) {
        IAuthenticationResponse response = OpenId.GetResponse();
    
        if (response == null) {
            //make openid request here
        } else {
            var user = OpenIdUserLogin(response.ClaimedIdentifier);
        }
    }
    

    Btw, the two classes at the top represent my Entity Framework POCOs The key here is the Authentication Table which is separate from the user table. It allows one user to have multiple methods of signing in. Hope this helps you get you on track.

提交回复
热议问题