Authentication and Custom Error pages - acs

I have a site that is using Azure ACS for authentication, backed by ADFS. When things are going well and people do things they are supposed to its great but that doesn't happen always so we have been implementing custom error pages.
The problem is, it doesn't seem to catch authentication errors, such as
ID3206: A SignInResponse message may only redirect within the current web application
Key not valid for use in specified state.
These errors still produce the ugly yellow error screen no matter what I say in my web.config. They are clearly ASP.NET errors and not IIS errors, so my question is how and where can I put custom error pages to display such errors in a 'pretty' way, as setting a page in web.config isn't working?
EDIT: To be clear, we have ACS set up to use an error page, have customErrors on with a different error page, neither or being used.

You have to have an action on a controller in your web app that accepts a POST from ACS and takes a parameter of type string. You must also configure your relying party application in ACS to point to that action for errors. Then in the action code you can do something like this:
namespace ASPNETSimpleMVC.Controllers
{
public class ErrorController : Controller
{
// Errors can be mapped to custom strings here.
static Dictionary<string, string> ErrorCodeMapping = new Dictionary<string, string>();
static ErrorController()
{
ErrorCodeMapping["ACS50019"] = "You chose to cancel log-in to the identity provider.";
ErrorCodeMapping["ACS60001"] = "No output claims were generated. You may be unauthorized to visit this site.";
}
//
// POST: /Error/
//
// If an error occurs during sign-in, ACS will post JSON-encoded errors to this endpoint.
// This function displays the error details, mapping specific error codes to custom strings.
[AcceptVerbs( HttpVerbs.Post )]
public ActionResult Index( string ErrorDetails )
{
// The error details contain an array of errors with unique error codes to indicate what went wrong.
// Additionally, the error details contain a suggested HTTP return code, trace ID, and timestamp, which may be useful for logging purposes.
ErrorDetails parsedErrorDetails = new JavaScriptSerializer().Deserialize<ErrorDetails>( ErrorDetails );
ViewData["ErrorMessage"] = String.Format( "An error occurred during sign-in to {0}. ", parsedErrorDetails.identityProvider );
// Loop through all ACS errors, looking for ones that are mapped to custom strings.
// When a mapped error is found, stop looking and append the custom string to the error message.
foreach ( ErrorDetails.Error error in parsedErrorDetails.errors )
{
if ( ErrorCodeMapping.ContainsKey( error.errorCode ) )
{
ViewData["ErrorMessage"] += ErrorCodeMapping[error.errorCode];
break;
}
}
return View( "Error" );
}
}
}
You may also find this article helpful.

Related

App maker override server side error message

I have a problem with the server-side error management on Google App Maker.
Here an exemple of my code
Server-side
function serverSideFn() {
// Consider the error to be throw.
if ( anError ) {
throw new Error("A specific error message");
}
}
Client-side
function clientSideFn() {
google.script.run
.withSuccessHandler(function(result) {
// Success code...
})
.withFailureHandler(function(error) {
console.log(error.message); // The message error here is not the same if I have or not the Admin role.
showErrorPopup(error.message);
})
.serverSideFn();
}
When I execute the "clientSideFn" function with default role Admin, I have the good message ("A specific error message"), but if I don't have the Admin role, I have a "Server Error" message instead of the expected.
I've tried to use the developer account option, and set Admin role to this account and execute the server side scripts, but the error is still present for users without Admin role.
I've also tried to throw a custom Exception, but the error is still changed on client side.
What I can change to got the expected message when the user don't have the Admin role ?
The relevant documentation to your question is located here https://developers.google.com/appmaker/scripting/api/server. The basics is that you use:
throw new app.ManagedError('Your custom message here');

Handle Unauthorized Request and Return Status Code 404

I am developing a standalone .Net Core API targeting framework .Net Core 2.2.The authentication scheme is JWTBearerTokens connecting to our ADFS Identify server.
When I call an API endpoing decorated with the [Authorize] attribute I am getting a 401 Unauthorized response, which is expected and default behaviour.
What I want to do next is instead of having that same call return a 401, I would like to return the status code to be 404. (I don't want to get into great details of why 404. Simply, I do not want to expose that the endpoint exists if a valid token is not included in request)
In previous .Net Framework WebAPI you could create your own attribute and override the HandleUnauthorizedRequest method and return the status code you want.
I have reviewed the documentation on policy-based authorization, but have not tried the sample or tried implementing it. The policy handler looks more to do with handling (return success or fail) if a policy is not fulfilled. I do not see anywhere where you can return a different status code on failure. So that only would make sense if I start checking against actual Policies.
Any insights?
Returning 404 instead of 401 is bad practice(as mentioned in the comments by #Chris Pratt) and must be avoided. Consider these cases,
You're leaving the project to someone else and they can't figure why 404 is returned
A 404 is returned when you call the homepage/Index page. Poor ideology.
Later on in the project, you decide to allow post requests without authentication. So on and so forth.
Anyways, as part of the community, I'll give you the answer...
Add this to your global.asax
void Application_EndRequest(object source, System.EventArgs args)
{
if (Response.StatusCode == 401)
{
Response.ClearContent();
Response.RedirectToRoute("ErrorH", (RouteTable.Routes["ErrorH"] as Route).Defaults);
}
}
And in routeConfig, create a route for your errorHandler :
routes.MapRoute(
"ErrorH",
"Error/{action}/{errMsg}",
new { controller = "CustomController", action = "Change401To404", errMsg = UrlParameter.Optional }
);
And in your custom controller :
public class CustomController : Controller //or Base
{
public ActionResult Change401To404(){
//Do whatever you want
}
}
PS: This is not the only way, there are many other ways to do it. But at least in this method, you can differentiate real 404 responses from 401 responses.

ASP.NET Web API removing HttpError from responses

I'm building RESTful service using Microsoft ASP.NET Web API.
My problem concerns HttpErrors that Web API throws back to user when something go wrong (e.g. 400 Bad Request or 404 Not Found).
The problem is, that I don't want to get serialized HttpError in response content, as it sometimes provides too much information, therefore it violates OWASP security rules, for example:
Request:
http://localhost/Service/api/something/555555555555555555555555555555555555555555555555555555555555555555555
As a response, I get 400 of course, but with following content information:
{
"$id": "1",
"Message": "The request is invalid.",
"MessageDetail": "The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'MyNamespaceAndMethodHere(Int32)' in 'Service.Controllers.MyController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter."
}
Something like this not only indicates that my WebService is based on ASP.NET WebAPI technology (which isn't that bad), but also it gives some information about my namespaces, method names, parameters, etc.
I tried to set IncludeErrorDetailPolicy in Global.asax
GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Never;
Yeah, that did somehow good, now the result doesn't contain MessageDetail section, but still, I don't want to get this HttpError at all.
I also built my custom DelegatingHandler, but it also affects 400s and 404s that I myself generate in controllers, which I don't want to happen.
My question is:
Is there any convinient way to get rid of serialized HttpError from response content? All I want user to get back for his bad requests is response code.
What about using a custom IHttpActionInvoker ?
Basically, you just have to send an empty HttpResponseMessage.
Here is a very basic example :
public class MyApiControllerActionInvoker : ApiControllerActionInvoker
{
public override Task<HttpResponseMessage> InvokeActionAsync(HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken)
{
var result = base.InvokeActionAsync(actionContext, cancellationToken);
if (result.Exception != null)
{
//Log critical error
Debug.WriteLine("unhandled Exception ");
return Task.Run<HttpResponseMessage>(() => new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
else if (result.Result.StatusCode!= HttpStatusCode.OK)
{
//Log critical error
Debug.WriteLine("invalid response status");
return Task.Run<HttpResponseMessage>(() => new HttpResponseMessage(result.Result.StatusCode));
}
return result;
}
}
In Global.asax
GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpActionInvoker), new MyApiControllerActionInvoker());
One other important thing you could do, not related to Web Api, is to remove excessive asp.net & IIS HTTP headers. Here is a good explanation.
I believe your approach of using the message handler is correct because regardless of the component in the Web API pipeline that sets the status code to 4xx, message handler can clear out response body. However, you do want to differentiate between the ones you explicitly set versus the ones set by the other components. Here is my suggestion and I admit it is a bit hacky. If you don't get any other better solution, give this a try.
In your ApiController classes, when you throw a HttpResponseException, set a flag in request properties, like so.
Request.Properties["myexception"] = true;
throw new HttpResponseException(...);
In the message handler, check for the property and do not clear the response body, if the property is set.
var response = await base.SendAsync(request, cancellationToken);
if((int)response.StatusCode > 399 && !request.Properties.Any(p => p.Key == "myException"))
response.Content = null;
return response;
You can package this a bit nicely by adding an extension method to HttpRequestMessage so that neither the ApiController nor the message handler knows anything about the hard-coded string "myException" that I use above.

Symfony2 debug log doesn't show username

I've got a problem with debug logs – if an error occured error log doesn't show which user causes error, but set username blank — security.DEBUG: Username "" was reloaded from user provider. [] []
I use custom entity provider written according cookbook tutorial. Other messages – for example security.INFO: User "......" has been authenticated successfully is displayed correctly.
Note: I post this problem also to the forum.
I had the same issue and it took me a lot of digging to figure this out.
The problem is that you don't serialize the username in the serialize function of the User object.
Many people use the following for their serialization functions:
public function serialize()
{
return serialize($this->id);
}
public function unserialize($data)
{
$this->id= unserialize($data);
}
This way only the id is known when loading the user from the session token (note this also breaks the ?_switch_user=_exit functionality).
To fix this you should use the following code:
public function serialize()
{
return serialize(array($this->id,$this->username));
}
public function unserialize($data)
{
list($this->id,$this->username) = unserialize($data);
}
This way the username AND id are available and the issue is fixed.
NOTE: The 'refreshUser' function of your custom user provider will NEVER be used as it will be overruled by the EntityUserProvider!

Extending Access Token Expiration not functioning

I am at the intermediate level in php and am new with facebook development. I have looked through the facebook documents and Stack Overflow previous comments.
All I basically wanted to do was let the user log in with their Facebook account and display their name.
My php page has a graph, and the page auto refreshes every 2 or 5 min.
I authenticate and get the facebook first_name to put on the page.
$graph = $facebook->api('/me');
echo $graph['first_name'] to get the first name of the user .. (for which I thought that no access token was required).
After about 90 min. I have been receiving the error:
fatal error: Uncaught OAuthException: An active access token must be used to query information about the current user......
and I have no value ( 0 ), in the $facebook->getUser(); parameter
I do know that off line access permission has been depreciated, (and I have have this enabled in my apps advanced settings)
I am trying to get an extended access token. In the FB docs. I see:
https://graph.facebook.com/oauth/access_token?
client_id=APP_ID&
client_secret=APP_SECRET&
grant_type=fb_exchange_token&
fb_exchange_token=EXISTING_ACCESS_TOKEN
I included my information in the link(an existing valid access token and all) and received a access token:
access_token=AAADbZBPuUyWwBAFubPaK9E6CnNsPfNYBjQ9OZC63ZBN2Ml9TCu9BYz89frzUF2EnLttuZAcG2fWZAHbWozrvop9bQjQclxVYle7igvoZCYUAg2KNQLMgNP&expires=4050
Yet this token expired in about 1 hour or so.(....expires=4050)
I assume I am using server side auth because I am using PHP?
I assume you need to enable "deprecate offline_access" in your Apps Advanced Settings page. As this worked for me:
//added code in base_facebook.php inside the facebook class
public function getExtendedAccessToken(){
try {
// need to circumvent json_decode by calling _oauthRequest
// directly, since response isn't JSON format.
$access_token_response =
$this->_oauthRequest(
$this->getUrl('graph', '/oauth/access_token'),
$params = array( 'client_id' => $this->getAppId(),
'client_secret' => $this->getAppSecret(),
'grant_type'=>'fb_exchange_token',
'fb_exchange_token'=>$this->getAccessToken(),
));
} catch (FacebookApiException $e) {
// most likely that user very recently revoked authorization.
// In any event, we don't have an access token, so say so.
return false;
}
if (empty($access_token_response)) {
return false;
}
$response_params = array();
parse_str($access_token_response, $response_params);
if (!isset($response_params['access_token'])) {
return false;
}
return $response_params['access_token'];
}
The token can still be invalid for several reasons, See How-To: Handle expired access tokens.
Hope it helps
There's a bug on this:
https://developers.facebook.com/bugs/241373692605971
But, another question on SO has a workaround (user uninstalls and re-installs):
fb_exchange_token for PHP only working once user removes app

Resources