I am getting a 401 (Unknown authentication scheme) problem when retrieving data for group-membership.
My application uses IN.API.Raw for retrieving the data but generates the error message as 401 (Unknown authentication scheme).
The response is shown below:
{
"errorCode": 0,
"message": "Access to group-memberships denied",
"requestId": "6YW0D6JWWR",
"status": 403,
"timestamp": 1395933151070
}
and the JS code is below for the group-memberships.
IN.API.Raw("/people/~/group-memberships?count=100&start=0")
.result(function(result) {
jQuery('#ligroupslabel').html("<strong>To edit the group, simply choose from your list of groups below:</strong>");
for (var i = 0; i < result._total; i++) {
jQuery('#linkedInGroups ul').append(
"<li><a href=\"linkedin_connection\" onclick=\"saveGroup('" + result.values[i].group.id + "','" + result.values[i].group.name + "'); return false;\">" +
result.values[i].group.name + "</a></li>");
}
});
Error 401 = Your request may be alright, but there is the little problem of authentication. You have to provide some proof of who you are. You would usually have a header which gives an authentication scheme and some authentication information in the request.
You may not have supplied any authentication scheme at all; quite possible that you get the (not entirely accurate) error message "unknown authentication scheme" in that case.
Related
I am running into an error when using next-auth, and Okta as the provider. It redirects me back to my app but I get a page saying 'try signing in with another account' and redirects to 'api/auth/signin?error=Callback'
The error I get in the terminal with next auth's debugger is:
[next-auth][debug][oauth_callback_protection] Comparing received and expected state {
state: 'b3ef7bf3d4a5aa8f5f81fc95260502b0a206180bd0a831bb27b26d8c21271e33',
expectedState: 'b3ef7bf3d4a5aa8f5f81fc95260502b0a206180bd0a831bb27b26d8c21271e33'
}
[next-auth][error][oauth_get_access_token_error]
https://next-auth.js.org/errors#oauth_get_access_token_error {
statusCode: 401,
data: '{"errorCode":"invalid_client","errorSummary":"No client credentials found.","errorLink":"invalid_client","errorId":"******************","errorCauses":[]}'
} undefined undefined
[next-auth][error][oauth_get_access_token_error]
https://next-auth.js.org/errors#oauth_get_access_token_error {
statusCode: 401,
data: '{"errorCode":"invalid_client","errorSummary":"No client credentials found.","errorLink":"invalid_client","errorId":"**************","errorCauses":[]}'
} okta ************************
[next-auth][error][oauth_callback_error]
https://next-auth.js.org/errors#oauth_callback_error {
statusCode: 401,
data: '{"errorCode":"invalid_client","errorSummary":"No client credentials found.","errorLink":"invalid_client","errorId":"*******************","errorCauses":[]}'
}
This is my Okta App settings:
I have checked the cliendID and client secret and they are correct. Does anyone have any clues?
I know it can work with okta because I have had it working with another app, but I have tried to replicate the exact same setup.
in [...nextauth].js:
Providers.Okta({
clientId: process.env.OKTA_CLIENT_ID,
clientSecret: process.env.OKTA_CLIENT_SECRET,
domain: process.env.OKTA_DOMAIN,
accessTokenUrl: `https://${process.env.OKTA_DOMAIN}/oauth2/default/v1/token`,
authorizationUrl: `https://${process.env.OKTA_DOMAIN}/oauth2/default/v1/authorize/?response_type=code`,
})
It is a bug in next-auth package. Had the same issue and after debugging with a colleague and trying out a couple of things we came to following patch that works for us.
diff --git a/node_modules/next-auth/dist/server/lib/oauth/client.js b/node_modules/next-auth/dist/server/lib/oauth/client.js
index b4e48c2..7f68dd7 100644
--- a/node_modules/next-auth/dist/server/lib/oauth/client.js
+++ b/node_modules/next-auth/dist/server/lib/oauth/client.js
## -160,7 +160,7 ## function _getOAuth2AccessToken() {
headers.Authorization = 'Basic ' + Buffer.from(provider.clientId + ':' + provider.clientSecret).toString('base64');
}
- if ((provider.id === 'okta' || provider.id === 'identity-server4') && !headers.Authorization) {
+ if ((provider.id === 'identity-server4') && !headers.Authorization) {
headers.Authorization = "Bearer ".concat(code);
}
The issue seems to be an issue with sending both client_id and secret as query parameters but also sending a Authorization header. Removing the Authorization header made the idp integration work.
Also worth noting this; https://developer.okta.com/docs/reference/api/oidc/#client-secret
I choose ASP.NET Web Application and then Web API. I leave the Authentication at "Individual User Accounts" and create the project.
I have made no additional changes except to add an ajax call to api/Account/Register.
When I make a request with a password that is too simple I get the json response below - it seems really hard to work with.
Is there some method for working with this, or do I really need to access textStatus.responseJSON.ModelState.\_empty\_[0] to get a nice text response from this? Will all error messages follow this general response format for ASP.Net Application rest requests?
PS: Actually I don't even know how to deal with a property called \_empty\_ as textStatus.responseJSON.ModelState.\_empty\_[0] doesn't even work.
My textStatus object:
{
"readyState": 4,
"responseText": "{\"Message\":\"The request is invalid.\",\"ModelState\":{\"\":[\"Passwords must have at least one non letter or digit character. Passwords must have at least one uppercase ('A'-'Z').\"]}}",
"responseJSON": {
"Message": "The request is invalid.",
"ModelState": {
"_empty_": [
"Passwords must have at least one non letter or digit character. Passwords must have at least one uppercase ('A'-'Z')."
]
}
},
"status": 400,
"statusText": "Bad Request"
}
UPDATE:
This is the actual body of the response.
But I still don't know how to access the property whose name is "". And, I want to be sure that this is how all error messages will be returned to me.
{
"Message": "The request is invalid.",
"ModelState": {
"": [
"Passwords must have at least one non letter or digit character. Passwords must have at least one uppercase ('A'-'Z')."
]
}
}
UPDATE:
This seems to parse it pretty well. Is this about as good as it gets?
error: function (textStatus, errorThrown) {
var json = textStatus.responseJSON;
var message = json.Message;
if (json.ModelState) {
for (var i = 0; i < json.ModelState[''].length; i++) {
if (i == 0) message += "\n";
message += "\n" + json.ModelState[''][i];
}
}
alert(message);
}
This HttpHandler does not send a response if con.Open() throws an exception, for example if faultyConnectionString has an invalid database name. Why?
public void ProcessRequest(HttpContext context)
{
int status = 400;
string message = "Test error!";
string faultyConnectionString = "Data Source=LOCALHOST\\SQLEXPRESS;Initial Catalog=XXX;User ID=XXX;Password=XXX";
try
{
using (SqlConnection con = new SqlConnection(faultyConnectionString))
{
//throw new Exception("This works as expected, and is returned to client");
con.Open();
}
}
catch (Exception ex)
{
status = 500;
message = "Test Exception: " + ex.Message;
}
context.Response.StatusCode = status;
context.Response.StatusDescription = message;
}
Here is how I am handling the call in the client:
function GetContacts() {
$.ajax({
type: "POST",
url: "xxx.ashx",
data: "",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
dataType: "text", // "json",
success: function (response, a, b) {
alert(response.status + " " + response.statusText);
},
error: function (response, a, b) {
alert(response.status + " " + response.statusText);
}
});
}
If I F12 in FireFox it shows me that there is no Response received after the request is sent. In IE it shows me "SCRIPT7002: XMLHttpRequest: Network Error 0x2ef3, Could not complete the operation due to error 00002ef3.". In both cases the jquery ajax call returns status=0 and statusText="error".
If I comment out the two lines inside the catch block then it works as expected, sending the 403 code to the client and ignoring the exception.
Different types of exceptions do not have the same problem. If I throw a new Exception() before con.Open() then it also works as expected. What is different with SqlException?
UPDATE: The very first time I hit ProcessRequest it gets called 5 times in succession before the client shows the status=0 result (breakpoint on first line is hit 5 times).
FIDDLER: If I fire up Fiddler it (fiddler) intercepts the transaction and sends "504 Fiddler - Receive Failure" to my ajax call. Looks like the initial repetition may be a retry mechanism, when fiddler is active it does it 13 times.
Fiddler reports: "Session #xxx raised exception System.Net.Sockets.SocketException An existing connection was forcibly closed by the remote host".
I believe the way your client (browser) handles 404 errors is what is causing this, and each browser type is handling the error differently. 404 errors are specific to "Not Found" so you may want to use a different error code such as a 500 error. More info on error codes is available here: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
Please keep in mind that passing back detailed error messages to a client could be a security issue due to information leakage. You may be better off passing back a generic error to the client and logging detailed error information on the server side.
Edit:
Testing this locally, the way you are setting context.Response.StatusDescription to contain ex.Message is producing an invalid HTTP response. Try only placing text such as Internal Server Error in there. Additional details can be added to the body of the response using context.Response.Write(bodyText) but please keep the security implications of this in mind.
I got the foloowing error and I do not know how to solve it. I read the page but my problem is not the same as the writer problem (space in URL).
com.google.api.client.http.HttpResponseException: 403 Forbidden
{
"error": {
"errors": [
{
"domain": "usageLimits",
"reason": "userRateLimitExceededUnreg",
"message": "User Rate Limit Exceeded. Please sign up",
"extendedHelp": "https://code.google.com/apis/console"
}
],
"code": 403,
"message": "User Rate Limit Exceeded. Please sign up"
}
}
I checked the page 1; they mentioned "Freebase allows developers a free quota of up to 100,000 (one hundred thousand) read calls per day per person" and I only quota 49886 read calls.Then I got this error and I do not know how to solve the problem.
I created a server key for using Freebase API. Also, I defined my query in follwoing way:
String query="https://www.googleapis.com/freebase/v1/topic"+mId+"?key=xxx";
GenericUrl url = new GenericUrl(query);
HttpRequest request = requestFactory.buildGetRequest(url)
HttpResponse httpResponse = request.execute();
JSONObject response = (JSONObject)parser.parse(httpResponse.parseAsString());
The mId is mid in Freebase corpus. In addition, I add the flowing catch based on this pageto prevent error since in each second we can only send 10 requests to Freebase server.
catch (HttpResponseException e) {
if (e.getStatusCode()== 403
&& (e.getContent().contains("userRateLimitExceededUnreg")
|| e.getContent().contains("uotaExceeded"))) {
System.out.println("sleep");
Thread.sleep((2^ n) *1000 + randomGenerator.nextInt(1001));
}
All I want is to do a POST like this:
You can post a score or a user by issuing an HTTP POST request to /USER_ID/scores with the app access_token as long as you have the publish_actions permission.
Name Description Type Required
score numeric score with value > 0. integer yes
I am doing this:
try {
http.request( POST, URLENC ) {
uri.path = "/100000781309474/scores?" + user.accessToken
body = [score:10]
response.success = { resp ->
println "Tweet response status: ${resp.statusLine}"
assert resp.statusLine.statusCode == 200
}
response.failure = { resp ->
println "Unexpected error: ${resp.status} : ${resp.statusLine.reasonPhrase}"
}
}
} catch ( HttpResponseException ex ) {
// default failure handler throws an exception:
println "Unexpected response error: ${ex.statusCode}"
}
but it's returning this exception:
400: Bad request
It means that the POST isn't correct, yes?
Can someone tell me how to do the post with the user score?
Referring to https://developers.facebook.com/docs/score/
I first see you're passing in the user token
uri.path = "/100000781309474/scores?" + user.accessToken
It should be the app access token. The format is http://graph.facebook.com/{userId}/scores?access_token={AppAccessToken} with parameter name of score and value of {theirScore}. Be sure that access_token is an app access token. Also be sure your app is registered as an game app.