How to decrypt password in MVC5? - asp.net-mvc

I am using MVC5, i know that if a user forgets his password, then MVC provides the feature of forgot password and reset password.
My client server is disconnected from internet or mailing, it is behind the firewalls, so i cannot use forgot password, as it might generate a link to reset password, but cannot mail it to the user to facilitate the password reset.
Please suggest if there is any way to decrypt the password(to let user know if he forgets his password) like how it was available in asp.net membership by simply using the GetPassword method of the membership classes.
Thank you

As far I know there is no easy way to do this in MVC5, because Identity (next gen of Membership) is using hash of password rather then encrypted password.
Password is hashed and stored in db as a hash - generally it's one-way operation (it's mean that there is no easy way to get password form hash).
Little bit more about what is hashing and salting you can read here:
How to securely store passwords and beat the hackers
How does hashing work?

This step to Ecrypt and decrypt password in asp.net mvc5.
create class name Hashing, paste this code
private static string GetRandomSalt()
{
return BCrypt.Net.BCrypt.GenerateSalt(12);
}
public static string HashPassword(string password)
{
return BCrypt.Net.BCrypt.HashPassword(password, GetRandomSalt());
}
public static bool ValidatePassword(string password, string correctHash)
{
return BCrypt.Net.BCrypt.Verify(password, correctHash);
}
Create controller login you past this code
using WebBcryptMVC.Models; //
using WebBcryptMVC.Util; // call folder name of Hashing class
namespace WebBcryptMVC.Controllers
{
public class LoginController : Controller
{
private DBLoginEntities db = new DBLoginEntities();
public ActionResult frmLogin()
{
return View("frmLogin", new tblLogin());
}
[HttpPost]
public ActionResult frmLogin(tblLogin account)
{
var currentAccount = db.tblLogins.First(a => a.UserName.Equals(account.UserName));
if ((currentAccount != null))
{
if (Hashing.ValidatePassword(account.Password, currentAccount.Password))
{
Session.Add("UserName", account.UserName);
//return View("~/Views/Home/frmHome.cshtml");
return RedirectToAction("frmHome", "Home");
}
else
{
ViewBag.error = "Invalid";
return View("frmLogin");
}
}
else
{
ViewBag.error = "Invalid";
return View("frmLogin");
}
}

Related

Displaying the fullname (firstname, lastname) of the logged in user

I work on an ASP.NET MVC4 solution. When the user is logged in, I would like to display his fullname (not the username provided in the login form). His fullname (firstname + lastname actually stored in the user table in my database) should be displayed in the top right corner.
For better performance, I don't want to query the database each time a request is done.
How to proceed?
Keeping the user information (firstname, lastname, ...) in a cookie?
Keeping the user information is a session variable for all the lifecycle of the application?
Keeping the user information in a 'Profile' like explained here: How to assign Profile values? (*)
Something else?
(*) I think this solution a little complex for the use I have.
Thanks.
I would use a cookie. It doesn't hog up any memory on your machine like Session, and it doesn't hit the database like Profile would. Just remember to delete the cookie when the user signs off.
Note that the Profile would hit the database server each time you make a request. As far as I know, Profile data is not cached anywhere on the web server (unless you have a custom profile provider).
Another reason why I like cookie: if you ever want to store any additional user information for fast access, like UserPrimaryKey, or any special user preferences, you can just store them as JSON in the cookie. Here is an example:
Another note: the code below uses Newtonsoft.Json (the JsonConvert lines). It should come out of the box in an MVC4 project, but for an MVC3 project, you can just add it via nuget.
public class UserCacheModel
{
public string FullName { get; set; }
public string Preference1 { get; set; }
public int Preference2 { get; set; }
public bool PreferenceN { get; set; }
}
public static class UserCacheExtensions
{
private const string CookieName = "UserCache";
// put the info in a cookie
public static void UserCache(this HttpResponseBase response, UserCacheModel info)
{
// serialize model to json
var json = JsonConvert.SerializeObject(info);
// create a cookie
var cookie = new HttpCookie(CookieName, json)
{
// I **think** if you omit this property, it will tell the browser
// to delete the cookie when the user closes the browser window
Expires = DateTime.UtcNow.AddDays(60),
};
// write the cookie
response.SetCookie(cookie);
}
// get the info from cookie
public static UserCacheModel UserCache(this HttpRequestBase request)
{
// default user cache is empty
var json = "{}";
// try to get user cache json from cookie
var cookie = request.Cookies.Get(CookieName);
if (cookie != null)
json = cookie.Value ?? json;
// deserialize & return the user cache info from json
var userCache = JsonConvert.DeserializeObject<UserCacheModel>(json);
return userCache;
}
}
With this, you can read / write the cookie info from a controller like this:
// set the info
public ActionResult MyAction()
{
var fullName = MethodToGetFullName();
var userCache = new UserCache { FullName = fullName };
Response.UserCache(userCache);
return Redirect... // you must redirect to set the cookie
}
// get the info
public ActionResult MyOtherAction()
{
var userCache = Request.UserCache();
ViewBag.FullName = userCache.FullName;
return View();
}

Using OpenID/OpenAuth in MVC3 app with overridden authentication method

We override the basic authentication in an MVC3 application by calling a webservice with the user's credentials and returning a WCF structure that contains the user's ID, a "LogonTicket". This LogonTicket is used to "authenticate the user for each call made to the webservice.
Now, we override by replacing the defaultProvider in the Web.config. All we do in this overridden provider is
to override the ValidateUser() function. That is where we call the web service with their credentials and return
the "LogonTicket".
This is the LogOn() function from our AccountController, essentially the base code from the template:
public ActionResult LogOn(LogOnModel model)
{
string ReturnUrl = "";
if (HttpContext.Request.UrlReferrer.Query.Length > 11)
{
ReturnUrl = Uri.UnescapeDataString(HttpContext.Request.UrlReferrer.Query.Substring(11));
}
if (ModelState.IsValid)
{
if (Membership.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
if (Url.IsLocalUrl(ReturnUrl) && ReturnUrl.Length > 1 && ReturnUrl.StartsWith("/")
&& !ReturnUrl.StartsWith("//") && !ReturnUrl.StartsWith("/\\"))
{
return Redirect(ReturnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
ViewBag.MainWebsite = MainWebsite;
return View(model);
}
This is the overridden ValidateUser() function from our new default provider:
public override bool ValidateUser(string username, string password)
{
MyServiceClient mps = new MyServiceClient();
string sha1password = HashCode(password);
LogonInfo logonInfo = mps.GetLogonTicket(username, sha1password);
if (logonInfo.LogonTicket != "" && logonInfo.LogonTicket != "0")
{
// Authenticated so set session variables
HttpContext.Current.Session["LogonTicket"] = logonInfo.LogonTicket;
HttpContext.Current.Session["ParticipantID"] = logonInfo.ParticipantID;
return true;
}
else
{
return false;
}
}
I'm not really sure how to combine the use of the two, so my questions are:
How can I implement OpenID and Facebook logins and keep my current authentication method?
How can we "map" the OpenID user with our current user DB values? We MUST know so we can retrieve their info.
I know we can retrieve their email address but what if their OpenID email is different than the one they use for their record on our site?
Are there any examples of how to do this, anywhere?
Thanks for looking at my question.
I have done a project which required multiple log-on possibilities (custom account, Google and Facebook)
In the end your authentication with ASP.NET is entirely dependant on your configuration. (In your case it is FormsAuthentication) this means that FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe); basicly determines everything in regard to your user and where you set this isn't restricted.
You have now basicly the same implementation as we started out with, using a MembershipProvider to handle your own custom account. You only need to expand now to facilitate the openIds. You would have to expand your Controller with various actions for each login type (Now you have ActionResult LogOn() you can add to that for example: ActionResult LogOnOpenId()). Inside that method you basicly call the same code but instead of Membership.ValidateUser(model.UserName, model.Password) you call the OpenId services.
I have provided below an example of our google implementation using dotnetopenauth. The service method uses formsService.SignIn(userId.Value.ToString(), false); which basicly calls FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe); (we only do some custom behaviour there in regard to the SecurityPrincipal but this doesn't affect your Authentication process). You can also see that we make a new account when we receive a new user. To solve your question part 2 we have implemented a profile which can be merged if you can provide another login. This allows our users to keep their account consolidated and use whatever login method they like.
For examples in regard to multiple signons I will refer to the answer of Tomas whom referenced StackExchange as a good example. Also I'd advise you to install MVC4 and VS2012 and just do a File > New Project. The newest default template of MVC includes openid implementation alongside a custom login!
Example google openid implementation:
The controller method:
public virtual ActionResult LoginGoogle(string returnUrl, string runAction)
{
using (var openId = new OpenIdRelyingParty())
{
IAuthenticationResponse response = openId.GetResponse();
// If we have no response, start
if (response == null)
{
// Create a request and redirect the user
IAuthenticationRequest req = openId.CreateRequest(WellKnownProviders.Google);
var fetch = new FetchRequest();
fetch.Attributes.AddRequired(WellKnownAttributes.Name.First);
fetch.Attributes.AddRequired(WellKnownAttributes.Name.Last);
fetch.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
fetch.Attributes.AddRequired(WellKnownAttributes.Preferences.Language);
req.AddExtension(fetch);
req.RedirectToProvider();
return null;
}
_service.ConnectViaGoogle(response, TempData);
}
The service method:
public void ConnectViaGoogle(IAuthenticationResponse response, TempDataDictionary tempData)
{
// We got a response - check it's valid and that it's me
if (response.Status == AuthenticationStatus.Authenticated)
{
var claim = response.GetExtension<FetchResponse>();
Identifier googleUserId = response.ClaimedIdentifier;
string email = string.Empty;
string firstName = string.Empty;
string lastName = string.Empty;
string language = string.Empty;
if (claim != null)
{
email = claim.GetAttributeValue(WellKnownAttributes.Contact.Email);
firstName = claim.GetAttributeValue(WellKnownAttributes.Name.First);
lastName = claim.GetAttributeValue(WellKnownAttributes.Name.Last);
language = claim.GetAttributeValue(WellKnownAttributes.Preferences.Language);
}
//Search User with google UserId
int? userId = _userBL.GetUserIdByGoogleSingleSignOnId(googleUserId);
//if not exists -> Create
if (!userId.HasValue)
{
_userBL.CreateGoogleUser(
googleUserId,
firstName,
lastName,
email,
language,
DBConstants.UserStatus.DefaultStatusId,
out userId);
}
if (userId.HasValue)
{
_userBL.UpdateLastLogon(userId.Value);
var formsService = new FormsAuthenticationService();
formsService.SignIn(userId.Value.ToString(), false);
AfterLoginActions(tempData);
}
}
}
Any questions or comments? I'll gladly hear them.
it should be perfectly possible to have multiple authentications methods. All IIS / ASP.net cares about is the FormsAuthentication cookies. So you would have one set of actions for your standard username/password auth, and another for OpenId. This is at least what I have done on one project.
You can't even trust the openId provider to give you an email address! A common solution to this problem is to allow a user to attach multiple OpenId identifiers (URI's) to the his account after logging in. This is e.g. how StackOverflow works. If this is the first time the user visits the system then you can auto create a new account, or force the user through a signup process.
When I added the OpenId support in the system mentioned, it had an existing table used to store username and password(users table). I added a new table with a many to one relationship with the users table, and used this to store the URI's.
As mentioned above StackOverflow it self is a good place to start, also there are a lot of good examples in the http://www.dotnetopenauth.net/ project.
As far as I know the source of SO is not public, and they are using the dotnetopenauth project.
This may be to abstract, but this library is a openId (among other things) for the open source orchard CMS: http://orchardopenauth.codeplex.com/
I hope this helps, but if you have any questions then please expand your question with more details.

2-Step Authentication in ASP.Net MVC

I am working on an ASP.Net Mvc 3 application using FormsAuthentication with a custom MembershipProvider (so I do have some control over what the provider returns).
The requirements mandate a 2-step authentication process (username and password followed by secret question). A user should not be able to access any of the "secure" sections of the site without passing both steps. Please don't mention whether this is multi-factor security or not, I already know.
Please provide a recommendation on how to best accomplish this task.
Here are some considerations:
I am allowed (architecturally) to use session - would prefer not to.
I would prefer to use the out-of the box [Authorize] ActionFilter for Controllers providing secure content.
The people in charge would like for the url for the 2 steps to be the same: i.e. www.contoso.com/login/. In my attempts at least, this has caused some minor-but-not-insignificant issues when users enter an incorrect answer in the second step (they are not officially logged in, but I need to ensure that I am still working against the half-authenticated user's secret question/answer).
Thanks.
Use a custom View Model in conjunction with hidden form fields. Just make sure it's all done over https.
ViewModel
public LoginForm
{
public string UserName { get; set; }
public string Password { get; set; }
public int SecretQuestionId { get; set; }
public string SecretQuestion { get; set; }
public string SecretQuestionAnswer { get; set; }
}
Action Methods
public ActionResult Login()
{
var form = new LoginForm();
return View(form);
}
[HttpPost]
public ActionResult Login(LoginForm form)
{
if (form.SecretQuestionId == 0)
{
//This means that they've posted the first half - Username and Password
var user = AccountRepository.GetUser(form.UserName, form.Password);
if (user != null)
{
//Get a new secret question
var secretQuestion = AccountRepository.GetRandomSecretQuestion(user.Id);
form.SecretQuestionId = secretQuestion.Id;
form.SecretQuestion = secretQuestion.QuestionText;
}
}
else
{
//This means that they've posted from the second half - Secret Question
//Re-authenticate with the hidden field values
var user = AccountRepository.GetUser(form.UserName, form.Password);
if (user != null)
{
if (AccountService.CheckSecretQuestion(form.SecretQuestionId, form.SecretQuestionAnswer))
{
//This means they should be authenticated and logged in
//Do a redirect here (after logging them in)
}
}
}
return View(form);
}
View
<form>
#if (Model.SecretQuestionId == 0) {
//Display input for #Model.UserName
//Display input for #Model.Password
}
else {
//Display hidden input for #Model.UserName
//Display hidden input for #Model.Password
//Display hidden input for #Model.SecretQuestionId
//Display #Model.SecretQuestion as text
//Display input for #Model.SecretQuestionAnswer
}
</form>
If you're not happy with sending the username and password back to the view in hidden fields to re-authenticate and make sure they're not cheating... you could create a HMAC or something like that to test.
Btw, this question seems like a few questions rolled into one... so just answered how to do 2-step authentication with one view / action method.
I would probably do something where the first step makes them enter a username and password. Check it, if its good, move them along to an authorize flagged view that asks them to put in the answer to the question. If they fail that, sign them out, boot them out, whatever. I don't think this is possible in one view, unless you render a partial view and if they leave without finishing the authentication process, you sign them out and clear their cookie.
----EDIT-----
On second thought, you could do a partial view, just dont formsauth sign them in until they complete the second part of the partial view. Some psuedo code:
public ActionResult Login(){
get username and password off the view
if its valid
render a partial view that asks for the secret answer
if thats valid
forms auth login
else
try again, get booted, or whatever
else
get booted, try again, whatever
}

Which part of an application should be responsible for hashing a user's password?

I'm writing an ASP.NET MVC application which will provide user registration functionality but i am not sure which part of the application (e.g. User Domain model object, Controller, ViewModelMappers) should be responsible for hashing the user's password. I have a registration page that uses a strongly typed ViewModel and a Register action in my UserController as shown:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Register(UserRegisterViewModel userRegisterViewModel)
{
var user = userViewModelMapper.Map(userRegisterViewModel);
INotification validationResult = user.ValidateForRegistration(userRepository);
if (!validationResult.HasErrors)
{
user.HashPassword();
userRepository.AddOrUpdate(user); // i'm using NHibernate
return View("RegistrationAcknowledgement");
}
foreach (IError error in validationResult.Errors)
ModelState.AddModelError(error.Property, error.Message);
ViewData["country"] = new SelectList(countryRepository.GetAll(), "Code", "Name", userRegisterViewModel.Country);
return View("RegistrationForm", userRegisterViewModel);
}
User objects are composed in part by LoginDetail objects as shown and to avoid exposing the internals of the User object beyond what is absolutely required the Password Property is read-only. So i cannot for example do user.LoginDetails.Password = hashedandSaltedPassword;
namespace XXXX.Core.Model
{
public class User
{
private LoginDetails loginDetails;
public virtual LoginDetails LoginDetails
{
get { return loginDetails; }
private set { loginDetails = value; }
}
public virtual void AssignLoginDetails(LoginDetails loginDetails)
{
this.loginDetails = loginDetails;
}
public virtual void HashPassword()
{
IHashGenerator hashGenerator = new HashGenerator(new SaltGenerator());
IHashResult hashResult = hashGenerator.GenerateHash(loginDetails.Password, HashAlgoritm.SHA512);
loginDetails.Password = String.Concat(hashResult.HashValue, hashResult.Salt);
}
}
}
namespace XXXX.Core.Model
{
public class LoginDetails
{
private string username;
private string password;
private string confirmPassword;
private string passwordReminder;
private bool changePassword;
// Properties
#region Constructors
...
public LoginDetails(string username, string password, string confirmPassword, string passwordReminder, bool changePassword)
{
this.username = username;
this.password = password;
this.confirmPassword = confirmPassword;
this.passwordReminder = passwordReminder;
this.changePassword = changePassword;
}
}
}
Currently the responsibility for hashing the password is owned the User (by means of the HashPassword method) but
1. Is this a correct responsibility for the User to have (within the context of DDD and Single Responsibility principle)
2. If not, where should this operation reside?
3. If so, should it be called from the controller as i am doing?
Thanks
Without reading your code, I would argue hashing the password should be done in the model so it can be reused outside of the MVC framework. This tends to be true in all MVC frameworks that are implemented in languages general enough to be useful outside of the web.
Let's take a step back and look at the broader picture: when do we want to take a password in clear and hash it?
when the user is creating or
changing their password, and we need
to store it
when the user is logging in, and we
need to compare the entered
password with the the stored one
Currently your implementation addresses only the first instance. So you need a method which accepts a clear password and returns a hashed one.
As for where that method should go ...
The Single Responsibility Principle does not mean that a class does literally one thing. It means that the class handles only things which are clearly within its remit.
So, consider is the relationship between User and hashed password. Can you have a User wthout a hashed password? Will you ever want to work with a hashed password without its User? Do you have other objects which have a hashed password besides User? If the answer to those questions is "No" then I would argue that the password hashing method clearly belongs to the User class, and indeed increases its cohesiveness.

ASP.NET MVC - HTTP Authentication Prompt

Is it possible to make my application ask for username and password prompting for it before render a view?
Just like on twitter API to get information about your account:
http://twitter.com/account/verify_credentials.xml
So before render the view || file it asks you to insert you username and password, I think this is made directly on the server since the curl request is based on username:password as well like this:
curl -u user:password http://twitter.com/account/verify_credentials.xml
As I'm trying to build an API following the same structure I would like to know how I can do this on ASP.NET MVC C#. I've already used this on ruby rails and its pretty simple like:
before_filter :authenticate
def authenticate
authenticate_or_request_with_http_basic do |username, password|
username == "foo" && password == "bar"
end
I don't think that [Authorize] filter is the same since I believe it's just a redirection,
and it redirects you to the Accounts Internal Controller that is based on the accounts database, in this case I will use another database, specifically from a webservice and do the validation after the information is submitted.
But I need the action to require the user and pass credentials on its request.
Thanks in advance
UPDATE:
Actually to request a page that requires this authentication (i.e. Twitter)
I would have to declare this on its request
request.Credentials = new NetworkCredential("username", "password");
And this would reflect that prompted username and password.
So, it's exactly the same thing but from the other side, if it's possible to provide information to the authentication prompt on request, how could I require this authentication on the request instead?
So everytime somebody tries to make a request to my application on example:
http://myapplication/clients/verify_credentials
it should ask for a username and password with that server prompt
so to retrive information on curl for example it would be like this
curl -u user:password http://myapplication/clients/verify_credentials
Well, to require basic authentication you need to return 401 status code. But doing that will cause the current authentication module to execute its default unauthorized handler (for forms authentication, this means redirecting to login page).
I wrote an ActionFilterAttribte to see if I can get the behaviour you want when there's no authentication module installed in web.config.
public class RequireBasicAuthentication : ActionFilterAttribute {
public override void OnActionExecuting(ActionExecutingContext filterContext) {
var req = filterContext.HttpContext.Request;
if (String.IsNullOrEmpty(req.Headers["Authorization"])) {
var res = filterContext.HttpContext.Response;
res.StatusCode = 401;
res.AddHeader("WWW-Authenticate", "Basic realm=\"Twitter\"");
res.End();
}
}
}
And the controller action :
[RequireBasicAuthentication]
public ActionResult Index() {
var cred = System.Text.ASCIIEncoding.ASCII
.GetString(Convert.FromBase64String(
Request.Headers["Authorization"].Substring(6)))
.Split(':');
var user = new { Name = cred[0], Pass = cred[1] };
return Content(String.Format("user:{0}, password:{1}",
user.Name, user.Pass));
}
That action successfully prints the username and password I enter. But I really doubt that's the best way to do this. Do you have no choice except asking for username and password this way?
You really want to create a service and not a web application, based on what I have read. I am guessing here, but I think you picked ASP.NET MVC to take advantage of the routing and building the URL's the way you want? Correct me if I am wrong.
In my opinion the best way to solve the problem you are having is to build RESTful web services with WCF if you are returning data. This article should help you get started if you want to go this route.
Otherwise, you will need to go further up the stack for handling the request and authenticating it. If this is the case, I can help with providing more info and code.
I modified the çağdaş answer to put the whole logic inside my custom ActionFilter attribute.
public class BasicAuthenticationAttribute : ActionFilterAttribute
{
public string BasicRealm { get; set; }
protected string Username { get; set; }
protected string Password { get; set; }
public BasicAuthenticationAttribute(string username, string password)
{
this.Username = username;
this.Password = password;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var req = filterContext.HttpContext.Request;
var auth = req.Headers["Authorization"];
if (!String.IsNullOrEmpty(auth))
{
var cred = System.Text.ASCIIEncoding.ASCII.GetString(Convert.FromBase64String(auth.Substring(6))).Split(':');
var user = new { Name = cred[0], Pass = cred[1] };
if (user.Name == Username && user.Pass == Password) return;
}
var res = filterContext.HttpContext.Response;
res.StatusCode = 401;
res.AddHeader("WWW-Authenticate", String.Format("Basic realm=\"{0}\"", BasicRealm ?? "Ryadel"));
res.End();
}
}
It can be used to put under Basic Authentication a whole controller:
[BasicAuthenticationAttribute("your-username", "your-password",
BasicRealm = "your-realm")]
public class HomeController : BaseController
{
...
}
or a specific ActionResult:
public class HomeController : BaseController
{
[BasicAuthenticationAttribute("your-username", "your-password",
BasicRealm = "your-realm")]
public ActionResult Index()
{
...
}
}
NOTE: The above implementation requires the developer to manually insert the username and password as ActionFilter required parameters but can be easily extended to make it support any authorization mechanism (MembershipProvider, ASP.NET Identity, custom userbase on an external DBMS or file, etc.) by removing the custom constructor and modifying the OnActionExecuting method IF block accordingly.
For additional info, you can also read this post I wrote on my blog.
Here's the way that has worked for me. It's a little foot work but it will make IIS and MVC3 behave a lot more like all the other Basic Http authentication systems, like Apache...
Step 1.
Make sure "Basic Authentication" is installed for IIS.
( Example: Control Panel -> Programs and Features -> Turn Windows features on or off )
*I'm using Windows 7 at the moment and am not sure the exact path. [GOOGLE: installing basic authentication in IIS] should get you close.
Step 2.
Make sure Basic Authentication is enabled under your site. If you had to install this in the previous step you need to make sure you reset the IIS service and that all the app pools actually went down.
Step 3.
(Note: I am using MVC3, and feel this should work in most models, including ASP.Net, without a lot of fuss.)
In your project you will need to add the following classes:
public class ServicePrincipal : IPrincipal { // This answers the "What am I allowed to do" question
// In real life, this guy will contain all your user info
// and you can put what ever you like and retrieve it
// later via the HttpContext, on your application side.
// Some fun with casting will be required.
public static IPrincipal Default {
get {
return new ServicePrincipal {
Identity = new ServiceIdentity {
AuthenticationType = "Test",
IsAuthenticated = true,
Name = "Basic"
}
};
}
}
public IIdentity Identity { get; set; }
public bool IsInRole(string role) {
// If you want to use role based authorization
// e.g. [Authorize(Roles = "CoolPeople")]
// This is the place to do it and you can do
// anything from load info from a db or flat file
// or simple case statement...though that would
// be silly.
return true;
}
}
public class ServiceIdentity : IIdentity { // This answers the "Who Am I" Question
public string AuthenticationType { get; set; }
public bool IsAuthenticated { get; set; }
public string Name { get; set; }
}
public class ServiceModule : IHttpModule { // This is the module for IIS
public void Init(HttpApplication context) {
context.AuthenticateRequest += this.BasicAuthenticationRequest;
}
public void BasicAuthenticationRequest(object sender, EventArgs e) {
HttpApplication app = sender as HttpApplication;
if( !ServiceProvider.Authenticate(app.Context) ) {
// Total FAIL!
}
}
public void Dispose() {
// Clean up the mess, if needed.
}
}
public class ServiceProvider {
public static bool Authenticate( HttpContext context ) {
// For the example we are going to create a nothing user
// say he is awesome, pass him along through and be done.
// The heavy lifting of the auth process will go here
// in the real world.
HttpContext.Current.User = ServicePrincipal.Default;
return true;
}
}
Step 3a. [edit]
Here's the different libs you'll be "using"
using System.Security.Principal;
using System.Web;
Just wanted to throw those in. I hate it when folks leave them out. :)
Step 4.
Add the following to your web config. Please note I am including the surrounding structure, for example the "configuration" tag... It's just a road map, if you already have a "configuration" tag don't add the other or IIS gets upset with you.
<configuration>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="ServiceCredentialModule" type="{Namespace}.ServiceModule"/>
</modules>
</system.webServer>
<configuration>
Please note that the Namespace in {Namespace}.ServiceModule is the Namespace you put the classes from Step 3 into.
...and that's pretty much it.

Resources