Is there anyway/endpoint to create access_token in code for Dropbox SDK authorization? - dropbox

I am using dropbox javascript sdk for file uploads using following end points.
For file below 150MB
/upload
For file above 150MB
/files/upload_session/start
/files/upload_session/append_v2
For Authorization, I am using the following code for now.
const ACCESS_TOKEN = 'my_access_token_created_manualy_from_app_console';
var dbx = new Dropbox.Dropbox({ accessToken: ACCESS_TOKEN, refresh_token });
Now I don't want to go to the app console every now and then to get access token.
Is there any way I could handle it in my code? Any API/ajax request to get access token in response to app_key and app_secret?

Getting a Dropbox access token for a user's account always requires some initial manual interaction from the user to authorize the app in some way. This cannot be done entirely programmatically. For the developer's own account, such as in your case, you can generate an access token on the App Console. For arbitrary end-users, this is instead processed via the OAuth app authorization flow.
You can refer to the OAuth Guide and authorization documentation for more information. For the Dropbox JavaScript SDK in particular, there's an example of processing the OAuth flow here.

Related

I want to use MsGraph in B2C, but I get a corrs error when getting an access token

I have an SPA that uses B2C as its certification.
not AD, im using B2C.
Now I want to display user information on the SPA,
so I want to use MsGraphAPI to get data from B2C.
Therefore, we are trying to obtain an access token using credential flow.
The code is as follows
requestUri = "https://login.microsoftonline.com/{tenandId}/oauth2/v2.0/token";
var params = new URLSearchParams();
params.append("grant_type","client_credentials");
params.append("client_id","XXXX");
params.append("client_secret","ZZZZ");
params.append("scope","https://graph.microsoft.com/.default");
const response = fetch(requestUri, {
method:"POST",
body:params
});
At this time, the developer tool shows a corrs error.
The following error.
access to fetch "https://login.microsoftonline.com/{tenandId}/oauth2/v2.0/token" from origin "http://localhost:3000" has been blocked by CORS policy.
How can I resolve this?
SPA is available at http://localhost:3000.
Is the localhost no good?
The purpose of authenticating is to get user information. You can insert any attribute into the token, and then parse the id_token to display the users profile information in your application. Calling MS Graph API for this seems counter intuitive.
Next, you shouldnt be using client_credentials in your SPA, those are secret credentails, and should only be used by your server. By exposing those credentials in your SPA, any user could extract them and use them to read your entire directroy store. This is why you are getting a CORS error, it's never supposed to be running on the client browser.

Exchanging code for access token fails when using Sign in with Google in Dropbox

We have an application that uses Dropbox API. When the user goes through the Dropbox OAuth 2 flow and signs-in using their email address and password, all works fine and we get the access_token. However, when the user uses the "Sign in with Google" flow in the Dropbox authorization dialog, we get back code which we then try to exchange for access token but the request fails with {"error_description": "code doesn't exist or has expired", "error": "invalid_grant"}.
Here's the steps we use:
1.
var dbx = new Dropbox.Dropbox({ clientId: clientId });
var authUrl = dbx.getAuthenticationUrl('https://www.dropbox.com/1/oauth2/redirect_receiver');
This gives us url https://www.dropbox.com/oauth2/authorize?response_type=token&client_id=...&redirect_uri=https://www.dropbox.com/1/oauth2/redirect_receiver.
2.
Open authUrl in a popup.
3.
User uses "Sign in with Google"
4.
We get a redirect to the URL below that contains the code:
https://www.dropbox.com/google/authcallback?state=...&code=...&scope=...
Now trying to exchange the code for access token with POST to https://api.dropboxapi.com/oauth2/token gives us:
{"error_description": "code doesn't exist or has expired", "error": "invalid_grant"}
The problem here is that, given the use of the Google Sign In flow, there are actually two OAuth authorization flow instances occurring; the Google Sign In flow is nested inside the Dropbox app authorization flow. Your app doesn't actually need to know about this though.
That https://www.dropbox.com/google/authcallback URL is Dropbox's redirect URL for the Google Sign In flow, and accordingly the code given there is for the Google OAuth flow, not the Dropbox OAuth flow. Attempting to use it for the Dropbox OAuth 2 flow will accordingly fail as you've seen (since it actually came from Google, not Dropbox).
You should have your app wait until your own redirect URL (in your shared code, https://www.dropbox.com/1/oauth2/redirect_receiver) is accessed, and only then take the code from there and exchange it for a Dropbox access token.

What does Ember-simple-auth check against?

I have been looking for answer of implementing ember-simple-auth (oauth2-password-grant) for days without luck. I use firebase to sign up users, which is successful. However on the log in page, the action of this.get('session').authenticate('authenticator:oauth2', credentials) seems to cause a json error (SyntaxError: Unexpected token < in JSON at position 0).
So my first question is, in theory, how does this authentication check if the user's email/password is correct? Meaning, in which file is the "answer" located? Am I supposed to define a token? If yes, I already tried "serverTokenEndpoint: 'http://localhost:4200/' or serverTokenEndpoint: 'http://localhost:4200/token" and nothing works. Thanks.
Ember simple auth sends login request to API(in your case Firebase). If entered credentials are valid your API will authenticate user, create and save auth token. Authenticated user with created token will be sent to Ember and token will be saved in local storage by Ember simple auth. Every subsequent request from Ember after login needs to include that token in its header and API will authenticate your request based on that token(comparing token from Ember with the one saved in API).

How to provide credentials for Google Apps user creation using JAVA API

From the Google Documentation I understood that the email quota is not used anymore. I'm OK with that, but the question is how to provide credentials for user creation in Google Apps. Currently I'm doing it like that:
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(transport)
.setJsonFactory(jsonFactory)
.setClientSecrets(adminid, adminpwd)
.build();
But I'm receiving 401 Unauthorized.
Where's your access token? Try
credential.refreshToken();
accessToken = credential.getAccessToken();
credential.setAccessToken(accessToken);
You'll probably want to retrieve a refresh token too. It may be cleaner to build your credentials with the tokens. Refer to the docs here or here.

OWIN/OAuth2 3rd party login: Authentication from Client App, Authorization from Web API

I am trying to create a Web API that allows the API's clients (native mobile apps) to login using a 3rd party cloud storage provider. I'm using the following general flow from Microsoft:
Here is what I am trying to achieve:
I am using the default ASP.NET Web API Visual Studio template with external authentication, along with the OWin.Security.Providers Nuget package for Dropbox login functionality, and the existing built-in login functionality for Google (Drive) and Microsoft (OneDrive).
The issue I'm having is that the built-in functionality all seems to do the authentication and authorization as part of one flow. For example, if I set up the following in Startup.Auth.cs:
DropboxAuthenticationOptions dropboxAuthOptions = new DropboxAuthenticationOptions
{
AppKey = _dropboxAppKey,
AppSecret = _dropboxAppSecret
};
app.UseDropboxAuthentication(dropboxAuthOptions);
... and navigate to this url from my web browser:
http://<api_base_url>/api/Account/ExternalLogin?provider=Dropbox&response_type=token&client_id=self&redirect_uri=<api_base_url>
I am successfully redirected to Dropbox to login:
https://www.dropbox.com/1/oauth2/authorize?response_type=code&client_id=<id>&redirect_uri=<redirect_uri>
... and then after I grant access, am redirected back to:
http://<api_base_url>/Help#access_token=<access_token>&token_type=bearer&expires_in=1209600
... as you can see the token is part of that, so could be extracted. The problem is that the client needs to be the one navigating to Dropbox and returning the authorization code back up to the Web API, and the Web API would send the authorization code back to the third party to get the token which would then be returned to the client... as shown in the diagram above. I need the ExternalLogin action in the AccountController to somehow retrieve the Dropbox url and return that to the client (it would just be a json response), but I don't see a way to retrieve that (it just returns a ChallengeResult, and the actual Dropbox url is buried somewhere). Also, I think I need a way to separately request the token from the third party based on the authorization code.
This post seems a little similar to what I am trying to do:
Registering Web API 2 external logins from multiple API clients with OWIN Identity
... but the solution there seems to require the client to be an MVC application, which is not necessarily the case for me. I want to keep this as simple as possible on the client side, follow the flow from my diagram above, but also not reinvent the wheel (reuse as much as possible of what already exists in the OWIN/OAuth2 implementation). Ideally I don't want the client to have to reference any of the OWIN/OAuth libraries since all I really need the client to do is access an external url provided by the API (Dropbox in my example), have the user input their credentials and give permission, and send the resulting authorization code back up to the api.
Conceptually this doesn't sound that hard but I have no idea how to implement it and still use as much of the existing OAuth code as possible. Please help!
To be clear, the sample I mentioned in the link you posted CAN be used with any OAuth2 client, using any supported flow (implicit, code or custom). When communicating with your own authorization server, you can of course use the implicit flow if you want to use JS or mobile apps: you just have to build an authorization request using response_type=token and extract the access token from the URI fragment on the JS side.
http://localhost:55985/connect/authorize?client_id=myClient&redirect_uri=http%3a%2f%2flocalhost%3a56854%2f&response_type=token
For reference, here's the sample: https://github.com/aspnet-security/AspNet.Security.OpenIdConnect.Server/tree/dev/samples/Mvc/Mvc.Server
In case you'd prefer a simpler approach (that would involve no custom OAuth2 authorization server), here's another option using the OAuth2 bearer authentication middleware and implementing a custom IAuthenticationTokenProvider to manually validate the opaque token issued by Dropbox. Unlike the mentioned sample (that acts like an authorization proxy server between Dropbox and the MVC client app), the JS app is directly registered with Dropbox.
You'll have to make a request against the Dropbox profile endpoint (https://api.dropbox.com/1/account/info) with the received token to validate it and build an adequate ClaimsIdentity instance for each request received by your API. Here's a sample (but please don't use it as-is, it hasn't been tested):
public sealed class DropboxAccessTokenProvider : AuthenticationTokenProvider {
public override async Task ReceiveAsync(AuthenticationTokenReceiveContext context) {
using (var client = new HttpClient()) {
var request = new HttpRequestMessage(HttpMethod.Get, "https://api.dropbox.com/1/account/info");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.Token);
var response = await client.SendAsync(request);
if (response.StatusCode != HttpStatusCode.OK) {
return;
}
var payload = JObject.Parse(await response.Content.ReadAsStringAsync());
var identity = new ClaimsIdentity("Dropbox");
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, payload.Value<string>("uid")));
context.SetTicket(new AuthenticationTicket(identity, new AuthenticationProperties()));
}
}
}
You can easily plug it via the AccessTokenProvider property:
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions {
AccessTokenProvider = new DropboxAccessTokenProvider()
});
It has its own downsides: it requires caching to avoid flooding the Dropbox endpoint and is not the right way to go if you want to accept tokens issued by different providers (e.g Dropbox, Microsoft, Google, Facebook).
Not to mention that if offers a very low security level: since you can't verify the audience of the access token (i.e the party the token was issued to), you can't ensure that the access token was issued to a client application you fully trust, which allows any third party developer to use his own Dropbox tokens with your API without having to request user's consent.
This is - obviously - a major security concern and that's why you SHOULD prefer the approach used in the linked sample. You can read more about confused deputy attacks on this thread: https://stackoverflow.com/a/17439317/542757.
Good luck, and don't hesitate if you still need help.