YAFLogo

Mikael
  • Mikael
  • 51.8% (Neutral)
  • YAF Forumling
7 years ago
Hello,

I try to integrate a forum in a existing .net MVC website.

For now I don't want to merge the authentication. I use the MVC authentication for the website and the default YAF authentication on the forum.

https://github.com/YAFNET/YAFNET/wiki/YAF.NET-Integration-in-to-an-existing-ASP.NET-Application 

My problem is that it seems I can log in (I enter my login and my password and I haven't error message), but when I am redirected on the homepage I'm not connected.

Do you have an idea to solve this problem ?

mattharper
6 years ago
I cannot thank you enough for posting this. I have struggled with this for the past week. I understood perfectly well how MVC membership and profiles work. The part that I was missing was simply that I don't need to utilize the Forms Auth for YAF. This was driving me insane. Genius to try the cookie name in existing Startup.Auth for MVC. I was a bout to manually maintain a sych between the two since I wasted so much time on this.

I am going to add a little more code here for anyone else coming to this post.

If you have the the default account controller from the MVC Template from VS.NET (AccountController.cs), here are the changes you need to make to it.

1. Add the references.

Quote:

using YAF.Utils;

using YAF.Core;

using System.Web.Security;

using YAF.Providers.Membership;

using System.Data;

2. Alter Register

Quote:

// POST: /Account/Register

[HttpPost]

[AllowAnonymous]

[ValidateAntiForgeryToken]

public async Task Register(RegisterViewModel model)

{

if (ModelState.IsValid)

{

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

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

if (result.Succeeded)

{

await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

http://go.microsoft.com/fwlink/?LinkID=320771 

// Send an email with this link

// string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

// var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);

// await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking here");

//mjh -- Persist the user in the YAF forums as well.

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

return RedirectToAction("Index", "Secure");

}

AddErrors(result);

}

// If we got this far, something failed, redisplay form

return View(model);

}

3: ExternalLoginConfirmation

Quote:

// POST: /Account/ExternalLoginConfirmation

[HttpPost]

[AllowAnonymous]

[ValidateAntiForgeryToken]

public async Task ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)

{

if (User.Identity.IsAuthenticated)

{

return RedirectToAction("Index", "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.Email, Email = model.Email };

var result = await UserManager.CreateAsync(user);

if (result.Succeeded)

{

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

if (result.Succeeded)

{

await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

CreateYAFUser(user.UserName, user.PasswordHash, model.Email);

return RedirectToLocal(returnUrl);

}

}

AddErrors(result);

}

ViewBag.ReturnUrl = returnUrl;

return View(model);

}

4. Add CreateYAFUser (I added mine to AccountController as static. Put it where ever you want.)

Quote:

#region YAF User Sync with MVC Membership

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

{

if (!UserMembershipHelper.UserExists(sUserName, email))

{

YafMembershipProvider mb = (YafMembershipProvider)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"];

}

}

}

}

#endregion

5. Fix login and register links in YAF or remove them completely.

Quote:

Use something like this depending on your particular site structure for the YAF Links

https://localhost:44300/Account/VerifyCode/?provider=matt&returnUrl=%2Fforum%2FForum.aspx&rememberMe=true

and inside VerifyCode do a redirect to returnURL

Thanks Again!

marcelocabrera
6 years ago
HI Jumping in late on this....

I followed your example and it always seems to find the user as an existing user, in other words:

if (!UserMembershipHelper.UserExists(sUserName, email))

always returns true, so I think it is looking in the MVC 5 indentity tables, not on the YAF user tables, how do I know the static class YAF.Core.UserMembershipHelper is using the right tables?

Thanks,

MC

clubnp
  • clubnp
  • 50.6% (Neutral)
  • YAF Forumling
6 years ago
Hate to necro this thread, but I think its pretty relevant and useful if someone has the answer...

I'm a fairly experienced web forms programmer, currently learning MVC and wanted to implemented YAF into a site.

In the above post user's mention this line:

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

But LegacyDb.UserFind no longer exists in the current source code. It looks like the current code is using some sort of (I'm guessing) dependency injection?? I'm not really sure how to do what I need in this scenario. Is there an alternative to the code above??

Thanks! 🙂

Edit: It feels kind of hackish, but looking at the old code something like this might work:


else
				{
                    DataTable results = 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"];
					}
				}
			}
		}

		public static DataTable UserFind(int boardID,bool filter, [NotNull] string userName, [NotNull] string email, [NotNull] string displayName, [NotNull] object notificationType, [NotNull] object dailyDigest)
        {		
            using (var cmd = DbHelpers.GetCommand("user_find"))		
            {		
                cmd.CommandType = CommandType.StoredProcedure;		
		
                cmd.Parameters.AddWithValue("BoardID", boardID);		
                cmd.Parameters.AddWithValue("Filter", filter);		
                cmd.Parameters.AddWithValue("UserName", userName);		
                cmd.Parameters.AddWithValue("Email", email);		
                cmd.Parameters.AddWithValue("DisplayName", displayName);		
                cmd.Parameters.AddWithValue("NotificationType", notificationType);		
                cmd.Parameters.AddWithValue("DailyDigest", dailyDigest);

				return LegacyDb.DbAccess.GetData(cmd);	
            }		
        }

Edit 2: Now that I look at it... what's the point of the else statement? Debugging?