I figure since people are starting to really look into MVC and are realizing that it’s going to be around for a while, they’re going to need some decent samples when researching how to do things. I’m hoping this particular post will possibly be one of those examples. I had the same thought when I wrote the Security Questions with ASP.NET MVC & fluentHtml post.
Let’s get started with the view model class for the sign in page. By the way, if you’re not familiar with the way I setup my MVC projects, see this post.
public class SignInView
{
[ValidateNonEmpty("Username is required.")]
public string Username { get; set; }
[ValidateNonEmpty("Password is required.")]
public string Password { get; set; }
}
Really simple. The ValidateNonEmpty is an attribute from the Castle project and I’m passing in the error message I want displayed if invalid.
Okay, so let’s go ahead and pass in this view model to our actual view from the AuthenticationController. This will look like this:
public ActionResult Index()
{
return View(new SignInView());
}
Now we’ll create our actual view (html):
<%=Html.DivValidationSummary("All fields are required.") %>
<form action="/authentication/index" method="post">
<fieldset>
<legend>Sign In</legend>
<p><%=this.TextBox(f => f.Username).Label("Username: ")%></p>
<p><%=this.Password(f => f.Password).Label("Password: ")%></p>
<%=Html.AntiForgeryToken() %>
<%=Html.SubmitButton("Sign In", cssclass=>"sb", accesskey=>"S") %>
</fieldset>
</form>
This is our basic html setup with fluentHtml added to it. If you need a tutorial on fluentHtml, here’s a post on it. Basically, I’m using my htmlHelper for a DivValidationSummary, I’m calling the index action on the authentication controller, then I’m setting up my textboxes with fluentHtml, using the antiforgerytoken to prevent csrf, and I’m using my submit button that I blogged about before this post.
Now let’s look at the action that’s being called by the form above.
[AcceptVerbs(HttpVerbs.Post), ValidateModel(typeof(SignInView)), ValidateAntiForgeryToken]
public ViewResult Index(SignInView form)
{
if (!ModelState.IsValid)
return View("index", form);
IUser user = DependencyRegistrar.With<string, IUser>(form.Username);
bool passwordMatches = _authenticationService.PasswordMatches(user, form.Password);
if (passwordMatches)
{
//Sign In – Write Cookie & Redirect most likely through a UserSession
}
ModelState.AddModelError("SignIn", "Invalid credentials");
return View("index", form);
}
Okay, so you can see I’m accepting only post, I’m validating the model, and I’m validating the token. I’m also accepting my SignInView model. If the model state is not valid I return the model back to the view. Otherwise, I get an instance of user with my username and then I call my authenticationService. If passwordMatches, sign in and return, otherwise add an error and return.
So let’s look at my IUser real quick. It’s really simple:
public interface IUser
{
string Username { get; set; }
}
Think my AuthenticationService is much more difficult? Of course not!
public interface IAuthenticationService
{
bool PasswordMatches(IUser user, string password);
}
By the way, I’m accepting an instance of IAuthenticationService in the constructor of the controller like so:
public AuthenticationController(IAuthenticationService authenticationService)
{
_authenticationService = authenticationService;
}
I’m using StructureMap to know what to pass in to the constructor. Okay, so my AuthenticationService implementation looks like this:
public class AuthenticationService : IAuthenticationService
{
private readonly IActiveDirectorySettings _adSettings;
public AuthenticationService(IActiveDirectorySettings activeDirectorySettings)
{
_adSettings = activeDirectorySettings;
}
public bool PasswordMatches(IUser user, string password)
{
var authenticated = false;
var domainAndUsername = _adSettings.DomainName + "\\" + user.Username;
var entry = new DirectoryEntry("LDAP://" + _adSettings.LdapPath, domainAndUsername, password);
try
{
var bindToNativeObjectToForceAuthentication = entry.NativeObject;
authenticated = true;
}
catch (COMException)
{
}
return authenticated;
}
}
Now my IActiveDirectoryCredentials looks like this:
public interface IActiveDirectorySettings
{
string DomainName { get; }
string LdapPath { get; }
}
That’s basically it. There’s not a whole lot to an authentication process, but thought I’d share anyhow.
Thanks for reading!
Wе're a gaggle of volunteers and opening a brand new scheme in our community. Your web site provided us with useful info to work on. You have performed a formidable job and our whole group will be grateful to you.
ReplyDeleteMy page > www.prweb.com
It is appropriate time to make some plans for the future and it is time to be happy.
ReplyDeleteI have read this post and if I could I wish to suggest you few interesting
things or suggestions. Perhaps you could write next articles referring to this article.
I desire to read even more things about it!
my webpage; lowcarb ernährung
Wаy cool! Somе extremely valid points! I appreciate yоu writing thiѕ
ReplyDeletearticlе аnd also the rest оf the ωеbsite is еxtrеmely good.
Check out my web-site - planetside 2 aimbot
naturally like your web site but you have to take a look at
ReplyDeletethe spelling on several of your posts. Several of them are rife with
spelling issues and I to find it very bothersome to inform the reality nevertheless I'll certainly come back again.
Stop by my web-site: low carb riegel
Revitοl cream is far more of а prevеntative rather thаn a
ReplyDeletereѕolutіon.
Check out mу web-sitе - http://www.mailspect.ru/
Also see my site :: http://www.prnewswire.com/news-releases/trilastin-review-and-latest-coupon-code-savings-released-at-awesomealldaycom-190256601.html
Great blog here! Additionally your web site so much up fast!
ReplyDeleteWhat web host are you using? Can I am getting your associate hyperlink on
your host? I desire my web site loaded up as quickly as yours lol
Here is my web blog ... anlageberater wiesbaden
It's actually a great and useful piece of info. I'm happy that you shared this helpful info with us.
ReplyDeletePlease keep us up to date like this. Thank you for
sharing.
My homepage - paleo gerichte
Their workout routines are even available on i - Tunes
ReplyDeletefor a small fee. Besides, people who are drinking
enough fluids is a day usually have clearer complexion so drink
up. I am aware this seems enjoy ridiculous advice - Get real if you may possibly just flip a
switch and enjoy exercise you would certainly, right.
Also visit my webpage; Women Fitness Tips Abs
Highly energetic article, I enjoyed that a lot. Perhaps there is part
ReplyDeleteTwo?
My weblog; www.firecrew77.com
Sometimes funny pictures are created automatically, and now need a little time to
ReplyDeleteour own. If you have wandered around the internet to any extent you have probably encountered funny pictures.
Many of the paintings have a tendency to use a signature in order to improve a funny message that's shown in the photo.
my homepage ... linked web-site
Hello, I log on to your new stuff like every week.
ReplyDeleteYour story-telling style is awesome, keep it up!
Feel free to visit my website ... please click the following internet site
They do not insert secret or additional advertising in our material.
ReplyDeleteo To make sure that the funny element remains intact inside your text
message, keep that short and simple. The videos relax,
they make people smile and as they say, laughter
is the best medicine.
My web site - http://brightbluehosting.com
One can find lot of such funny sports moments very easily.
ReplyDeleteThat is why we have dedicated this page to
help you renew your spirit and perhaps have a few laughs too.
However, for the next several miles until we got to our hotel, he smelled pretty dog-gone good, not.
My webpage ... funny pictures at walmart top rated
Helping optimistic people excel - in 7 areas of life is
ReplyDeleteher mission. Men can follow these health and fitness tips to lose weight and get healthy and
fit. These tips are followed by every pregnant woman all around the world but remember whatever you do, you should first check with your gynecologist
so that there is no complication in your pregnancy.
Feel free to visit my website: pt.wiki.aktivix.org
Helping optimistic people excel - in 7 areas of life is her mission.
ReplyDeleteEven if your small business doesn't have some sort of refrigerator (a rarity today) you can choose vegetable and fruit that do not even require refrigeration. The decisive factor is that men would want to show themselves as hot and rock solid before the fashionable ladies as ever.
Feel free to visit my homepage: fitness tips at home
It's great that you are getting ideas from this post as well as from our dialogue made at this place.
ReplyDeleteMy page: Biotechnology Companies
For centuries, man has been exploiting biology to make food products such as bread,
ReplyDeletebeer, wine, and cheese. Many of these focus on treating various types of cancer, as
well as genetic disorders. This means that by the time elementary school-age children reach the workplace, this
system will be in place, requiring maintenance and advancements.
My web site; shbab.twhed.com/blogs/21095/22200/a-guide-to-necessary-criteria-of
There is a growing need to meet the growing demand for biotechnology professionals and qualified graduates produced by universities in the United States.
ReplyDeleteThe firm has invested over US$750 million in more than 120 companies throughout
the United States and the Greater China region. In reality,
once a patent is issued, the inventor or patent owner (i.
My blog post: solseeds.com/RoseDanie
So, while I am no roving reporter I am endeavoring with my menial reporting skills, to
ReplyDeletebring you. I have more stuffings in me from yesterday than I care to think
about. Due to the recent horrifying terror attacks and other such couple
of events people want to be aware and alerted of the whereabouts of the nation.
Feel free to visit my web-site Latest Daily News
I also Love playing Online Games, Contest and Challenges. If you have wandered around the internet to any extent
ReplyDeleteyou have probably encountered funny pictures. simply keep in mind few websites that may lead you to fun and
smiles on face.
My blog post; lol pictures
People sometimes tend to think, “if only I were a celebrity, everything would be better”.
ReplyDeleteYou can give tips to the workers in the salon, restaurants where the star visit frequently.
With this online store you need not worry about being fooled because the site is
accorded security.
Also visit my weblog latest celeb news
Everything is very open with a clear explanation
ReplyDeleteof the challenges. It was definitely informative. Your site is extremely helpful.
Thank you for sharing!
my weblog: cellulite treatment reviews