How to fix "An unhandled exception occurred while processing the request."? - c#

As we're developing a webapp which we want to authorize against a Shibboleth IDP we're getting the following error, after what seems like a successfull login at the IDPP:
An unhandled exception occurred while processing the request.
UnexpectedInResponseToException: Received message contains unexpected InResponseTo "idd95739d3bc9e44efa1154b3e62a2e121". No cookie preserving state from the request was found so the message was not expected to have an InResponseTo attribute. This error typically occurs if the cookie set when doing SP-initiated sign on have been lost.
Sustainsys.Saml2.Saml2P.Saml2Response.ReadAndValidateInResponseTo(XmlElement xml, Saml2Id expectedInResponseTo, IOptions options) in Saml2Response.cs, line 153
Our startup.cs looks like this:
services.AddAuthentication()
.AddSaml2(options =>
{
options.SPOptions.EntityId = new EntityId("https://adress.to.the.SP.net");
options.SPOptions.Compatibility.UnpackEntitiesDescriptorInIdentityProviderMetadata = true;
options.SPOptions.ReturnUrl = new Uri(#"https://adress.to.a.site.of.our.site.net.net/Saml/Session");
options.SPOptions.ServiceCertificates.Add(new X509Certificate2(#"wwwroot/mycert.pfx")); // "Sustainsys.Saml2.Tests.pfx"
options.IdentityProviders.Add(
new IdentityProvider(
new EntityId("adress.to.the.IDP.net"), options.SPOptions)
{
LoadMetadata = true,
MetadataLocation = ("https://adress.to.the.MetadataLocation.xml")
});
IdentityProvider idp;
var x = options.IdentityProviders.TryGetValue(new EntityId(Prov.Idp), out idp);
X509Certificate2 ssoTest = new X509Certificate2(#"wwwroot/sso-test.pem");
idp.SigningKeys.AddConfiguredKey(ssoTest);
});^^^
This is what I see when I check the browser's dev-tools cokkies option:
Gett 200 BIGipServer~idm~ipv4-shib-test: ! experimentation_subject_id: JSESSIONID: shib_idp_session:
Post 500 .AspNetCore.Antiforgery.w5W7x28NAIs: ARRAffinity: Saml2.t8NpWx0u6S6zBFc97nzgN_IL:
Gett 200 .AspNetCore.Antiforgery.w5W7x28NAIs: ARRAffinity: Saml2.5AYF3RXdiYbN3iolD0HCRu9P:

Related

Smart home report state SYNC new device | Requested entity was not found. [404]

I've implemented the HomeGraph API with the help of the package Google.Apis.HomeGraphService.v1 (1.50.0.2260)
It seems to work fine as well, the ReportStateAndNotification function works fine on the query, execute, and some sync requests.
But when I add a new device to my system through our app and a SYNC request is sent to Google and comes in our backend, the HomeGraph API will return an exception when sending this sync request..
-> The sync request does not throw an exception when I modify a device name in our app. It only occurs when new devices are added.
I've searched through google and multiple StackOverflow posts.. But I'm probably missing something. Most posts say check the API key etc but then the ReportStateAndNotification function should always fail, not only when the sync request comes from Google to our backend.
Could anyone point me in the right direction?
Function that is used for sync requests:
public static void Send(Dictionary<string, object> deviceStateList, string requestId, string googleCustomerId)
{
string deviceIdList = String.Format("({0})", string.Join(", ", deviceStateList.Keys));
try
{
var jsonFilePath = _appSettingsRetriever.PrivateGoogleAuthenticationFile;
string scope = "https://www.googleapis.com/auth/homegraph";
using (var stream = new FileStream(jsonFilePath, FileMode.Open, FileAccess.Read))
{
GoogleCredential credentials = GoogleCredential.FromStream(stream);
if (credentials.IsCreateScopedRequired)
credentials = credentials.CreateScoped(scope);
HomeGraphServiceService service = new HomeGraphServiceService(new BaseClientService.Initializer()
{
HttpClientInitializer = credentials
});
var request = new ReportStateAndNotificationRequest
{
AgentUserId = googleCustomerId,
RequestId = requestId,
Payload = new StateAndNotificationPayload
{
Devices = new ReportStateAndNotificationDevice
{
States = deviceStateList
}
}
};
_log.Debug($"Sending to HomeGraph for devices: {deviceIdList} customer: {googleCustomerId} requestId: {requestId}");
DevicesResource.ReportStateAndNotificationRequest rp = service.Devices.ReportStateAndNotification(request);
ReportStateAndNotificationResponse resop = rp.Execute();
}
}
catch (Exception ex)
{
_log.Error($"Exception in ReportToHomeGraph for Customer: {googleCustomerId}. DeviceList: {deviceIdList}. JsonPath: {_appSettingsRetriever.PrivateGoogleAuthenticationFile} Exception: {ex}.");
}
}
Exception:
2021-09-24 14:16:13,547 [110] ERROR ReportToHomeGraph
Exception in ReportToHomeGraph for Customer: 05. DeviceList: (
fe965e6a-21ad-425f-b594-914bf63510a9,
1cc0ee97-a87f-44c5-a3e3-a39d159ee193,
618cdf94-2b31-434f-b91e-00837d155d4a
).
JsonPath: C:/myfile.json Exception: The service homegraph has thrown an exception:
Google.GoogleApiException: Google.Apis.Requests.RequestError
Requested entity was not found. [404]
Errors [
Message[Requested entity was not found.] Location[ - ] Reason[notFound] Domain[global]
]
at Google.Apis.Requests.ClientServiceRequest`1.<ParseResponse>d__35.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Google.Apis.Requests.ClientServiceRequest`1.Execute()
at BusinessLogic.GoogleAssistant.TokenService.HomeGraph.ReportToHomeGraph.Send(Dictionary`2 deviceStateList,
String requestId, String googleCustomerId) in C:\Repos\GoogleAssistant
.TokenService\HomeGraph\ReportToHomeGraph.cs:line 57.
When users add a new device, the first step you need to do is to issue a Request Sync to Google. This indicates the set of devices for that user has changed, and you need a new Sync request to update the data in homegraph. Google will follow this by delivering a Sync intent to your fulfillment endpoint, which you can respond with the updated set of devices.
Getting a 404 when calling Request Sync might indicate your Service Account Key might be invalid, or the agent user id you target might be wrong. Otherwise getting an error for your Sync Response might indicate it’s structured incorrectly. You can find out more about how to structure it in our examples.

.Net Core Api: Invalid session: Microsoft Graph API Workbook Session Paused

I am using AzureAd along with the Microsoft Graph Client to do calculations on Excel spreadsheets. It works most of the time but every now and again the request comes back with a Invalid Session error:
Status Code: BadRequest
Microsoft.Graph.ServiceException: Code: InvalidSession
Message: The target session is invalid.
Inner error:
Code: invalidSessionReCreatable
Message: The session specified in the request does not exist or is invalid due to a transient error.
Inner error:
Code: InvalidOrTimedOutSession
Message: We noticed that you haven't been interacting with this workbook, so we paused your session.
It seems like the session gets paused before the API gets to finish the call (which happens in less than a second).
Startup Code to configure AD and Graph Services:
services.AddMicrosoftIdentityWebApiAuthentication(Configuration, "AzureAd")
.EnableTokenAcquisitionToCallDownstreamApi()
.AddMicrosoftGraph(Configuration.GetSection("GraphBeta"))
.AddInMemoryTokenCaches();
Creating the session:
WorkbookSessionInfo res = await _graphServiceClient.Groups[_groupId].Drive.Items[productStructureCalculator.CalculatorId].Workbook
.CreateSession(persistChanges)
.Request()
.Header("Prefer", "respond-async")
.PostAsync();
Doing a batch request:
var batchRequestInfo = CreateBatchRequestAsync(sessionId, structure, productStructureCalculator, productMatrixInputs);
var resultRequest = _graphServiceClient.Groups[_groupId].Drive.Items[productStructureCalculator.CalculatorId].Workbook.Worksheets[productStructureCalculator.SheetName]
.Range("D6:J6")
.Request()
.Header("workbook-session-id", "{" + sessionId + "}")
.Header("Prefer", "return=minimal")
.GetHttpRequestMessage();
resultRequest.Method = HttpMethod.Get;
var resultRequestID = Guid.NewGuid().ToString();
var batchResultRequestStep = new BatchRequestStep(
resultRequestID,
resultRequest,
new List<string> { batchRequestInfo.LastEventRequestId }
);
batchRequestInfo.BatchRequestContent.AddBatchRequestStep(batchResultRequestStep);
var returnedResponse = await _graphServiceClient.Batch.Request().PostAsync(batchRequestInfo.BatchRequestContent);
As per | Microsoft Docs ,
InvalidSessionReCreatable :The session specified in the request does not exist or is invalid due to a transient error.
Error Handling : The Microsoft Graph client can try to recreate a session and resume the work. Further access to the session specified in the failed request is not expected.
Please Check if the below work arounds help in your case:
1)
use the CreateSession method > workbook: createSession | Microsoft Docs to get the workbook info, and set the persistChanges setting.
=>(Set var persistChanges = true; )
Code:
var persistChanges = true;
try
{
WorkbookSessionInfo res = await _graphServiceClient.Groups[_groupId].Drive.Items[productStructureCalculator.CalculatorId].Workbook
.CreateSession(persistChanges)
.Request()
.Header("Prefer", "respond-async")
.PostAsync();
var result = res;
return result;
}
catch (Exception ex)
{
Console.WriteLine($"Error getting items: {ex.Message}");
return null;
}
Reference-SO
Or
2)
You can set the Timeout to a higher value .Lets say one hour:
graphServiceClient.HttpProvider.OverallTimeout = TimeSpan.FromHours(1);
Or
3)
Add session in start up class
Ex:
services.AddSession(options => {
options.IdleTimeout = TimeSpan.FromMinutes(30);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
At least chance, take a look at activityBasedTimeoutPolicy which Represents a policy that can control the idle timeout for web sessions for applications that support activity-based timeout functionality.

Join meeting result "Authentication failed due to missing credentials." bigbluebutton?

I am very new to bigbluebutton. I successfully installed bbb on Ubuntu server and enabled API demo. It is working absolutely fine. I am calling API from c# and it is working fine too. I am creating a meeting like below which is working fine.
public CreateMeetingResponse CreateMeeting(CreateMeetingRequest request)
{
var qb = new QueryStringBuilder
{
{"meetingID", request.MeetingID},
{"name", request.Name},
{"attendeePW", request.AttendeePW},
{"moderatorPW", request.ModeratorPW},
{"record", request.Record.ToString()},
{"allowStartStopRecording", request.AllowStartStopRecording.ToString()},
{"autoStartRecording", request.AutoStartRecording.ToString()},
{"voiceBridge", request.VoiceBridge.ToString()},
{"welcome", request.Welcome},
{"recordingmarks", "true"},
{"logoutURL", request.LogoutURL}
};
qb.Add("checksum", GenerateChecksum("create", qb.ToString()));
var createRequest = new RestRequest($"/api/create?{qb}", Method.GET);
var response = Client.Execute<CreateMeetingResponse>(createRequest).Data;
return response;
}
After creating the meeting, i am trying to join the meeting like as below.
public JoinMeetingResponse JoinMeeting(JoinMeetingRequest request)
{
var qb = new QueryStringBuilder
{
{"meetingID", request.MeetingID},
{"fullName", request.FullName},
{"userId", request.UserID},
{"password", request.Password},
{"joinViaHtml5","true" },
{"redirect","false" },
{"guest","true" }
};
qb.Add("checksum", GenerateChecksum("join", qb.ToString()));
var joinRequest = new RestRequest($"/api/join?{qb}", Method.GET);
var joinResponse = Client.Execute<JoinMeetingResponse>(joinRequest);
return new JoinMeetingResponse();
}
The response from bbb server API is "SUCCESS" and message is "You have successfully joined". But when i try to open meeting or join with URL it shows UNAUTHORIZED 401. "Authentication failed due to missing credentials."
I open browser console and it shows:
[18:07:28:0290] DEBUG: clientLogger: Initial connection status change. status: connecting, connected: false https://bbb.adorasoft.net/html5client/7df6acf6cb0f651dba4e71b3adac0efd23889793.js?meteor_js_resource=true:121:1031295
7df6acf6cb0f651dba4e71b3adac0efd23889793.js?meteor_js_resource=true:9 [18:07:28:0970] DEBUG: clientLogger: Initial connection status change. status: connected, connected: true https://bbb.adorasoft.net/html5client/7df6acf6cb0f651dba4e71b3adac0efd23889793.js?meteor_js_resource=true:121:1031295
7df6acf6cb0f651dba4e71b3adac0efd23889793.js?meteor_js_resource=true:9 [18:07:28:0971] INFO: clientLogger: Connection to Meteor took 0.68s https://bbb.adorasoft.net/html5client/7df6acf6cb0f651dba4e71b3adac0efd23889793.js?meteor_js_resource=true:121:1031466
7df6acf6cb0f651dba4e71b3adac0efd23889793.js?meteor_js_resource=true:9 [18:07:29:0142] ERROR: clientLogger: User faced an error on main.joinRouteHandler. g.fetchToken (https://bbb.adorasoft.net/html5client/7df6acf6cb0f651dba4e71b3adac0efd23889793.js?meteor_js_resource=true:121:1033747)
7df6acf6cb0f651dba4e71b3adac0efd23889793.js?meteor_js_resource=true:9 [18:07:29:0144] ERROR: clientLogger: Encountered error while trying to authenticate t (https://bbb.adorasoft.net/html5client/7df6acf6cb0f651dba4e71b3adac0efd23889793.js?meteor_js_resource=true:121:999188)
7df6acf6cb0f651dba4e71b3adac0efd23889793.js?meteor_js_resource=true:9 [18:07:29:0146] ERROR: clientLogger: User could not log in HTML5, hit 401 z.renderByState (https://bbb.adorasoft.net/html5client/7df6acf6cb0f651dba4e71b3adac0efd23889793.js?meteor_js_resource=true:121:1206397)
7df6acf6cb0f651dba4e71b3adac0efd23889793.js?meteor_js_resource=true:9 [18:07:29:0327] ERROR: clientLogger: User could not log in HTML5, hit 401 z.renderByState (https://bbb.adorasoft.net/html5client/7df6acf6cb0f651dba4e71b3adac0efd23889793.js?meteor_js_resource=true:121:1206397)
What i am doing wrong?
So, after investing enough time i got the solution. There was no problem in bigBlueButton. The problem was that "Join" API request from server side.
"The Join request should be made from the client side/Browser"
So what I had to do is instead of passing XML response, I just need to pass the whole Big blue button Join URL with Checksum and redirect = true
so whenever someone want to join they will redirect to the meeting directly.

Why does call to api token during authentication fail in specific environment? (400 error)

Background/Problem: I am running an Angular app (with C#/.NET WebApi/DataAccess) and am getting the following errors when attempting to login (happens in DEV environment, not in REL):
Chrome Dev Tools Console errors:
POST http://localhost:1789/api/token 400 (Bad Request)
Backend
returned code 400, body was [object Object]
Error is only happening in DEV. Does not happen in REL or PROD. This was working in DEV previously.
What I've tried so far:
I am able to make calls to other classes and methods in the WebApi,
but not sure where this error came from.
I don't see any extra discernible information in "Network" tab of
Chrome Dev Tools (it just mentions the status code again)
I used the debugger in the Sources tab of Chrome dev tools and also
did not see any extra discernible information
There have not been any changes in the C# code that I can see from
source control. The Angular component and service are the same as
well.
I have tested other parts of the API as mentioned above
I have checked my config files multiple times and they seem to have
the appropriate values they used to have
I have looked up information about token authorization such as:
https://learn.microsoft.com/en-us/aspnet/aspnet/overview/owin-and-katana/owin-oauth-20-authorization-server
Spotify API bad request on api/token authorization Error: 400
(as well as all the other SO articles on 400 error for api token I
could find)
Debugged in Visual Studio: For OAuthAuthorizationServerOptions:
AccessTokenFormat is null. AuthorizeEndpointPath is {}. But
TokenEndpointPath is {/api/token}
Code:
login.component.ts:
cmdLogin_click()
{
if (this._authForm.value.username != null && this._authForm.value.password != "")
{
if (this._authForm.valid)
{
this.securityService.loginEndpoint(this._authForm.value.username,this._authForm.value.password)
.subscribe(response => {
this.setUser(response);
this.routerService.navigate(['/home']);
},
}
}
}
security.service.ts:
public loginEndpoint(email: string, password: string): Observable<any> {
let url = API_URL + '/api/token';
let ip = "";
const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
let content: string = "grant_type=password&username=" + email + "&password=" + password + "&ip=" + ip
return this.http.post(url, content, { headers: headers }).pipe(
catchError(this.handleError)
)
}
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error.message);
} else {
// The backend returned an unsuccessful response code. // The response body may contain clues as to what went wrong,
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
}
// return an observable with a user-facing error message
return throwError(
'Something bad happened; please try again later.');
};
Startup.cs:
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
Startup.Auth.cs:
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context and user manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
// Configure the application for OAuth based flow
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/api/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromHours(25),
Provider = new EmdOAuthProvider(),
RefreshTokenProvider = new SimpleRefreshTokenProvider()
};
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(OAuthOptions);
}
My expected result is to be able to login without the error. My actual result is the errors listed above.
Been stuck on this for hours. Where should I be focusing at this point?

DropNet Integration - GetAccessTokenAsync error

I'm trying to implement the DropNet library into my Windows Phone app but I'm getting the an error when calling the GetAccessTokenAsync method.
Step 1: Get the oauth token from Dropbox
public void ConnectToDropbox()
{
_client = new DropNetClient(API_KEY, API_SECRET);
_client.UseSandbox = true;
// Get Request Token (oauth token) from Dropbox
_client.GetTokenAsync(
(userLogin) =>
{
// Authorise app with Dropbox
var url = _client.BuildAuthorizeUrl();
browser.LoadCompleted += new System.Windows.Navigation.LoadCompletedEventHandler(browser_LoadCompleted);
browser.Navigate(new Uri(url));
},
(error) =>
{
Debug("Error: GetTokenAsync");
});
}
This seems to work correctly and returns an oauth authorisation code. The URL which the browser navigates to is
https://www.dropbox.com/1/oauth/authorize?oauth_token=TSLEY7lLS8K2Mmnr
Step 2: Convert the oauth token into usable Dropbox API token
void browser_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
Debug("Callback URL: " + e.Uri.AbsoluteUri);
if (e.Uri.AbsolutePath == "/1/oauth/authorize")
{
//The User has logged in!
//Now to convert the Request Token into an Access Token
_client.GetAccessTokenAsync(
(response) =>
{
Debug("User is logged in");
LoadContents();
},
(error) =>
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
Debug("Error getting access token (GetAccessTokenAsync)");
MessageBox.Show(error.Message);
});
});
}
else
{
//Probably the login page loading, ignore
}
}
The GetAccessTokenAsync method throws the following exceptions at runtime:
An exception of type 'System.Net.WebException' occurred in System.Windows.ni.dll and wasn't handled before a managed/native boundary
The in-app MessageBox displays:
Exception of type 'DropNet.Exceptions.DropboxException' was thrown.
All the properties of the DropboxException object are as follows:
Response: RestSharp.RestResponse
Status Code: Unauthorized
Stack Trace:
Data: System.Collections.ListDictionaryInternal
Base Exception: DropNet.Exceptions.DropboxException: Exception of type 'DropNet.Exceptions.DropboxException' was thrown.
Inner Exception:
Type: DropNet.Exceptions.DropboxException
Is the the Status Code Unauthorized relevant? I'm using the appropriate API key and secret provdided by Dropbox.
I'd be grateful if anyone who's experienced similar issues when using DropNet could give me some advice in resolving this problem. Happy to provide any further info if needed.
Thanks in advance,
Andrew

Categories