Logging username with Elmah for WCF Webservices - asp.net

We are using the approach described here to log our webservice errors with Elmah. And this actually works, but sadly the username beeing logged is empty.
We did some debugging and found, that when logging the error in the ErrorHandler the HttpContext.Current.User has the correct User set.
We also tried:
HttpContext context = HttpContext.Current;
ErrorLog.GetDefault(context).Log(new Error(pError, context));
and
ErrorLog.GetDefault(null).Log(new Error(pError));
Without success.
Any ideas on how we can make Elmah log the username?
On a sidenote, when logging the error directly within the Webservice, the username is logged as expected. But taking this approach is not very DRY.

Elmah take the user from Thread.CurrentPrincipal.Identity.Name and not from HttpContext.Current.User.
Since there ins't a convenient way to add custom data to Elmah, I would suggest recompiling the code, and calling HttpContext.Current.User instead.

This is a question that I see over and over again. While re-compiling the code is a possibility, I would rather suggest using features built into ELMAH already, as explained in my blog post Enrich ELMAH errors using error filtering hook.
In your case, setting the User property on all errors, can be achieved by adding the ErrorLog_Filtering-method:
void ErrorLog_Filtering(object sender, ExceptionFilterEventArgs args)
{
var httpContext = args.Context as HttpContext;
if (httpContext != null)
{
var error = new Error(args.Exception, httpContext);
error.User = httpContext.User.Identity.Name;
ErrorLog.GetDefault(httpContext).Log(error);
args.Dismiss();
}
}

As an alternative to recompile Elmah, we can use a global method, which populates Thread.CurrentPrincipal.Identity.Name before calling elmah.
public static void LogError(Exception exception, string username)
{
Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(username), new string[] {});
Elmah.ErrorSignal.FromCurrentContext().Raise(exception);
}

Related

HttpContext does not contain a definition for SignOutAsync

I'm trying to write a custom authentication manager that will handle user login and logout and many other stuff in my ASP .Net Core 2.x app, but i'm stuck in the first place.
i have tried the way suggested in this Microsoft Article but when i try to implement Sign-in, it shows the HttpContext does not contain a definition for SignOutAsync error. i have all the references as suggested in the article :
public async void SignIn(HttpContext httpContext, UserDbModel user, bool isPersistent = false)
{
ClaimsIdentity identity = new ClaimsIdentity(this.GetUserClaims(user), CookieAuthenticationDefaults.AuthenticationScheme);
ClaimsPrincipal principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(IdentityConstants.ApplicationScheme);
}
below code works but it is obsolete :
await HttpContext.Authentication.SignOutAsync(...)
references in class :
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Authentication;
What's missing here ? maybe these extension-methods are removed in new versions, if so ... how do i implement the authentication in it's correct way ?
HttpContext should be a reference to a field in your Controller and that you are not referring to a/the type HttpContext. If that is not the case then that is the cause of your problem, change your code to use the field/variable and not the type.
So if the field name is httpContext then use that as calling an extension methods is done by referring to the method on an instance and not a type as the instance is also passed in as the first parameter of the extension method.
await httpContext.SignInAsync(IdentityConstants.ApplicationScheme);
AuthenticationHttpContextExtensions.SignOutAsync(HttpContext, "Cookies");
AuthenticationHttpContextExtensions
.SignOutAsync(HttpContext, CookieAuthenticationDefaults.AuthenticationScheme);
try this in a controller
insted of
await HttpContext.SignInAsync(IdentityConstants.ApplicationScheme);
should use
await httpContext.SignInAsync(IdentityConstants.ApplicationScheme,ClaimsPrincipal.Current);
or could use
await Microsoft.AspNetCore.Authentication.AuthenticationHttpContextExtensions.SignInAsync(IdentityConstants.ApplicationScheme,ClaimsPrincipal.Current);

Unable to access TempData inside my HandleUnauthorizedRequest

I have created my own customization for the AuthorizeAttribute inside my asp.net mvc web application, and to be able to return the user to the current URL after login , i am trying to save the current URL inside a TempData and then redirect to the login action method ,as follow-
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (!_authorize && !filterContext.HttpContext.Request.IsAjaxRequest())
{
var viewResult = new RedirectResult("/Account/Login");
TempData["returnUrl"] = filterContext.HttpContext.Request.Url.PathAndQuery;
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
filterContext.Result = viewResult;
}
but seesm that i can not reference TempData in this case, because the above code will raise the following error:-
The name 'TempData' does not exist in the current context
Can anyone advice please?
Thanks
Try using controller base,
filterContext.Controller.TempData["returnUrl"] = filterContext.HttpContext.Request.Url.PathAndQuery;
Also TempData may behave unexpectedly in Authorize attribute as it lives only on one request cycle. If so use Session instead.

How to Customize ASP.NET Web API AuthorizeAttribute for Unusual Requirements

I am inheriting from System.Web.Http.AuthorizeAttribute to create a custom authorization/authentication routine to meet some unusual requirements for a web application developed using ASP.NET MVC 4. This adds security to the Web API used for Ajax calls from the web client. The requirements are:
The user must logon each time they perform a transaction to verify
someone else has not walked up to the workstation after someone has
logged on and walked away.
Roles cannot be assigned to the web service methods at program time.
They must be assigned at run time so that an administrator can
configure this. This information is stored in the system database.
The web client is a single page application (SPA) so the typical forms authentication does not work so well, but I am trying reuse as much of the ASP.NET security framework as I can to meet the requirements. The customized AuthorizeAttribute works great for requirement 2 on determining what roles are associated with a web service method. I accept three parameters, application name, resource name and operation to determine which roles are associated with a method.
public class DoThisController : ApiController
{
[Authorize(Application = "MyApp", Resource = "DoThis", Operation = "read")]
public string GetData()
{
return "We did this.";
}
}
I override the OnAuthorization method to get the roles and authenticate the user. Since the user has to be authenticated for each transaction I reduce the back and forth chatter by performing authentication and authorization in the same step. I get the users credentials from the web client by using basic authentication which passes the encrypted credentials in the HTTP header. So my OnAuthorization method looks like this:
public override void OnAuthorization(HttpActionContext actionContext)
{
string username;
string password;
if (GetUserNameAndPassword(actionContext, out username, out password))
{
if (Membership.ValidateUser(username, password))
{
FormsAuthentication.SetAuthCookie(username, false);
base.Roles = GetResourceOperationRoles();
}
else
{
FormsAuthentication.SignOut();
base.Roles = "";
}
}
else
{
FormsAuthentication.SignOut();
base.Roles = "";
}
base.OnAuthorization(actionContext);
}
GetUserNameAndPassword retrieves the credentials from the HTTP header. I then use the Membership.ValidateUser to validate the credentials. I have a custom membership provider and role provider plugged in to hit a custom database. If the user is authenticated I then retrieve the roles for the resource and operation. From there I use the base OnAuthorization to complete the authorization process. Here is where it breaks down.
If the user is authenticated I use the standard forms authentication methods to log the user in (FormsAuthentication.SetAuthCookie) and if they fail I log them out (FormsAuthentication.SignOut). But the problem seems to be that base OnAuthorization class does not have access to Principal that is updated so that IsAuthenticated is set to the correct value. It is always one step behind. And my guess is that it is using some cached value that does not get updated until there is a round trip to the web client.
So all of this leads up to my specific question which is, is there another way to set IsAuthenticated to the correct value for the current Principal without using cookies? It seems to me that cookies do not really apply in this specific scenario where I have to authenticate every time. The reason I know IsAuthenticated is not set to the correct value is I also override the HandleUnauthorizedRequest method to this:
protected override void HandleUnauthorizedRequest(HttpActionContext filterContext)
{
if (((System.Web.HttpContext.Current.User).Identity).IsAuthenticated)
{
filterContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden);
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
This allows me to return a status code of Forbidden to the web client if the failure was because of authorization instead of authentication and it can respond accordingly.
So what is the proper way to set IsAuthenticated for the current Principle in this scenario?
The best solution for my scenario appears to be bypass the base OnAuthorization completely. Since I have to authenticate each time cookies and caching the principle are not of much use. So here is the solution I came up with:
public override void OnAuthorization(HttpActionContext actionContext)
{
string username;
string password;
if (GetUserNameAndPassword(actionContext, out username, out password))
{
if (Membership.ValidateUser(username, password))
{
if (!isUserAuthorized(username))
actionContext.Response =
new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden);
}
else
{
actionContext.Response =
new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
}
}
else
{
actionContext.Response =
new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest);
}
}
I developed my own method for validating the roles called isUserAuthorized and I am not using the base OnAuthorization any more since it checks the current Principle to see if it isAuthenticated. IsAuthenticated only allows gets so I am not sure how else to set it, and I do not seem to need the current Principle. Tested this out and it works fine.
Still interested if anyone has a better solution or can see any issues with this this one.
To add to the already accepted answer: Checking current sourcecode (aspnetwebstack.codeplex.com) for System.Web.Http.AuthorizeAttribute, it looks like the documentation is out of date. Base OnAuthorization() just calls/checks private static SkipAuthorization() (which just checks if AllowAnonymousAttribute is used in context to bypass the rest of the authentication check). Then, if not skipped, OnAuthorization() calls public IsAuthorized() and if that call fails, it then calls protected virtual HandleUnauthorizedRequest(). And that's all it does...
public override void OnAuthorization(HttpActionContext actionContext)
{
if (actionContext == null)
{
throw Error.ArgumentNull("actionContext");
}
if (SkipAuthorization(actionContext))
{
return;
}
if (!IsAuthorized(actionContext))
{
HandleUnauthorizedRequest(actionContext);
}
}
Looking inside IsAuthorized(), that's where Principle is checked against roles and users. So, overriding IsAuthorized() with what you have above instead of OnAuthorization() would be the way to go. Then again, you'd still have to probably override either OnAuthorization() or HandleUnauthorizedRequest() anyway to decide when to return a 401 vs a 403 response.
To add to the absolutely correct answer by Kevin, I'd like to say that I may slightly modify it to leverage the existing .NET framework path for the response object to ensure downstream code in the framework (or other consumers) is not adversely affected by some weird idiosyncrasy that can't be predicted.
Specifically this means using this code:
actionContext.Response = actionContext.ControllerContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, REQUEST_NOT_AUTHORIZED);
rather than:
actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
Where REQUEST_NOT_AUTHORIZED is:
private const string REQUEST_NOT_AUTHORIZED = "Authorization has been denied for this request.";
I pulled that string from the SRResources.RequestNotAuthorized definition in the .NET framework.
Great answer Kevin! I implemented mine the very same way because executing OnAuthorization in the base class made no sense because I was verifying an HTTP Header that was custom to our application and didn't actually want to check the Principal at all because there wasn't one.

asp.net custom role provider nhibernate error

HI,
I am implementing a custom role provider in my nhibernate application
I have a repository that I call whenever I want to access the nhibernate session.
So when my role provider initializes itself
public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config) {
base.Initialize(name, config);
Repository = new Repository();
}
Then I override
public override string[] GetRolesForUser(string username) {
var users = Repository.QueryAll<Users>();
//I then filter and so on
}
But when this function is called I always get an error that the NHibernate session is closed.
I debugged the nhibernate source code and it turns out that the session here has a different guid that the session in my controllers(I am using ASP.NET MVC also).
And this particular session is closed by the time I get here.
I don't know who closes it. I know it is started when the application starts and only then.
Does anyone have any idea what I am doing wrong?
I want to still use Nhibernate in this provider but not get the error any more.
Thank you
I had what appears to be the exact same problem. Don't forget that Role and Membership providers are only instantiated once and exist for the lifetime of the application. If you're using a Session per Web request pattern, the ISession will be closed after the first request and then any reference to an ISession internal to the provider will likely be null for subsequent requests.
You can get around this by injecting a reference to the ISessionFactory and calling GetCurrentSession, instead of directly holding a reference to an ISession.
This is how I evetually fixed it.
in my repository class I had this:
public Repository()
{
this.Session = SessionManager.GetCurrentSession();
}
I deleted the constructor entirely
I put in this instead:
private ISession _session;
protected ISession Session
{
get
{
if (_session == null)
{
_session = SessionManager.GetCurrentSession();
}
return _session;
}
}

HttpContext.Current NullReferenceException in Static Method

I have a static class with several static methods. In these methods, I'm trying to access the current thread's context using HttpContext.Current. For example:
var userName = HttpContext.Current.User.Identity.Name;
However, when I do that, I receive a NullReferenceException, the infamous "Object reference not set to an instance of an object."
Any ideas?
It isn't clear from the original post that the HttpContext is actually what's missing. The HttpContext.User property can also be null at certain stages of the lifecycle, which would give you the exact same exception. All other issues aside, you need to step through the source and see which part of the expression is actually null.
When you write code that references static methods/properties like HttpContext.Current, you have to write them knowing that your code isn't guaranteed to be run when the methods/properties are actually available. Normally you have something like this:
static string GetCurrentUserName()
{
HttpContext context = HttpContext.Current;
if (context == null)
return null;
IPrincipal user = context.User;
if (user == null)
return null;
return user.Identity.Name;
}
Although I suspect that this wouldn't really solve your problem here, it would just get rid of the exception. The issue is more likely that you're calling this method at a time or place when the context is simply not available, such as on a background thread, static constructor or field initializer, or in the Application_BeginRequest method, or some similar place.
I might start by changing the static methods to instance methods of a class that depends on an HttpContext instance (i.e. taken in the constructor). It's easy to fool yourself into thinking that methods like GetCurrentUserName are simple "utility" methods, but they're really not, and it is generally invalid to be invoking a method that references HttpContext.Current through the static property from any place where you don't already have an instance reference to the same HttpContext (i.e. from the Page class). Odds are, if you start rewriting your classes like this:
public class UserResolver
{
private HttpContext context;
public UserResolver(HttpContext context)
{
if (context == null)
throw new ArgumentNullException("context");
this.context = context;
}
public string GetUserName()
{
return (context.User != null) ? context.User.Identity.Name : null;
}
}
...then you will likely find out very quickly where the chain is being broken, which will be the point at which you need to reference HttpContext.Current because you can't get it from anywhere else.
In this specific case, obviously, you can solve the problem just by taking the stack trace of the NullReferenceException to find out where/when the chain begins, so you don't have to make the changes I've described above - I'm simply recommending a general approach that will help reduce these sorts of "missing singleton" errors in the future.
I've run into this a few times, especially with static methods in another library and not my main project. I've resorted to passing the HttpContext to the static method as a param when nothing else seems to work.
Where exactly is the null exception being thrown? Have you debug and see what is null? Is the HttpContext.Current is null or the User?

Resources