authlib: InsecureRequestWarning when fetching token - authlib

I am using a flask client to perform openid authentication. However I get the following warning
Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
When fetching the token a request is done using requests.Session.requests here.
Adpating the request method of OAuth2Session fixes the warning.
def request(self, method, url, withhold_token=False, auth=None, **kwargs):
"""Send request with auto refresh token feature (if available)."""
if not withhold_token and auth is None:
if not self.token:
raise MissingTokenError()
auth = self.token_auth
return super(OAuth2Session, self).request(
method, url, auth=auth, verify=True, **kwargs)
Should verification not be enabled by default? Is there a more elegant way to pass verify=True?

You can pass verify directly to the methods of the registered RemoteApp when you fetch the token like this:
token = oauth.remote_app_name.authorize_access_token(verify=True)
I believe SSL verification is enabled by default, however, I use an env var to enable/disable the verification for the requests on a development environment.

Related

outlook oauth 2.0 and IMAP

I'm trying to achieve the authentication for office 365 accounts by using oauth 2.0 ,
i'm using PublicClientApplication and InteractiveRequestParameters method for acquiring access token and in result successfully received access token ,refresh token and id token but when i am using access_token to connect to imap, i am getting error as authentication failure, can anyone please help me out what am i missing here.
have given all the required permissions from azure portal.
here is my code through which i am trying to connect to server
store.connect("outlook.office365.com", "my_email_id, access_token); //here store is imap
properties i have set are:
properties.put("mail.smtp.port", "587");
properties.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.setProperty("mail.imap.socketFactory.fallback", "false");
properties.setProperty("mail.imap.port", "993");
properties.setProperty("mail.imap.socketFactory.port", "993");
properties.put("incomingHost", "outlook.office365.com");
properties.put("mail.imap.ssl.enable", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("outgoingHost", "smtp.office365.com");
properties.setProperty("mail.imaps.ssl.trust", "*");
Note: when i am providing password instead of access_token , i am successfully able to login but failure while using access_token.
Thank you !!
You cannot use your access token in place of a password. IMAP requires that your client use SASL XOAUTH2 to authenticate. Details can be found here.
For example, the SASL XOAUTH2 format to access test#contoso.onmicrosoft.com with access token EwBAAl3BAAUFFpUAo7J3Ve0bjLBWZWCclRC3EoAA is:
base64("user=test#contoso.onmicrosoft.com^Aauth=Bearer EwBAAl3BAAUFFpUAo7J3Ve0bjLBWZWCclRC3EoAA^A^A")
After base64 encoding, this translates to the following string. Note that line breaks are inserted for readability.
dXNlcj10ZXN0QGNvbnRvc28ub25taWNyb3NvZnQuY29tAWF1dGg9QmVhcmVy
IEV3QkFBbDNCQUFVRkZwVUFvN0ozVmUwYmpMQldaV0NjbFJDM0VvQUEBAQ==

Keycloak 401 on getAccessToken()

sometimes on production I have an following error, its while doing registration, after getting email to confirm account, there is special client for that, so they must be good otherwise other clients wont register
javax.ws.rs.NotAuthorizedException: HTTP 401 Unauthorized
at org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.handleErrorStatus(ClientInvocation.java:221)
at org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.extractResult(ClientInvocation.java:195)
at org.jboss.resteasy.client.jaxrs.internal.proxy.extractors.BodyEntityExtractor.extractEntity(BodyEntityExtractor.java:62)
at org.jboss.resteasy.client.jaxrs.internal.proxy.ClientInvoker.invokeSync(ClientInvoker.java:151)
at org.jboss.resteasy.client.jaxrs.internal.proxy.ClientInvoker.invoke(ClientInvoker.java:112)
at org.jboss.resteasy.client.jaxrs.internal.proxy.ClientProxy.invoke(ClientProxy.java:76)
at com.sun.proxy.$Proxy277.search(Unknown Source)
at com.company.KeycloakAdminService.getUserFromKeycloakByUsername(KeycloakAdminService.java:35)
on calling this:
AccessTokenResponse accessToken = keycloakUserReader.tokenManager().getAccessToken();
timeouts config:
I can not reproduce it locally.. not sure what can be the reason, maybe someone here also had similar issues with Keycloak ?
thanks!

Spring Boot OAuth 2 SSO how to extract token to pass back to thick client application

I have a thick client application (C# but that should not matter).
All the users already exist in an authentication/authorization (3rd party) system that provides OAuth 2 API (authorize/access_token plus a user_info service).
I have a Spring Boot web service tier that will have RESTful web services that will be called by the thick client application that must only be called by authenticated users for protected web services.
To authenticate the thick client will launch a Web Browser (OS installed default) and will open https to restful.web.server:8443 /login of the Spring Boot web service tier. This will do the OAuth 2 (authorization_code) interaction. Once redirected back with a valid token I want to redirect to a custom URI passing the token and for the browser to close (if possible) so an OS registered application can extract the token and pass it via an IPC mechanism to the thick client application.
The thick client application can then pass the token to the Web Services in the header (Authorize: TOKEN_TYPE TOKEN_VALUE).
The Web Services must then validate the authenticity of the token.
The Web Services if called with an invalid token must just return an HTTP error and JSON error content (e.g. code+message) and not try and redirect to the login screen. This will be orchestrated by the thick client application.
I have no concern with any of the custom URI handling, IPC development, or thick client web service calls. It is all the Spring/SSO magic in getting the token to be sent to my thick client and returning the relevant error from protected web services without returning a redirect to the SSO login.
I appear to be authenticating and being sent a token but then I get an exception.
I have made some progress and it appears that by manually launching a browser and hitting my web service tier https to restful.web.server:8443 /login it redirects to the SSO site https to 3rdparty.sso.server /oauth/authorization (passing in client_id, redirect_uri, response_type=code, state). I can log in, and Spring is calling the https to 3rdparty.sso.server /oauth/access_token endpoint (I had to create a custom RequestEnhancer to add in Authorization: Basic ENCODED_CLIENT_ID_AND_CLIENT_SECRET to satisfy the access_token SSO API requirement).
This returns 200 OK but then I get exceptions and do not know how to extract the token. The access_token returned may not be using the standard property names but unsure when to go and check if this is the case. I done the authentication this way to keep the client id and client secret out of the thick client application and my web services must do the authorisation anyway. If there is a better way or pointers to someone else doing this already it would be greatly appreciated. I find so many examples that are either not quite relevant or more towards web applications.
server:
port: 8443
ssl:
key-store: classpath:keystore.p12
key-store-password: **********
keyStoreType: PKCS12
keyAlias: tomcat
servlet:
context-path: /
session:
cookie:
name: UISESSION
security:
basic:
enabled: false
oauth2:
client:
clientId: *******
clientSecret: *****************
accessTokenUri: https://3rdparty.sso.server/oauth2/access_token
userAuthorizationUri: https://3rdparty.sso.server/oauth2/authorize
authorizedGrantTypes: authorization_code,refresh_token
scope:
tokenName: accessToken
redirectUri: https://restful.web.server:8443/login
authenticationScheme: query
clientAuthenticationScheme: header
resource:
userInfoUri: https://3rdparty.sso.server/oauth2/userinfo
logging:
level:
org:
springframework: DEBUG
spring:
http:
logRequestDetails: true
logResponseDetails: true
#Configuration
#EnableOAuth2Sso
#Order(value=0)
public class ServiceConectWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter
{
#Override
protected void configure(HttpSecurity http) throws Exception {
http
// From the root '/' down...
.antMatcher("/**")
// requests are authorised...
.authorizeRequests()
// ...to these url's...
.antMatchers("/", "/login**", "/debug/**", "/webjars/**", "/error**")
// ...without security being applied...
.permitAll()
// ...any other requests...
.anyRequest()
// ...the user must be authenticated.
.authenticated()
.and()
.formLogin().disable()
.logout()
.logoutSuccessUrl("/login")
.permitAll()
.and()
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
;
}
I expect that the secured web services would be accessible once authenticated via the browser whilst testing without the client and would not expect exceptions to be thrown. I need to be able to extract the returned token and pass it back to my thick client.
Redirects to 'https://3rdparty.sso.server/oauth2/authorize?client_id=***HIDDEN_CLIENT_ID***&redirect_uri=https://localhost:8443/login&response_type=code&state=***HIDDEN_STATE_1***'
Then FilterChainProxy : /login?code=***HIDDEN_CODE_1***&state=***HIDDEN_STATE_1*** at position 6 of 12 in additional filter chain;
Request is to process authentication
RestTemplate : HTTP POST https://3rdparty.sso.server/oauth2/access_token
RestTemplate : Response 200 OK
IllegalStateException: Access token provider returned a null access token, which is illegal according to the contract.
at OAuth2RestTemplate.acquireAccessToken(OAuth2RestTemplate.java:223) ```
Then end up at an error page
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
There was an unexpected error (type=Internal Server Error, status=500).
Access token provider returned a null access token, which is illegal according to the contract.
The access_token service was returning non-standard JSON names.
I created a MyOwnOAuth2AccessToken with the relevant non-standard JSON names the necessary de/serialisation classes.
I created a MyOauth2AccesTokenHttpMessageConverter class for returning my OAuth2AccessToken.
The MyOauth2AccesTokenHttpMessageConverter was plumbed in from an
#Configuration
public class ServiceConnectUserInfoRestTemplateFactory implements UserInfoRestTemplateFactory
within the
#Bean
#Override
public OAuth2RestTemplate getUserInfoRestTemplate()
method with the following code:
List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
messageConverters.add(new ItisOAuth2AccessTokenHttpMessageConverter());
messageConverters.addAll((new RestTemplate()).getMessageConverters());
accessTokenProvider.setMessageConverters(messageConverters);
There is probably a better way to do this but this worked for me.

SP-Initiated SLO Generating multiple SLO requests

I'm using the sustainsys saml2 owin package, and I'm having problems with SP-initiated SLO. I'm new to the saml process, so there's a good chance I'm doing something wrong.
Our signout workflow is as follows:
User hits myapp.com/signout
myapp redirects to myapp.com/saml2/logout
The owin package generates a saml request and sends it to the Idp's slo route
The Idp responds with a successful saml response to the same url: myapp.com/saml2/logout
At this point, the owin package is generating another saml request to sign the user out of the idp. It would get stuck in an infinite redirect, if the Idp didn't halt the process.
Here's a snapshot of my network panel in chrome:
I'm using https://github.com/mcguinness/saml-idp as a development Idp, and here's a stub of my owin configuration:
I suspect I've misconfigured something or I'm using the saml2/logout route inappropriately, but I also find it odd that the owin package would generate another request when it gets a successful response.
Update 11.9.2018
Here's my verbose log starting from the logout process:
Expanded Saml2Url
AssertionConsumerServiceUrl: http://locala.foliotek.com/saml2/linuxdev/Acs
SignInUrl: http://locala.foliotek.com/saml2/linuxdev/SignIn
LogoutUrl: http://locala.foliotek.com/saml2/linuxdev/Logout
ApplicationUrl: http://locala.foliotek.com/
=================
Initiating logout, checking requirements for federated logout
Issuer of LogoutNameIdentifier claim (should be Idp entity id): http://myidentityprovider.com
Issuer is a known Idp: True
Session index claim (should have a value): http://Sustainsys.se/Saml2/SessionIndex: 1926000282
Idp has SingleLogoutServiceUrl: http://myidentityprovider.com/saml/slo
There is a signingCertificate in SPOptions: True
Idp configured to DisableOutboundLogoutRequests (should be false): False
=================
Expanded Saml2Url
AssertionConsumerServiceUrl: http://myserviceprovider.com/saml2/linuxdev/Acs
SignInUrl: http://myserviceprovider.com/saml2/linuxdev/SignIn
LogoutUrl: http://myserviceprovider.com/saml2/linuxdev/Logout
ApplicationUrl: http://myserviceprovider.com/
=================
Initiating logout, checking requirements for federated logout
Issuer of LogoutNameIdentifier claim (should be Idp entity id): http://myidentityprovider.com
Issuer is a known Idp: True
Session index claim (should have a value): http://Sustainsys.se/Saml2/SessionIndex: 1926000282
Idp has SingleLogoutServiceUrl: http://myidentityprovider.com/saml/slo
There is a signingCertificate in SPOptions: True
Idp configured to DisableOutboundLogoutRequests (should be false): False
=================
Expanded Saml2Url
AssertionConsumerServiceUrl: http://myserviceprovider.com/saml2/samltestid/Acs
SignInUrl: http://myserviceprovider.com/saml2/samltestid/SignIn
LogoutUrl: http://myserviceprovider.com/saml2/samltestid/Logout
ApplicationUrl: http://myserviceprovider.com/
=================
Initiating logout, checking requirements for federated logout
Issuer of LogoutNameIdentifier claim (should be Idp entity id): http://myidentityprovider.com
Issuer is a known Idp: False
Session index claim (should have a value): http://Sustainsys.se/Saml2/SessionIndex: 1926000282
Idp has SingleLogoutServiceUrl:
There is a signingCertificate in SPOptions: True
Idp configured to DisableOutboundLogoutRequests (should be false):
=================
Expanded Saml2Url
AssertionConsumerServiceUrl: http://myserviceprovider.com/saml2/linuxdev/Acs
SignInUrl: http://myserviceprovider.com/saml2/linuxdev/SignIn
LogoutUrl: http://myserviceprovider.com/saml2/linuxdev/Logout
ApplicationUrl: http://myserviceprovider.com/
=================
Http POST binding extracted message
<samlp:LogoutResponse xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" ID="_d02d42fbb8ed00bbee02" InResponseTo="idf75b17a7713e4f698f891edf1fcca117" Version="2.0" IssueInstant="2018-11-09T16:44:01Z" Destination="http://myserviceprovider.com/saml2/linuxdev/logout"><saml:Issuer xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">http://myidentityprovider.com</saml:Issuer><Signature xmlns="http://www.w3.org/2000/09/xmldsig#"><SignedInfo><CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" /><SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" /><Reference URI="#_d02d42fbb8ed00bbee02"><Transforms><Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" /><Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" /></Transforms><DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256" /><DigestValue>X+93fiv6vuuy8sIhmFFxIVxNgAy/f1Zk62RRh/rn91I=</DigestValue></Reference></SignedInfo><SignatureValue>qXMlLe2fciQR6u7Ddx40RFI51IJ5r8A3m7X7mrgIMHBdFf2vypiCFxqOrEOKCSIqWzDUxVXujWyMQzO/zZtVyZlm6xXnb3lId0VDHLEIUT/8kyNsodzvzPIyTMaMMV/cmhQ3UZlYRv9BeyPswpkosFTn/xc6c+BX9z+w4AN4KDMFfYlTeu/uyDBa1u5zr/Ze6OXwP7///Mo/zdy2ZXyHJhia+yscWZ+Hrb49ekI9csJvuic0p6ttJPjS72tmEesGR1vLT0Y/5T+SqOVmmbmN8hZygRxrEwgfo9oNI+8BBC7aYK2PCtTZZFwoO3KsEEttQjxzKTbzja9s8XslGxfKkw==</SignatureValue><KeyInfo><X509Data><X509Certificate>MIIDgzCCAmugAwIBAgIJALOc35pt94LuMA0GCSqGSIb3DQEBCwUAMFgxCzAJBgNVBAYTAlVTMREwDwYDVQQIDAhNaXNzb3VyaTERMA8GA1UEBwwIQ29sdW1iaWExFTATBgNVBAoMDEZvbGlvdGVrIEluYzEMMAoGA1UEAwwDSWRwMB4XDTE4MTEwOTE1MDI0MVoXDTM4MTEwNDE1MDI0MVowWDELMAkGA1UEBhMCVVMxETAPBgNVBAgMCE1pc3NvdXJpMREwDwYDVQQHDAhDb2x1bWJpYTEVMBMGA1UECgwMRm9saW90ZWsgSW5jMQwwCgYDVQQDDANJZHAwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDhX8PX+C/1orPpFnOIRy7UkrLU7YCq6DNzB5QSUzT366++ZCWFzx+Ub+HFxbR/htY/EAramlCNFawOSGS6mnWev/tiokGObXdMK6tAXyZZMc/u9Rg65EjM892Oep6gIEWgjnE+l7M8v84QOWqAl+GaeM8YZJKHXAZ+7MVMgkMWeYKrksvQdKrQjhyzqoLmBNL5yGBgEH1KEtFy0A0qYdiwdWptvaeWkTk6tp3kfminRaQ1bj/BmMwAWeDbE7EFkk7wF1ig4QhTINoVFQhPGa/+sPg+NuDNlGszDBV3fmfpHwPpjRr4zzoNyJnMvf3u1+C63c7DPSC+uKGvYlgeWbc/AgMBAAGjUDBOMB0GA1UdDgQWBBQvczxcOnaazyGJ8H3vi1vY6g24xDAfBgNVHSMEGDAWgBQvczxcOnaazyGJ8H3vi1vY6g24xDAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQAoMsoDnrEPCS+VIqVlnlbxxd4lx5AYMvUTZPugJ88+Jjp/1kkKbxWzbJBR1yl0v9quLoQ/u5XkYoSI3u/azydywpADlgsKHrL7Ger+ZU2pdSCK9LTbOP3gnginmPldB7LW6jxWxuEYadWLpYocEFU6Ua7XJUDOzMpO3SXxmhiyhvQC2PF0Q1uehNkwIpUP+9I9ulAXxjScyputgYjkWjiLYu+gcWYW6DmeWqJKyYR6XSwaa+QV4/UPupBmSc1Bx7BuF29+1RwJyTEI6Uz5wQe+lbzZ5ay3J3oa3lilwYg/HYq4mQzVucHEhQLsU9ZIfuGStMHX23sdzWuEBbcQgCCd</X509Certificate></X509Data></KeyInfo></Signature><samlp:Status><samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success" /></samlp:Status></samlp:LogoutResponse>
=================
Here's my info log from the logout process
Sending logout request to http://myidentityprovider.com
=================
Sending logout request to http://myidentityprovider.com
=================
Federated logout not possible, redirecting to post-logout and clearing local session
=================
Received logout response Microsoft.IdentityModel.Tokens.Saml2.Saml2Id, redirecting to http://myidentityprovider.com/saml/slo?SAMLRequest=fZJdS8MwFIbvB%2FsPJbeyNv3Y1oatOBhCYXrhxAvvYpKu0XzUnlT2803rJpugkJvz8bznPYesgGqVtGRnD7Z3j%2BKjF%2BCCo1YGyHdpjfrOEEtBAjFUCyCOkf3mfkeSEJO2s84yq9Al8z9CAUTnpDUoqLZrJHmRFuw1LnKcUpYt2JImC1rXOc94yuZpnaHgWXTggTXyvKcAelEZcNQ4n8JxPovjGS6e4gXJUjLPX1Cw9WtIQ91INc61JIpqq6R%2Fpj9y8RmOkRPvIbOaLPESR4P3CJRF5XQSBKtxFTIO68qThLKMKnrFjlgSnXVX0RV3ofTgL1Ftgzvbaer%2BPlEcxmNG8lk9thKhqVQbzjsBgErXCN4Py4GWrrlxjdUU3m4PQ9Pg52zge9yFgZbsvYA%2FSGW4OJZxkSwwxkmenIhf9enkJ3%2F1Ocov&RelayState=MnZ2DPYtc9cY8CkEaR5CRJDz&SigAlg=http:%2F%2Fwww.w3.org%2F2001%2F04%2Fxmldsig-more%23rsa-sha256&Signature=LS0QmYpXX2utWqmEKQJmMeQukm%2FFFVUZCP8I0C7sIt1LklVK0NzuqrJgG9VGwO6uPBZObpZ%2FU9%2BZVddCoIGmg3FCKrhhW7hspsQNN%2FGqpf0QY3kxW%2Bt956TqgynW0yM4I9%2Fc7X%2F9Sy4keFu1uxihjemm%2BCNlZdRS71ch4SyG4YStmKZrWJns1T6H4m8d2eBK7O2KVn9iqwIh6OaV5S6obhpMH9gzx5Y01uc5fTm2gfdoExuVNsKbZB8ycois1MEEz7Uox5zRm09gEfCNMHKf2Dp%2Fwd7GmQoK84VvPoNrxl5047WxfKxkhQPTRFbM5h50peFjOlnFN0yKw9C3DARSBw%3D%3D
=================
After digging into the code a little, I've found if I do the following:
GetLogoutResponseState = (req) => { return null; }
...in my Saml2AuthenticationOptions.Notifications, it works as expected.
From here, I still suspect I'm configuring something wrong, or the IDP is sending the wrong data, but I don't know where StoredRequestState is being initialized. It appears that it contains the wrong returnUrl.
Looking at the logs, I think that this is the sequence of events.
SignOut on your application is hit and redirects to the logout endpoint in the Saml2 library.
The logout endpoint is hit and initiates a logout request to the Idp.
The Idp renders a page (that probably contains some kind of SAML response - but might be incorrect).
The logout endpoint is hit again and this is wrong
Either this is a duplicate request.
Or it is a response that doesn't get properly detected by the Sustainsys.Saml2 library
What makes me really confused is that in the second run all the requirements for a federated logout are fulfilled. Specifically it does find the LogoutNameIdentifier. That shouldn't be possible, as the local session cookie is normally cleared when the redirect to the Idp is done.
To understand further what is happening I recommend that you download the Sustainsy.Saml2 source, link directly to the project and set a breakpoint at LogoutCommand.Run. That should help you understand better and be able to further examine the requests.
I tracked my problem down to the LogoutCommand.Run being called twice during the initial GET request to /saml2/logout. Once from the Saml2AuthenticationHandler .ApplyResponseGrantAsync method, and once from the Saml2AuthenticationHandler.InvokeAsync.
The solution was to set Compatibility = new Compatibility { StrictOwinAuthenticationMode = true } in my SPOptions. Which prevents the LogoutCommand from executing within the ApplyResponseGrantAsync method.
I'm a little unclear on the Passive vs Active authentication modes, but my guess is that I'm indicating to the Sustainsys package that I'm controlling the authentication (including signing out) manually. Maybe Anders can clear that up?

Robot Framework api test with OAUTH2 Authorization Request Header

I am trying to use the RequestsLibrary on an api thats using the OAUTH2 authentication.
Authentication is via OAUTH2 with credentials being supplied to the /v1/authtoken endpoint.
Subsequent calls to the APÍ need to have the token included as a ‘bearer’ in the ‘Authorization’ header of the http requests.
So below is the test case. The error I am getting is:
401 != 200
The credentials work ok in jmeter and a list of accounts is returned. However, I am not able to get the RF script work. Any help will be appreciated.
In the script,
Log to Console ${accessToken} returns the access token: 8ETFXTZOWQLrgsMj7c_KuCEeypdj-eO1r...
Log to Console ${token} returns: Bearer 8ETFXTZOWQLrgsMj7c_KuCEeypdj-eO1r...
*** Test Cases ***
Get authToken
Create Session hook http://xxxx.azurewebsites.net verify=${True}
${data}= Create Dictionary grant_type=client_credentials client_id=yyy-zzzz client_secret=xxxxxxxxxxxxxxx
${headers}= Create Dictionary Content-Type=application/x-www-form-urlencoded
${resp}= post request hook /v1/authtoken data=${data} headers=${headers}
Should Be Equal As Strings ${resp.status_code} 200
Dictionary Should Contain Value ${resp.json()} bearer
${accessToken}= evaluate $resp.json().get("access_token")
Log to Console ${accessToken}
${Bearer}= Set Variable Bearer
${token}= catenate Bearer ${accessToken}
Log to Console ${token}
${headers}= Create Dictionary Authorization=${token}
${resp1}= get request hook /v1/integration/accounts headers=${headers}
Should Be Equal As Strings ${resp1.status_code} 200
#Log to Console ${resp1.json()}
I am using OAuth 2.0 authentication as well for my salesforce automation.
My first answer would be to skip client based authentication and switch to username/password based authentication
Get authToken by Password Authentication
RequestsLibrary.Create Session hook https://<url>/services/oauth2 verify=${True}
${data}= Create Dictionary grant_type=password client_id=1abc client_secret=2abc username=test#test.com password=keypass
${headers}= Create Dictionary Content-Type=application/x-www-form-urlencoded
${resp}= RequestsLibrary.Post Request hook /token data=${data} headers=${headers}
Should Be Equal As Strings ${resp.status_code} 200
${accessToken}= evaluate $resp.json().get("access_token")
Log to Console ${accessToken}
If you are using client based or web based authentication, there will be a login screen that will be used by the user to enter their username/password to authorise the app to send requests on its behalf. Have a look at these pages for more information as they primarily discuss about using either refresh tokens or skipping the user prompt altogether.
Why does Google OAuth2 re-ask user for permission when i send them to auth url again
https://salesforce.stackexchange.com/questions/785/authenticate-3rd-party-application-with-oauth2
I have added the new answer for this question.
RequestsLibrary.Create Session OA2 <Your Server URL> verify=${True}
${data}= Create Dictionary Token_Name=TestTokenname grant_type=<grant type> client_Id=<your Id> Client_Secret=<Your client secret> scope=<your scpe>
${headers}= Create Dictionary Content-Type=application/x-www-form-urlencoded
${resp}= RequestsLibrary.Post Request OA2 identity/connect/token data=${data} headers=${headers}
BuiltIn.Log To Console ${resp}
BuiltIn.Log To Console ${resp.status_code}
Should Be Equal As Strings ${resp.status_code} 200
Dictionary Should Contain Value ${resp.json()} Testtokenname
${accessToken}= evaluate $resp.json().get("access_token")
BuiltIn.Log to Console ${accessToken}
${token}= catenate Bearer ${accessToken}
BuiltIn.Log to Console ${token}
${headers1}= Create Dictionary Authorization=${token}
RequestsLibrary.Create Session GT <Your Server URL> verify=${True}
${resp}= RequestsLibrary.Get Request GT <Your API URL> headers=${headers1}
Should Be Equal As Strings ${resp.status_code} 200