https://api.dropbox.com/1/account/info generating an Invalid OAuth request - dropbox

Got my tokens and can call the core API, but when I call
https://api.dropbox.com/1/account/info
I get a
{"error": "Invalid OAuth request."}
According to the documentation (https://www.dropbox.com/developers/core/docs#account-info) there are no parameters except the locale, only the GET, which is suspicious.
The use-case I am exercising validates if the access token wasn't revoked by checking the current user's account info.
I am accessing the core-api via HTTP and not via the libraries provided (Python, Ruby, PHP, ...)

You have to add your access token in your url connection by setting the authorization header with your token.
System.out.println("accesstoken:" + access_token);
String token="Bearer ";
token+=access_token;
if (access_token != null) {
URL url = new URL(
"https://api.dropbox.com/1/account/info?locale=English");
connection = (HttpURLConnection) url.openConnection();
This works for me.

Related

Use JSON Web Token and Firestore support for Bearer token

I want to have authentication and authorization support in Firestore while using a node.js app that talks to Firestore. Users interact via a URL (http.get with embedded tokens) and that interacts with a node.js app. The app accepts some input from user, then talks to firestore. The access token needed for the client to perform secure activities are all embedded in the GET url (the id + access token).
I have a flow here, and want to validate if this flow is right or I am missing something? I am unable to find the most definite document that can guide me on the steps to follow.
First off I generate JWT token part before generating the GET url:
The function used to generate the JWT token is as follows:
// generate JWT token
function getJWT() {
var token = jwt.sign({
exp: Math.floor(Date.now() / 1000) + (60 * 60) * constants.JWT_TOKEN_VALIDITY_HOURS,
admin: '​XXXXXXX'
}, constants.JWT_SECRET_TOKEN);
return token;
}
Bearer Tokens: ​I have heard in many forums that it is possible for me to send this JWT web token as a "Bearer token" in the authorisation header. It means firestore magically does all the authorization for me. Anything else I should be doing?
1) I believe I need to sign in using this custom JSON web token, and obtain an ID token. is that correct?
Sign in from a Firebase Client SDK
Use the Firebase Auth REST API to exchange the custom token to an ID token.
2) Then I need pass this ID token (not the JSON web token) to the Cloud Firestore endpoints when I am making a request for db access as an Authorization header set to Bearer {YOUR_TOKEN}.. Then you can access the Firestore REST API with the resulting ID token:
https://firebase.google.com/docs/firestore/use-rest-api#working_with_firebase_id_tokens
Imagine I embed into the header the bearer token also...using the JSON access token or the ID token I get from firestore
return this.http
.get(${OUR URL to app}, {
headers: new HttpHeaders().set('Authorization', Bearer ${JSON Web accessToken or ID Token})
})​
​User clicks on the URL that has this access token. They agree to terms and conditions and then I re-direct them to a cloud function that does some processing.​ This JSON Web token is passed along. I verify the JWT token also​ for authentication purpose using this code.​
function verifyToken(token) {
try {
var decoded = jwt.verify(token, constants.JWT_SECRET_TOKEN);
var admin = decoded.admin;
if (admin == "​XXXXXXXXX") {
return true;
}
return false;
} catch (err) {
console.log(err);
return false;
}
}
​any samples related to this will be helpful.​
related links I used
https://firebase.google.com/docs/firestore/use-rest-api#working_with_firebase_id_tokens
Firestore Custom Tokens
https://auth0.com/blog/how-to-authenticate-firebase-and-angular-with-auth0-part-1/
finally
Protocol specification for https.onCall
in https://firebase.google.com/docs/functions/callable-reference
Optional: Authorization: Bearer
A Firebase Authentication user ID token for the logged-in user making the request. The backend automatically verifies this token and makes it available in the handler's context. If the token is not valid, the request is rejected.
this is the official response I got from Google (but again works only if the user has an authentication request -- mean a valid firebase user I think), but what I want to know is using the Json web token itself can I achieve something like this.
Just to clarify, you'll need either a Firebase ID token or a Google
Identity OAuth 2.0 token to be passed on to the Cloud Firestore
endpoints as an Authorization header set to Bearer {YOUR_TOKEN}.
You may refer on the following links for more information on this:
REST API Firestore authentication with ID Token
https://firebase.google.com/docs/firestore/use-rest-api#authentication_and_authorization
Also, we don't have any samples related to this, but there's an
internal request to improve our REST documentation. I won't be able to
share you any details or timelines as to when it could materialize,
however, you may keep an eye out on our release notes or Firebase blog
for any updates we might have.
I am hopeful in stackoverflow I might get more samples related to this. But for now this is all what I got.

how to refresh google access token with refresh token without SSL?

I have faced a problem to refresh google access token on server side.
RestTemplate restTemplate = new RestTemplate();
MultiValueMap<String, String> params = new LinkedMultiValueMap();
params.add("client_id", clientSecrets.getDetails().getClientId());
params.add("client_secret", clientSecrets.getDetails().getClientSecret());
params.add("refresh_token", this.refreshToken);
params.add("grant_type", "refresh_token");
String result = restTemplate.postForObject(requestUrl, params, String.class);
Response I got from google authentication server is just 403 status code.
and message is like this
{"error":"internal_failure","error_description":"SSL is required to perform this operation."}
Is that compulsory to use SSL on my server just in order to refresh access token ?
It's been tested on my local server and does not attach any SSL to it.
References for this code is from below URL.
https://developers.google.com/identity/protocols/OAuth2WebServer#offline
I solved this issue by adding 'https' protocol instead of 'http' protocol for google api
I had called like
http://www.googleapis.com/oauth2/v4/token
but for SSL call
https://www.googleapis.com/oauth2/v4/token
is required to refresh access token

Get UserInfo from ADFS in UWP with ADAL

I am trying to authenticate the user with ADFS and I am using ADAL. Authetication seems to work since I can get the AccessToken. The problem is that looking at the code authResult contains a UserInfo where all properties (for instance GivenName or FamilyName) are null.
AuthenticationContext authContext = null;
AuthenticationResult authResult;
try
{
authContext = new AuthenticationContext(authority, false);
authResult = await authContext.AcquireTokenAsync(resource, clientId, new Uri(returnUri),
new PlatformParameters(PromptBehavior.Auto, false));
}
Those values are null because of ADFS configuration? I noted that decoding the AccessToken returned I can read User information. But I don't think that decoding the JWT Token is the right way to achieve those information. Do you have a better suggestion?
I have also seen people getting information by using claims, but I don't know exactly how to use it on UWP, since all the sample I found used
ClaimsPrincipal claimsPrincipal = System.Threading.Thread.CurrentPrincipal as ClaimsPrincipal;
But System.Threading.Thread is not available on UWP.
Normally, the access_token is used in Oauth and OpenID connect scenarios and intended to be consumed by the resource. To identify the user we should use the id_token( verify the token and extract the claims abut user by decoding the token). Please refer below about the usage of tokens:
id_token: A JWT token used to represent the identity of the user. The
'aud' or audience claim of the id_token matches the client ID of the
native or server application.
access_token: A JWT token used in Oauth and OpenID connect scenarios
and intended to be consumed by the resource. The 'aud' or audience
claim of this token must match the identifier of the resource or Web
API.
refresh_token: This token is submitted in place of collecting user
credentials to provide a single sign on experience. This token is
both issued and consumed by AD FS, and is not readable by clients
or resources.
And you can refer the link below about the native client to web API scenario for ADFS:
AD FS Scenarios for Developers - Native client to Web API
Depending on the ADFS version of your server. If your company is using Windows Server 2012 R2, then it is ADFS 3.0. I did successfully integrate with SSO login created by the admin of company I am working in. You should refer to this article before venturing in : https://learn.microsoft.com/en-us/previous-versions/adfs-windows-server-2012r2/dn660968(v=msdn.10). Note : you don't even need to make a web api of ToDoList.
using only GetAuthorizationHeader() and authenticationContext.AcquireTokenAsync(), you could obtain the token by asking the user to authorize their credentials and decrypt the receive token.
This is sample of code I did:
authority = https://contoso.com/adfs/ls (Endpoint from the ADFS metadata)
resourceURI = https://localhost:44300/ (Relying party, ask your ADFS admin to register)
clientID = it is recommended to use Package.appmanifest's package name from Packaging tab. As long as it is a unique ID.
clientReturnURI = use the following code to obtain the clientReturnURI (also available in the article in the link) :
string clientReturnURI = string.Format("ms-appx-web://Microsoft.AAD.BrokerPlugIn/{0}",WebAuthenticationBroker.GetCurrentApplicationCallbackUri().Host.ToUpper());
AuthenticationContext ac = new AuthenticationContext(Authority_Uri, false);
AuthenticationResult ar = await ac.AcquireTokenAsync(resourceURI, GlobalVar.clientID, new Uri(clientReturnURI), new PlatformParameters(PromptBehavior.Always, true));
var jwt = new JwtSecurityToken(ar.AccessToken);
string unique_name = jwt.Claims.First(c => c.Type == JwtRegisteredClaimNames.UniqueName).Value;
You can replace JwtRegisteredClaimNames.UniqueName with anything else. It depends what info/claims that is available in the access token. You should inspect the available info in the jwt by placing breakpoint at var jwt. Or you can decrypt the access token in the AuthenticationResult.AccessToken in this website :
https://jwt.ms/
Lastly, you need to install certificate from your ADFS admin and install the certificate across your web and UWP server to allow the application able to trust execute the actions.

Okta: Failed to get authorization code through API call

I'm integrating Okta to my own IdP server by using Okta's API.
I'm implementing the Authorization code flow by following the steps below:
In my own server, use the /api/v1/authn endpoint to get the sessionToken.
Use the sessionToken to obtain the authorization by calling this endpoint: /oauth2/v1/authorize?client_id=" + clientId + "&sessionToken=" + sessionToken + "&response_type=code&response_mode=query&scope=openid&redirect_uri=" + redirectUrl + "&state=evanyang&nonce="
It's supposed to return a response with status code 302 and with the Location header containing the redirect url as well as the code value.
However, I keep getting a response with status code 200 and without the Location header, with a html body saying "You are using an unsupported browser." and "Javascript is disabled on your browser."
According to the API documentation: http://developer.okta.com/docs/api/resources/oidc.html#authentication-request, the sessionToken parameter is sufficient to do this: An Okta one-time sessionToken. This allows an API-based user login flow (rather than Okta login UI).
Am I missing any extra requirement for getting the authorization code through API? Please help.
Thanks in Advance :)
The Authorization Code grant type and the Authorization endpoint in there are meant to be access through a browser, not a non-browser client.
This issue is caused by obtaining session id between obtaining session token and authorization code. Once the session token is used to get session id, it becomes invalid, which means it cannot be used to get authorization code anymore.
According to Okta, the Authorization Code grant type and the Authorization endpoint and be used through a API-based web app too, as long as the session token is provided in the request: http://developer.okta.com/docs/api/resources/oidc.html#authentication-request. In fact, one can use this script(https://github.com/SohaibAjmal/Okta-OpenId-Scripts) to finish the flow.

how do you request a session from servicestack basic authentication, at /auth/basic?

I have set up a servicestack service with basic authentication using the first example, here:
https://github.com/ServiceStack/ServiceStack/wiki/Authentication-and-authorization
This automatically sets up a route: /auth/basic
However, I cannot find any information or examples on how to format a request to this URL (Variables/GET/POST/Auth Header, etc.).
I am able to access a simple service using the basic authentication credentials, so they are active and correct.
I have no custom authentication plugged in, just basic authentication.
I have tried:
Using a JsonServiceClient to send UserName and Password variables by GET or Json POST to /auth/basic, with and without an Auth header also containing the user & pass.
Using a browser to send GET requests with URL parameters of the user/pass, or as http://user:pass#localhost:123/auth/basic
I always just get "HTTP/1.1 401 Invalid BasicAuth credentials".
The only examples I can find involve some kind of custom authentication, and then /auth/credentials is accessed, but I want to use /auth/basic
I have looked at the code and it looks like it reads an Auth header, but the service does not accept one.
I am actually trying to get this working so I can then disable it and verify it is disabled (I want to require basic authentication for every request).
Questions are:
What is the correct way to call the /auth/basic service? I will take a servicestack client API example, specifications or even a raw http request!
How do you disable the /auth services altogether?
Many thanks.
What is the correct way to call the /auth/basic service? I will take a servicestack client API example, specifications or even a raw http request!
var client = new JsonServiceClient("http://localhost:56006/api");
var resp = client.Post(new Auth() { UserName = "TestUser", Password = "Password" });
This assumes you have also registered an ICacheClient and IAuthUserRepository (and added a user account)
The JSON format looks like this if you call into /auth/basic?format=json
{
"UserName": "admin",
"Password": "test"
"RememberMe": true
}
How do you disable the /auth services altogether?
Don't add the AuthFeature plugin to configuration.
You can also remove plugins
Plugins.RemoveAll(x => x is AuthFeature);
Putting the following in apphost config seems to do the trick.
//Disable most things, including SOAP support, /auth and /metadata routes
SetConfig(new EndpointHostConfig()
{
EnableFeatures = Feature.Json | Feature.Xml
});
I am a little suspicious about what this does to /auth however, because it returns an empty response, while most routes return 404.
So, would this truly disable the /auth functionality? As in, if someone formed a correct request to /auth/credentials, will it still return an empty response?