YAFLogo

evak2979
  • evak2979
  • 58.6% (Neutral)
  • YAF Camper Topic Starter
10 years ago
So, as promised, here is my guide of using the new ASP NET MVC Identity system with YAF's Memebrhip Provider.

For those who know and have read up on Microsoft's latest experiment - Mictosoft has adopted OWIN (Open Web Interface) and, in particular, their own adaptation of OWIN called project Katana for handling authentication in MVC 5 (And onwards, or -so- they say).

What OWIN is, in plain English, is a mechanism that allows the developer to enable as many OWIN middleware components (OWIN's term for functionality implemented by various providers) in the hosting service - a lightweight means of only loading what you need to run. For more details on OWIN and Katana, this post has helped me a lot in understanding the basics:

http://msdn.microsoft.com/en-us/magazine/dn451439.aspx 

Now, one of the interesting things in MVC 5 when using OWIN are these two entries in web. config:

...

This, along with YAF running memembership provider had me confused for a long while - how does one use membership provider, which is tied to the FormsAuthentication parameter in web.config, when we now have to remove FormsAuthentication altogether from our web. config?

After many sleepless nights of frustration, and a few stack overflow visits, I came across the following post that revealed a huge truth:

http://brockallen.com/2012/06/04/membership-is-not-the-same-as-forms-authentication/ 

The title is a giveaway, but basically the truth of the matter is - membership and FormsAuthentication are not tied together; a common misconception plaguing many developers (including yours truly) for many a year. Poof. Out the window. Gone.

With that in mind, I integrated yaf 'net's web .config entries into my MVC 5 web config (excluding the FormsAuthentication) bit. Still paddling in unknown waters, I decided to use common sense. Hrm..There. I integrated membership, role, profile in web. config. But I felt like I was missing something important. Back to looking at YAF .NET's original web config:

now, I've already said, we CANNOT include the above in MVC 5.

YAF defines a name for its cookie on hello called .YAFNET_Authentication. Now, I am not SURE if this is of any important, or not, but call me cautious. Your MVC 5 project has created a Startup.cs class under App_Start (this can be configured to be anywhere - if you are familiar with OWIN, you're looking for the file containing your Configuration method). In the standard MVC 5 template, there's a call to ConfigAuth from within Configuration. Here's part of the magic that's taking place in ConfigAuth:

app.UseCookieAuthentication(new CookieAuthenticationOptions

{

AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,

LoginPath = new PathString("/Account/Login"),

......

CookieName = ".YAFNET_Authentication"

......

});

And this is where you can tune your cookie setup in OWIN. Notice the name I gave my cookie? Just in case, I've used the default name used in YAF NET Web Config.

Now, last but not least - disable registration in YAF NET, and Log In - you will be handling this from your own site. Most of the pipeline is already there. And here is the excerpt from my code:

For CREATING a user:

public async Task Register(RegisterViewModel model)

{

if (ModelState.IsValid)

{

var user = new ApplicationUser() { UserName = model.UserName, Email = model.Email };

var result = await UserManager.CreateAsync(user, model.Password);

if (result.Succeeded)

{

await SignInAsync(user, isPersistent: false);

//persist the user in the forum as well.

CreateYAFUser(model.UserName, model.Password, model.Email);

....

For Signing in with an exertnal provider (Facebook/Twitter etc etc):

public async Task ExternalLoginConfirmation(RegisterViewModel model, string returnUrl)

{

if (User.Identity.IsAuthenticated)

{

return RedirectToAction("Manage");

}

if (ModelState.IsValid)

{

// Get the information about the user from the external login provider

var info = await AuthenticationManager.GetExternalLoginInfoAsync();

if (info == null)

{

return View("ExternalLoginFailure");

}

var user = new ApplicationUser() { UserName = model.UserName, Email = model.Email };

var result = await UserManager.CreateAsync(user, model.Password);

result = await UserManager.AddLoginAsync(user.Id, info.Login);

if (result.Succeeded)

{

await SignInAsync(user, isPersistent: false);

CreateYAFUser(model.UserName,model.Password,model.Email);

return RedirectToLocal(returnUrl);

}

meaning :

Whenever you register someone locally, or whenever you're authenticating someone, register them in your YAF DB as well, using YAF methods. Which mehods you as? Here's the implementation for CreateYAFUser:

private static void CreateYAFUser(string sUsername, string sPassword, string email)

{

if (!YAFHelper.YAFUserExists(email))

{

YafMembershipProvider mb = (YafMembershipProvider)System.Web.Security.Membership.Providers["YafMembershipProvider"];

int? forumUserID = 0;

if (!mb.ValidateUser(sUserName, sPassword))

{

MembershipCreateStatus status;

MembershipUser forumUser = mb.CreateUser(sUserName, sUserName, sUserName, "question", "answer", true, null, out status);

// create the user in the YAF DB as well as sync roles...

forumUserID = RoleMembershipHelper.CreateForumUser(forumUser, 1);

RoleMembershipHelper.SetupUserRoles(1, sUserName);

RoleMembershipHelper.AddUserToRole(sUserName, "Registered");

// create empty profile just so they have one

YafUserProfile userProfile = YafUserProfile.GetProfile(sUserName);

userProfile.Homepage = "fwd.com";

// setup their inital profile information

userProfile.Save();

}

else

{

DataTable results = (DataTable)YAF.Classes.Data.LegacyDb.UserFind(1, false, sUserName, sUserName, sUserName, null, null);

//DataTable results = YAF.Classes.Data.DB.UserFind(1, false, sUserName, sUserName);

if (results.Rows.Count > 0)

{

forumUserID = (int)results.Rows[0]["UserID"];

}

}

}

And that's about it - for the first step that is. This works for me just fine. Every user I create on my site is persisted in the forums. Every time someone logs ont o my site whether locally or through an external provider, they are also logged on the Forums.

It's imperitive you register the same username on your site as you do when you call the forum's create user, as that username is being used (in my understanding) by the YAF membership provider. Any questions or problems, please respond to this thread and I'll do my best to lend a hand (though I am not an expert).

And if any YAF Admins want to replace the CreateYAF method with something more better and current, please feel free :)

Sponsor
deggen40
10 years ago
Did you have to do anything else to get login to work? I tried setting the cookiename = .YAFNET_Authentication, but that does not seem to be working.
evak2979
  • evak2979
  • 58.6% (Neutral)
  • YAF Camper Topic Starter
10 years ago
what are you trying to do exactly? 🙂
deggen40
10 years ago
I am trying to log in a user that I have created for both my site and the forum.
evak2979
  • evak2979
  • 58.6% (Neutral)
  • YAF Camper Topic Starter
10 years ago
What authentication are you using on your site?
deggen40
10 years ago
I'm using the OWIN authentication that comes with MVC5.
evak2979
  • evak2979
  • 58.6% (Neutral)
  • YAF Camper Topic Starter
10 years ago
You need to ensure the following:

Users need to have the same username/email on the forums as they do on the site.

When you create a user on your site, whether externally or internally, use the create user for YAF I have posted.

You have to remove forms authentication (if it is there) on your site config, from when you merged the web configs.

Give the cookie the same name as the above.

Now, once you log on with a user who has the same username and email as one in the forums, and you navigate to the forum, it will work.

deggen40
10 years ago
Could you help me out with this line a bit. I can't seem to find the bit of code to detect if a user exists.

YAFHelper.YAFUserExists(email)

Thanks!

EDIT: I found what I needed to call (YAF.Core.UserMembershipHelper.UserExists()).

evak2979
  • evak2979
  • 58.6% (Neutral)
  • YAF Camper Topic Starter
10 years ago
No problem, glad it works 🙂
deggen40
10 years ago
This works perfectly. Thanks for posting this!

The only problem I am having now is that I cannot log in with the (host) Admin user that was created when the forum was installed. Can I easily change a created user to the admin type?

Zero2Cool
  • Zero2Cool
  • 100% (Exalted)
  • YAF Leader YAF Version: YAF 3.1.16
10 years ago

This works perfectly. Thanks for posting this!

The only problem I am having now is that I cannot log in with the (host) Admin user that was created when the forum was installed. Can I easily change a created user to the admin type?

Originally Posted by: deggen40 

What happens when you try using the password reset feature on the Admin user?

deggen40
10 years ago
EDIT: I tried using the below to reset the password but it is not working either. mb.ResetPassword only returned null and I am not being logged into both YAF and my dev site.

YafMembershipProvider mb =(YafMembershipProvider)System.Web.Security.Membership.Providers["YafMembershipProvider"];

var reset = mb.ResetPassword(user.UserName, model.Password);

Is there a way that I can install the database without setting up an admin or also create the user on my mvc site?

deggen40
10 years ago
I think I have this figured out now. I created another user with the Role of administrator and in the YAF_User table I set Flags = 3 for that user.
silentcid
10 years ago
I've been looking to add YAF into a new MVC 5 project. Do I follow the YAF.NET Integration in to an existing ASP.NET Application tutorial with this tutorial? If so, do I use the SampleWebApplication to do it or the manually integrate one?

edit: I just been trying to integrate it with the regular install of yaf. I just got done with the cookies step of this tutorial. Right now, if I build and go into localhost/forum it gives me a 404 error saying it cannot find /forum/Forum.aspx. If I go to forum/install it will allow me to install the forums. I can get in also just fine with /forum/default.aspx. If I click on any of the links, it will give me the same 404 error. Not quite sure how to fix that. Anyone have an idea what it could be?

edit 2: I fixed my problem, it looks like my urlrewrite wasn't setup properly. Just need to make my actual MVC5 page to be the one to show up first.

silentcid
10 years ago
The line:

if (!YAF.Core.UserMembershipHelper.UserExists()) is saying, "No overload for method 'UserExists' takes 0 arguments seems to be where I'm stuck on currently. Not sure how to fix this particular line.

edit: nvm I fixed my problem.