aspnet identity; how to login using a legacy password? - asp.net-web-api

i've a site i'm updating to web api with aspnet identity 2.0.
It's a legacy site for which we need to allow the users to use their old passwords; at least during a reasonable migration period
following this article, i've derived a new UserManager from the base UserManager, and set up the PasswordHasher to hash with an old SHA1 algorithm.
My passwordHasher looks like this:
public class SQLPasswordHasher : PasswordHasher
{
public override string HashPassword(string password)
{
string cipherText = EncryptPassword(password);
return cipherText;
}
public override PasswordVerificationResult VerifyHashedPassword(string hashedPassword, string providedPassword)
{
string cipherText = EncryptPassword(providedPassword);
if (cipherText == hashedPassword)
{
return PasswordVerificationResult.SuccessRehashNeeded;
}
else
{
return PasswordVerificationResult.Failed;
}
}
private string EncryptPassword(string plainText)
{
return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(plainText, "sha1");
}
}
When i register users with this code, I can see the passwords are being hashed and persisted in the database correctly... for the password 'foobar', the hashed value is fixed and recognizable, since this algorithm did not use a salt.
However, I cannot log in as these users. If i set a breakpoint in the new hasher, it never gets it. Neither can i seem to hit a breakpoint anywhere in the account controller when trying to log in.
thanks in advance

I'm answering my own question, in the hopes that someone else may benefit.
The problem was, i couldn't find what in the web api service was being called when logging in. I finally realized that something called /Token was being set up as the url to be called in the app.js javascript.
Searching through the project server side sources and googling led me to this article, which pointed me to the ApplicationOAuthProvider.cs file, in the 'Providers' folder of the template application.
The specific line of interest is where the method GrantResourceOwnerCredentials instantiates it's own user manager, thus:
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
From there, all i had to do was add this line:
userManager.PasswordHasher = new SQLPasswordHasher();
and i could finally log in.

Related

What to use instead of Exceptions when writing validation code?

I am writing some validation code and am not sure how to pass validation messages back to the calling code.
Exceptions come to mind, but I think that Exceptions should not be used in user input validation. As #Blowdart puts it:
Exceptions are not
control flow mechanisms. Users often get passwords wrong, it's not an
exceptional case. Exceptions should be a truly rare thing,
UserHasDiedAtKeyboard type situations.
From: https://stackoverflow.com/a/77175/125938. I'm extending that sentiment to all "incorrect" user input that a user might enter.
So the question is what to use instead of Exceptions. For certain situations, I could just use an IsValid… method that returns a bool for validity, but what if I want to pass an error message back with it? Should I create a custom "ValidationError" object, with a Message property? What makes sense and causes Least Astonishment (preferably a tried and tested pattern)?
If I were to do this in a truly object-oriented way, I'd adhere to the separation of concerns principle and compose a chain of classes that each deal with a separate step on the input - validation - output journey.
Let's say we are parsing a date from string as entered by the user.
My first class would encapsulate the raw value and attempt to parse the date (pseudo-code):
class TextualDate {
public TextualDate(string value) {
// just initialize with the provided value
}
public Option<Date> AsDate() {
// try parsing and either return the date or not
// the Option<Date> type is here to suggest that the conversion might not succeed
}
}
Next I'd have a validation class that instantiates the TextualDate class, invokes its AsDate() method and returns the validation result:
class ValidatedDate {
public ValidatedDate(TextualDate value) {
// initialize with the provided value
_textualDate = value;
}
private TextualDate _textualDate;
public ValidationResult Validated {
var maybeDate = _textualDate.AsDate();
// see whether we have a date or not
return new ValidationResult(...);
}
}
In our ValidationResult class, we might find some status property (OK, Failed), any error message either provided directly or as a key to then look-up in a message catalog etc.
This way, we can isolate concerns and only deal with the error messages on the UI layer while being able to use and reuse the validation logic independently.
I was faced with a similar dilemma in the past - I had to write a couple of services that takes data from a 3rd party, manipulating it in various ways, and send that data to other services for further processing.
All of these services might have failed because of wrong or incomplete data, but it was nor unexpected neither exceptional - and I refused to use exceptions for these cases.
I've done an extensive research, reading anything I could get my hands on in this subject in two days, and finally decided the following:
A method might need to return data and might not (sub in Visual Basic, void in Java/C#) - but in both cases, I wanted an indication for success/fail and a potential error message.
If your language of choice supports tuples, you could return a tuple from your methods:
public (bool Success, string ErrorMessage) DoSomething()
{
// implementation here
}
or
public (bool Success, someType Value, string ErrorMessage) DoSomething()
{
// implementation here
}
If not, you can do what I did (That was c#5 - so no value tuples) and create a result class:
public class Result
{
public static Result Success()
{
return new Result(true, null);
}
public static Result Fail(string errorMessage)
{
return new Result(false, errorMessage);
}
protected Result(bool success, string errorMessage)
{
Success = success;
ErrorMessage = errorMessage;
}
public bool Success {get; private set;}
public string ErrorMessage {get; private set;}
}
public class Result<T>
{
public static Result<T> Success(T value)
{
return new Result(true, null, value);
}
public new static Result<T> Fail(string errorMessage)
{
return new Result(false, errorMessage, default(T));
}
private Result<T>(bool success, string errorMessage, T value)
: base(success, errorMessage)
{
Value = value;
}
public T Value {get; private set;}
}
And use it like this:
public Result CouldBeVoid()
{
bool IsOk;
// implementation
return IsOk ?
Result.Success() :
Result.Fail("Something went wrong") ;
}
public Result<int> CouldBeInt()
{
bool IsOk;
// implementation
return IsOk ?
Result.Success(intValue) :
Result.Fail("Something went wrong") ;
}
var result = CouldBeVoid();
if(!result)
// do something with error message
var result = CouldBeInt()
if(result)
// do something with int value
else
// do something with error message
Users often get passwords wrong, it's not an exceptional case.
Yes and no. Whether to throw an exception or not depends on the question you're asking. And in the course of logging a user in, there are typically quite a number of questions being asked before you come to the conclusion whether the user can be logged in or not. The more you break down your code into specialised parts, the more it may make sense to raise exceptions in some of those parts.
Say you specify your login procedure the following way in an HTTP context:
Get the username* and password* from the request.
Fetch the user record* by its username from the database*.
Check whether the record's password* equals* the entered password.
If yes, start a session.
If any of the above steps do not successfully complete, output an appropriate error message.
Any of the items marked with an asterisk above may fail:
The request may not contain a username or password.
There may not be a user record for this username, or the database may be down.
For whatever reason, the record may not have a password and/or be corrupted. The stored password may, for whatever reason, use an unsupported hashing algorithm and hence can't be compared.
It should be rather obvious that in this process there are any number of cases that would be ideal to be implemented as an exception. The actual function which tests the password should probably not throw an exception in case the password is merely false; that should be a boolean return value. But it may still throw an exception for any other number of reasons. If you use exceptions properly, you'll end up with code that looks something like this (pseudo-pseudo code):
try {
username = request.get('username')
password = request.get('password')
user = db.get(username=username)
if (user.password.matches(password)) {
session.start()
} else {
print 'Nope, try again'
}
} catch (RequestDoesNotHaveThisDataException) {
logger.info('Invalid request')
response.status(400)
} catch (UserRecordNotFoundException) {
print 'Nope, try again'
} catch (UnsupportedHashingAlgorithmException, PasswordIsNullException) {
logger.error('Invalid password hash for user ' + user.id)
response.status(500)
print 'Sorry, please contact our support staff'
} catch (DatabaseDownException e) {
// mostly for illustration purposes,
// this exception should probably not even be caught here
logger.exception('SEND HALP!')
throw e
}
So, yes, this is a very simple process, but literally every step along the way has one or more exceptional cases. You ask the question "what is the username the user sent in the request?", and if there's no answer to this question because the user didn't sent any username, you have an exceptional case. Exceptions simplify control flow here a lot as opposed to trying to cover each of these cases with an if..else.
It is NOT an exception if the username is not valid or the password is not correct.
(From the answer you quote from.)
As you can see, we're testing whether the username is "valid" or not by trying to fetch its record from the database. If we have a function whose purpose is to fetch records of users from the database, and there is no such record, then an exception is an entirely valid response. If we defined that function to test whether such a record exists and null or false is a valid return value… fine. But in this case we didn't write it that way, and frankly, that results in simpler control flow I find.
Now, only the password validation itself does not use an exception, since the question asked there is "does this password match that password?", to which the answer can clearly be yes or no. Again, only if something exceptional like an unsupported hashing algorithm turns up can there be no answer to this question and an exception is entirely warranted.
Having said all this, you may notice that most of these cases, except the really fatal one with the database, does not outwardly result in an exception. The component here is expecting and handling certain cases that its sub-components regard as exceptional. This code here is asking the questions, and is prepared to handle Mu as an answer for some of them. Which is to say, a general rule that says "exceptions shouldn't be used in process X, Y or Z because it's not exceptional enough" is too dogmatic. It depends on the purpose of each individual piece of code whether an exception is warranted or not.
Having said all this, what you're asking about is some sort of form validation. The above code shows a case where two pieces of data may each be invalid, and it's using exceptions to in the end still result in a "yes" or "no" response. You can of course encapsulate that in an object like this:
val = new LoginFormValidator()
val.setDataFromRequest(request)
val.validate()
if (val.isValid) {
print 'Hurray'
} else {
print 'You have errors:'
for (error in val.errors) {
print error.fieldName + ': ' + error.reason
}
}
Whether this validator uses exceptions internally for any of this you do not need to care, but in the end it saves all of them as a "yes" or "no" result to its internal properties, from where you can take them either as an aggregate (val.isValid) or individually (for (error in val.errors)).

Persistent Storage using Application.Current.Properties not working

I'm trying to achieve a persistent storage in Xamarin.Forms. After researching in Xamarin.Forms, I decided to use Application.Current.Properties property.
It looks like it is working just only if the app still remains alive. If I close the app and start it again the Application.Current.Properties is empty.
Does anyone know if I'm doing something wrong? Can I achieve this feature in another way?
As usual, thanks guys.
I have had a ton of problems with Application.Current.Properties on Android. I highly suggest using Xamarin Settings plugin instead which I have never had any issues with. It is persistent even when the app is closed.
That being said Application.Current.Properties is supposed to work even when you close the app. Not sure why it wouldn't but it does not surprise me either.
*Edit: To use once it is installed, basically CrossSettings.Current is the plugin class that will do the work but the example just creates a separate property to access it. So create a new file, lets call it SettingsImplementation:
public static class SettingsImplementation {
#region Instance
private static Lazy<ISettings> _appSettings;
public static ISettings AppSettings {
get {
if(_appSettings == null) {
_appSettings = new Lazy<ISettings>(() => CrossSettings.Current, LazyThreadSafetyMode.PublicationOnly);
}
return _appSettings.Value;
}
set {
_appSettings = new Lazy<ISettings>(() => value, LazyThreadSafetyMode.PublicationOnly);
}
}
#endregion
private const string UserNameKey = "username_key"; //Key used to get your property
private static readonly string UserNameDefault = string.Empty; //Default value for your property if the key-value pair has not been created yet
public static string UserName {
get { return AppSettings.GetValueOrDefault<string>(UserNameKey, UserNameDefault); }
set { AppSettings.AddOrUpdateValue<string>(UserNameKey, value); }
}
}
Then to use that you would do this anywhere in your app:
SettingsImplementation.UserName = "something";
OR
string username = SettingsImplementation.UserName;
My own problem regarding this issue was due to me not explicitly saving the properties with the following line of code:
Application.Current.SavePropertiesAsync();
you can use Xamarin essentials "Preferences" instead:
Preferences.Set("Key", "Value");
Preferences.Get("Key", "Default");
I ran into the same issue.
The problem:
I was trying to throw complex objects into the Application Properties.
It turns out that the Properties can only take primitive data typs.
This Blog was very helpfull.
https://codemilltech.com/persist-whatever-you-want-with-xamarin-forms/

Unable to create new claim identity

I am currently trying to expose a field from an authenticated user, but I'm having a bit of difficulty trying to add a new claim to the authenticated user.
In MVC5 I would do something similar to the following:
public class ApplicationUser : IdentityUser
{
public string FullName { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
userIdentity.AddClaim(new Claim("FullName", FullName));
return userIdentity;
}
}
When I attempt to do this in MVC6 however I run into problems with objects and methods missing. CreateIdentityAsync() and DefaultAuthenticationTypes both appear to be missing or so says visual studio and when I dig into the Identity source I can see that CreateIdentityAsync is no longer there, however I can't seem to find anything about DefaultAuthenticationTypes.
Right now at this point I think this is a nice to have, but its been driving me nuts for the past few days and would be nice to understand whats wrong or how this has changed.

Where to filter Identity 2.0 claim ticket in a WebAPI app?

ASP.NET apps using OWIN permit multiple Identity sources (Facebook, Google, etc.). Most of the provider-specifc information those sources provide is irrelevant to my app, potentially even large, and I don't want it in my cookies all session. My app is primarily WebAPI, but I suspect the question applies equally to MVC and WebForms.
For now, all I need is an integer account ID. Where/when should I reconstruct the identity, after external authentication?
For example, here is one way I could filter claims:
public ReplaceExistingClaims(ClaimsIdentity identity) {
{
Claim customClaim = GetCustomClaimFromDbForIdentity(identity);
foreach (Claim claim in ClaimsIdentity.Claims) ClaimsIdentity.RemoveClaim(claim);
ClaimsIdentity.AddClaim(customClaim);
}
And following are two different places I could inject those claims changes:
var facebookAuthenticationOptions = new FacebookAuthenticationOptions
{
Provider = new FacebookAuthenticationProvider
{
OnAuthenticated = context =>
{
ReplaceExistingClaims(context.Identity);
return Task.FromResult(0);
}
}
};
Above, I know I can hook an individual provider from Startup IF it provides an Authenticated event. I have two conceptual problems with this. One: it requires me to write and wire up my code separately for each provider I plug in. Two: there is no requirement for providers to provide this event. Both of these make me feel like there must be a different intended insertion point for my code.
public ActionResult ExternalLoginCallback(string returnUrl)
{
ReplaceExistingClaims((ClaimsIdentity)User.Identity);
new RedirectResult(returnUrl);
}
Above, I know I can put code in ExternalLoginCallback. But this happens too late for two reasons. One: The user has already been issued a ticket I consider invalid, but the default [Authorized] considers valid because it's signed by me, and now they are making requests to my site with it. There could even be race conditions here. Two: There is no guarantee the browser will visit this redirect, and I'd prefer from a design perspective if it didn't have to, e.g. to simplify my WebAPI client code.
To the best of my knowledge, the best solution will meet these requirements:
same code applies to all providers
client receives my custom ticket from my server (e.g. without image claims)
client never receives another ticket format from my server
the authentication process requires the minimum possible HTTP round-trips
token-refresh and other core identity features are still available
once a user is [Authorize]d, no further account transformation is necessary
database/repository access is feasible during ticket generation
Some pages I'm researching, for my own notes:
How do I access Microsoft.Owin.Security.xyz OnAuthenticated context AddClaims values?
https://katanaproject.codeplex.com/SourceControl/latest#src/Microsoft.Owin.Security.Facebook/FacebookAuthenticationHandler.cs
https://katanaproject.codeplex.com/workitem/82
https://www.simple-talk.com/dotnet/.net-framework/creating-custom-oauth-middleware-for-mvc-5/
You have to implement DelegationHandler and put all your authentication routines in it.
Register at Application start (DI usage is enabled):
private static void RegisterHandlers(HttpConfiguration config)
{
var authHandler = new MyFacebookAuthHandler();
config.MessageHandlers.Add(authHandler);
}
And this is an example of implementation:
public class MyFacebookAuthHandler : DelegationHandler
{
public override sealed Task<HttpResponseMessage> OnSendAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
try
{
// Process credentials
// Probably you have to save some auth information to HttpContext.Current
// Or throw NotAuthorizedException
}
catch(NotAuthorizedException ex)
{
return request.CreateErrorResponse(HttpStatusCode.Unauthorized, ex).ToCompletedTask();
}
catch (Exception ex)
{
return request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex).ToCompletedTask();
}
return base.OnSendAsync(request, cancellationToken);
}
}
The ClaimsAuthenticationManager class is specifically for this.
https://msdn.microsoft.com/en-us/library/system.security.claims.claimsauthenticationmanager(v=vs.110).aspx
Code sample from that reference:
class SimpleClaimsAuthenticatonManager : ClaimsAuthenticationManager
{
public override ClaimsPrincipal Authenticate(string resourceName, ClaimsPrincipal incomingPrincipal)
{
if (incomingPrincipal != null && incomingPrincipal.Identity.IsAuthenticated == true)
{
((ClaimsIdentity)incomingPrincipal.Identity).AddClaim(new Claim(ClaimTypes.Role, "User"));
}
return incomingPrincipal;
}
}

Custom ASP.NET SqlMembershipProvider - handling connection string

I am creating a custom SqlMembershipProvider class to add some enhanced functionality to the base class. I'm getting caught up on handling the connection string, though. How can I read the Connection String Name from the configuration and make that available to the rest of the methods?
Right now I have:
public override void Initialize(string name, NameValueCollection config)
{
base.Initialize(name, config);
_ConnectionStringName = config["connectionStringName"];
}
But in other methods, the _ConnectionStringName variable is null:
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[_ConnectionStringName].ConnectionString)
What is the proper way to store the Connection String Name so it is available globally in my custom membership provider?
Thanks!
ProviderBase will throw a ConfigurationException if there are any entries left in the config collection by the time it get's it so each provider removes it's configuration entries before calling base.Initialize.
The issue, as you have found as a result of this answer is that you must get your values before calling base.Initialize.
Sorry, I missed that at first glance.
The rest of this post is historical and while technically correct misses the salient issue here as enumerated above.
First - try WebConfigurationManager.ConnectionStrings.
WebConfigurationManager handles applying the hierarchy of web.config all the way from your windows\microsoft.net\framework\2.0xxxx\web.config all the way up to your app.
This behaviour is not present in ConfigurationManager, which typically deals with machine.config to app.config.
If this does not solve your problem you must be overwriting the value elsewhere in your code, if indeed _ConnectionStringName is being properly assigned in Initialize.
First, set a breakpoint and ensure that _ConnectionStringName is being set as expected.
Then locate all references to the field and ensure that you do not have a bug.
This is assuming, of course, that _ConnectionStringName is a private field. If it is not, make it so and look for your compile error.
Not sure if this helps, but I was having a similar issue in needing to override the connectionstring in a sub-class of SqlMembershipProvider.
This idea is not my own - I found it in the comments section of this forum posting:
http://forums.asp.net/p/997608/2209437.aspx
public override void Initialize(string name, NameValueCollection config)
{
base.Initialize(name, config);<br>
string connectionString = //...what you want your connection string to be,
//so config["connectionStringName"]...
// Set private property of Membership provider.
System.Reflection.FieldInfo connectionStringField =
GetType().BaseType.GetField("_sqlConnectionString",
System.Reflection.BindingFlags.Instance
| System.Reflection.BindingFlags.NonPublic);
connectionStringField.SetValue(this, connectionString);
}
My apologies - I've never posted here before, so the formatting may be sub-par!
This is probably 6 months too late to help, but I was able to get the connection string this way:
using System.Web.Configuration;
Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
MembershipSection section = config.SectionGroups["system.web"].Sections["membership"] as MembershipSection;
string defaultProvider = section.DefaultProvider;
string connstringName = section.Providers[defaultProvider].ElementInformation.Properties["connectionStringName"].Value.ToString();
string val = config.ConnectionStrings.ConnectionStrings[connstringName].ConnectionString;
This makes the assumption that the default provider has a connection string property - but if you're subclassing SqlMembershipProvider then should always have one, somewhere up the web.config chain (it's defined in the machine.config I believe).
All of this, to add one method to change the username.

Resources