I am trying to get the code from json using below url using postman.but could able to get the code in json.
uber login link
Moreover when i hit this url in browser i am redirecting to my localhost url with query parameter where i can get the code.
Step 1. Create an OAuth2Credentials object with your client ID, client secret, scopes, and a redirect callback URI to capture the user’s authorization code.
SessionConfiguration config = new SessionConfiguration.Builder()
.setClientId("YOUR_CLIENT_ID")
.setClientSecret("YOUR_CLIENT_SECRET")
.setScopes(yourScopes)
.setRedirectUri(redirectUri)
.build();
OAuth2Credentials credentials = new OAuth2Credentials.Builder()
.setSessionConfiguration(config)
.build()
Step 2. Navigate the user to the authorization URL from the OAuth2Credentials object.
String authorizationUrl = credentials.getAuthorizationUrl();
Step 3. Once the user approves the request, you get an authorization code. Create a credential object to store the authorization code and the user ID.
Credential credential = credentials.authenticate(authorizationCode, userId);
I am confused with step 2 and step 3.
- what should i have to do with authorizationUrl in step 2 ?.
- How can i get authorizationCode in step 3 using authorizationUrl?.
You should follow the OAuth2.0 process, documented in the developer docs. Basically, you configure your OAuth2.0 settings. Your settings will generate a specific authentication URL (including client_id and scopes requested). This URL needs to be opened in a webview. Your users have to login with their Uber account and either approve or deny access to the scopes. This is the URL you get in step 2.
If the users click on approve in the auth webview, the configured redirect URI will be called through the Uber server. This callback will have a URL parameter for the authorizationCode.
Related
I'm building a Gmail add-on with 2 steps:
Authorization with Gmail account.
Authenticate to access my service.
Example: The same as Trello add-on:
When I click the button to login, a login form appears like this:
I want to receive data response after sign-in. I've read ActionResponse documentation, but can not find a solution.
How can I receive the data response?
I believe , you are trying to authorize a custom service.
In order to authorize a custom service like trello, you will have to configure oAuth for it.
Create an oAuth service at gmail add-on to request access to trello.
Once the user completes the oAuth flow, you can use the oAuth service to get the access token. Use this token to access the endpoints whenever required.
Refer example
Edit 1:
Action Response
The usage is as follows:
//action
var onTestBtnClick = CardService.newAction().setFunctionName('onTestBtnClick');
//Button
var testBtn = CardService.newTextButton().setText('test').setOnClickAction(onTestBtnClick);
//action handler
function onTestBtnClick(){
//do some action and finally open google.com
return CardService.newActionResponseBuilder()
.setOpenLink(CardService.newOpenLink()
.setUrl("https://www.google.com"))
.build();
}
You need to setup a separate authentication page for your server(3rd party service). The user has to go through the auth process on your page. Once the user successfully authenticates with your page you need to redirect him to the redirect_uri which is passed to your page from the add-on as an url parameter. Script at the redirect_uri will hit your token url endpoint, which you specify when initiating add-ons auth service. If your token url endpoint returns a valid response, authcallback function in your add-on code is triggered which caches the session and lets the user proceed with using your add-on.
Here's a diagram of the overall flow:
Check out this library Google provides to make the implementation easier.
Also checkout my post which goes into more detail on how to connect your 3rd party services to Gmail add-on
Please see this documentation https://isamatov.com/gmail-add-on-connect-non-google-service/
This will provide you the your ans.
You need to the login page url in
setAuthorizationBaseUrl('https://domain/login.php')
The response which you want to receive is need to set in below URL
setTokenUrl('https://domain/response.php')
function getService() {
return OAuth2.createService('Demo Auth')
.setAuthorizationBaseUrl('https://domain/json.php')
.setTokenUrl('https://domain/token.php')
}
I have a Function in Azure, which has MSI (Managed Service Identity) enabled which I am trying to use to access an Azure based WebAPI (App Service WebApp) which in turn has Azure AD Authentication enabled (all same Azure Directory).
My WebAPI has an Azure App registered so it can use AAD Authentication.
This app also has the necessary AppRoles configured in its Manifest (for types 'User' and for 'Application').
I have also verified that the Functions Identity (app) was successfully created in Azure AD when I enabled MSI on the Function.
When I try to obtain a token within my Function using MSI i receive a 400 Bad Request response / error:
"ExceptionMessage": "AADSTS50105: Application '###' is not assigned to a role for the application '###'
"ErrorCode": "invalid_grant"
I have ensured the Resource value I pass in is my webAPIs app ID URI.
string resource = "<My App URI>";
string apiversion = "2017-09-01";
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Secret", Environment.GetEnvironmentVariable("MSI_SECRET"));
var r = await client.GetAsync(String.Format("{0}/?resource={1}&api-version={2}", Environment.GetEnvironmentVariable("MSI_ENDPOINT"), resource, apiversion));
return r;
But I still get the same error. The code for requesting a token is fine, and the error does infact point towards a permissions issue.
The one thing I have not been able to do (and I guess this is the problem) is find a way to give add the new MSI/Function Identity to the Users & Groups of the webAPIs Azure App. No matter what I try my Functions App Identity does not appear in the Users list when I search for it to add as a member of the webAPI app (with the Application role).
Does anyone have any suggestions as to why I cannot add the Functions MSI to an Apps Users & Groups or to an Azure AD Group?
Or am I doing something else wrong perhaps?
Juuna was spot on in his response to my original post:
When enabling MSI on a service only a Service Principal is created in Azure AD and as such this wont appear in search results when trying to add the SP as a member of a Group or to User & Groups of an Azure AD App.
In order to assign your MSI created Service Principal permissions to your App you need to:
Edit your apps manifest and ensure you have app roles with allowed member type = "Application"
Run the PowerShell cmdlet "New-AzureADServiceAppRoleAssignment (link) to grant your Service Principal the Application role you added to your apps manifest
Within your MSI enabled service re-try requesting a token
For me, following the above, I can now successfully request app tokens from my Function so my same Azure Function can call my WebApp (which is AAD Authentication enabled).
In fact, when you enable MSI, it will create a service principal(not a user), so you could not find it in Users&Groups.
You could find it on Azure Portal and try to give permissions you need. Azure Active Directory -->Enterprise applications
Note: The service principal name is same with your function name.
In function, you should use the following code to get token, please refer to this link.
using Microsoft.Azure.Services.AppAuthentication;
using Microsoft.Azure.KeyVault;
// ...
var azureServiceTokenProvider = new AzureServiceTokenProvider();
string accessToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://management.azure.com/");
// OR
var kv = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
What i need to do is to authenticate myself into the GoolgeDrive API (I use it in python) to access my drive to do some automatique task.
I would like that my script run alone every hour without any intervention. So what i need is a way to create a credentials object with my login and password.
Is it possible without any redirection and so on?
I think it is not possible to achieve this with user id and password. The way Google Drive implements this is using a refresh token. That means that you authenticate your app one time interactively. This enables you app for one hour. If the refresh token mechanism is properly configured, the app will renew the token every time it needs it subsequently.
Basically the following steps need to be taken
Visit console.developers.google.com
Register a project and obtain Oauth Client IDs
Select as type web server and enter "http://localhost:8080/" as authorized redirect URL
Download the client_secrets.json and store it in the root of your python app
Create a file called "settings.yaml" at the same place with the following content
client_config_backend: settings
client_config:
client_id: YOUR_CLIENT_ID_GOES_HERE
client_secret: YOUR_CLIENT_SECRET_GOES_HERE
save_credentials: True
save_credentials_backend: file
save_credentials_file: credentials.son
get_refresh_token: True
oauth_scope:
- https://www.googleapis.com/auth/drive.file
- https://www.googleapis.com/auth/drive.install
In your python code you need to do proper authentication and credential saving:
gauth = GoogleAuth()
gauth.settings["get_refresh_token"]=True
gauth.settings["approval_prompt"]="force"
if exists(self.credsFile):
gauth.LoadCredentialsFile(self.credsFile)
if gauth.credentials is None:
# Authenticate if they're not there
gauth.LocalWebserverAuth()
gauth.SaveCredentialsFile(self.credsFile)
elif gauth.access_token_expired:
# Refresh them if expired
gauth.Refresh()
gauth.Authorize()
else:
# Initialize the saved creds
gauth.Authorize()
# Save the current credentials to a file
gauth.SaveCredentialsFile(self.credsFile)
self.driveInstance= GoogleDrive(gauth)
Make sure that you pass in self.credsFile as a valid filename
Executing this code should give you a URL at the console. Copy it to a browser, authenticate and give your consent. Google should ask you for two consents, the second is to authenticate for Google Drive - which is actually done by the refresh token.
The redirect url from the initial credential config in the developer console is called once the consent is given. It calls the temporary web server started by your application. This is how the call back is done. (This implies you have to run browser and your app on the same machine for this step - you may copy over all three files to your server)
From now on your app should run forever without requiring user interaction.
I wrote calss that saves refresh and access token in my db. I can generate access token by refresh token too. everything works well. I working with web application. now I have another question:
1)
For example, I have already saved Refresh token. then if another person comes, I should check if that person have refresh token in my database to generate her access token. but I should have her user ID firstly.
2)
to get user ID I need her credentials
For example:
Oauth2.Builder builder = new Oauth2.Builder(new NetHttpTransport(), new JacksonFactory(), credentials);
Oauth2 userInfoService = builder.build();
Userinfo userInfo= userInfoService.userinfo().get().execute();
3)
and to get credentials I need authorizationCode:
Credential credentials = exchangeCode(authorizationCode);
4)
and to get authorizationCode User Should Click "Allow Acess" in order to retrieve that code? is it right?
for example:
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(jsonFactory, GoogleStorage.class.getResourceAsStream(CLIENTSECRETS_LOCATION));
flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory, clientSecrets, SCOPES).setAccessType("offline").setApprovalPrompt("force").build();
and get URL where autorization code will be retrieved:
flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build();
for instance URL:
https://accounts.google.com/o/oauth2/auth?access_type=offline&approval_prompt=force&client_id=695230079990-bus3d9gp31vvv64qq5n4ma9mk8vtc1ck.apps.googleusercontent.com&redirect_uri=http://localhost/oauth2callback&response_type=code&scope=https://www.googleapis.com/auth/drive.file%20https://www.googleapis.com/auth/userinfo.email%20https://www.googleapis.com/auth/userinfo.profile
must one person click that button everytime she try to connect to Drive API? I see web applications, where one person clicks that button only once. how to get Autorization code without every time clicking "Allow Acess". I need to click that only once.
Users do not have to grant access to the app every time they run it. You store their credentials in a database and reuse them when needed.
Check the Java DrEdit guide for a complete sample app showing how to get a complete set of credentials for every request:
https://developers.google.com/drive/examples/java
I'm trying to use the new Box authentication API with OAuth. I would like to use the credential of the the box account I'm currently using to authorize my application.
The configuration of OAuth requests a redirection URI and I don't know what must be entered there. In the previous authentication method, the following URI was given http://www.box.net/api/1.0/auth/{ticket}, but this was done after getting the authentication ticket.
I'm new to OAuth so my question may be a bit obvious... but I'd like to know how to do the authentication with the credentials of a box account user.
I'm doing this in a Windows application, so I would also like to understand how to show the response from the request.
When I was searching around for answers on creating a Box.net application for desktop trying to get the login authentication took more than that it really should have...
So I decided to put together an article on my website that talks through the process of creating a C# .Net 4.0 desktop application that can login and work with their SDK. This is using their new OAuth 2.0 login system.
Firstly we send the initial web request using a standard HttpWebRequest object to get the UI web page for the OAuth 2.0 login. Once the web response has been returned, we convert it into a Stream for our web-browser to consume. The redirect URI can be any HTTPS based URI.
string baseURI = "https://www.box.com/api/oauth2/authorize?";
string responseType = "&response_type=code";
string clientId = "&client_id=YOUR OWN CLIENT ID";
string redirectURI = "&redirect_uri=https://app.box.com/services/poc_connector";
var targetUri = new Uri(baseURI + responseType + clientId + redirectURI);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(targetUri);
To inject the Stream into the web-browser control we use the document property
webBrowser1.DocumentStream = view;
Once that is done all the operations by the user are handled by the web-browser control. To capture the Authentication token when the user presses the "Grant access" button. We add an event listener for the web-browsers Navigated event.
private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
if (e.Url.AbsolutePath != "blank" && e.Url.ToString().Contains("&code="))
{
Token = e.Url.ToString().Substring(e.Url.ToString().IndexOf("&code="));
Token = Token.Replace("&code=", String.Empty);
this.Close();
}
}
Link my original article and source code: link
The first step in the OAuth 2 process is sending the user to https://api.box.com/oauth2/authorize with response_type and client_id as parameters of the request. The redirect URL will be the same as what you set in V1. If you client_id was 123456, for example, you could direct the user to
https://api.box.com/oauth2/authorize?response_type=code&client_id=123456
See here for more info.