APEX and Keycloak integration - redirect problem after login - single-sign-on

I'm trying to upgrade my APEX application (APEX 20.2.0.00.20) with a Keycloak authorization procedure.
What I am doing:
A - On Keycloak:
Realm: we already have a realm configured, which is used by other apps, in other development technologies.
1 - Client configuration - first attempt:
Root URL: ${authBaseUrl}
Valid Redirect URIs: /realms/[realm]/[client]/*
Base URL: /realms/[realm]/[client]/
Web Origins: *
2 - Client configuration - second attempt:
Root URL: empty
Valid Redirect URIs: http://[APEX app IP]:7020/*
Base URL: http://[APEX app IP]:7020/ords/[workspace]/r/[app_name]/
Web Origins: *
APEX configuration:
Authentication Scheme:
Credential Store: [APEX webcredential configured to keycloak client]
Authentication Provider: generic oauth2 provider.
Authorization Endpoint URL:
https://[keycloak address]/auth/realms/[realm]/protocol/openid-connect/auth
Token Endpoint URL:
https://[keycloak address]/auth/realms/[realm]/protocol/openid-connect/token
User Info Endpoint URL:
https://[keycloak address]/auth/realms/[realm]/protocol/openid-connect/userinfo
Token Authentication Method: basic authentication and client id in body
Scope: email
Authentication URI Parameters: empty
Username: #sub# (#APEX_AUTH_NAME#)
Convert Username To Upper Case: no
Verify Attributes: yes
** Tests **
I run my APEX app URL in workspace.
Test result of Client configuration nr. 1:
The following URL is shown as result:
https://[keycloak host]/auth/realms/[realm]/protocol/openid-connect/auth?response_type=code&client_id=[client_name]&scope=email&redirect_uri=http://[APEX address]:7020/ords/apex_authentication.callback&state=[A TOKEN/HASH]
And on the screen, the keycloak background image with the message:
Invalid parameter: redirect_uri. and a return to application link.
Test result of Client configuration nr. 2:
The keycloak login URL is activated and the login form is shown.
I type my user and password (keycloak user, configured on the client) and submit.
The following URL is shown as result:
https://[keycloak host]:7020/ords/apex_authentication.callback?state=[A TOKEN/HASH]
And on the screen, a APEX grey background (I know is a apex screen because a error with the icon is shown here) with the message:
Error processing request.
Contact your application administrator.
Question:
I think the second configuration is better, because I can do the Login on keycloak, but the redirect by keycloak to APEX fails, I think I APEX side.
Maybe any information sent by keycloak is wrong or it is missed.
Anyone knows what is the right configuration in APEX and keycloak?

Related

.NET Core Facebook - "Please make sure your redirect_uri is identical"

I'm out of ideas. I have a .NET Core 2.1 web app using Facebook Login. Facebook Login worked just fine until I upgraded from .NET Core 1.1 to 2.1. This works fine locally (localhost), but fails on our staging server (Apache on CentOS, EC2).
Our Facebook Login redirect URI is set up correctly in the Facebook app's login settings: http://example.com/ and https://example.com/ (see screenshot below).
What's interesting is in our .NET Core 1.1 branch, the request to http://example.com/signin-facebook?code=SOME_CODE shows up in the log once. In our .NET Core 2.1 branch, the request shows up twice, back-to-back.
Any idea how to dig more into the Facebook middleware that IdentifyFramework is using under the hood?
Facebook Login Settings:
Debug Log:
.NET Core 2.1.802, CentOS (Linux), EC2 instance
// debug ouput
AuthenticationScheme: Facebook was challenged.
Executed action Foobar.Controllers.AccountController.FacebookLogin
Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 2.1144ms 302
Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://example.com/signin-facebook?code=SOME_LONG_CODE
Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://example.com/signin-facebook?code=SOME_LONG_CODE
Error from RemoteAuthentication: OAuth token endpoint failure: Status: InternalServerError;
Headers: WWW-Authenticate: OAuth "Facebook Platform" "invalid_code"
"Error validating verification code.
Please make sure your redirect_uri is identical to the one you used in the OAuth dialog request"
Error from RemoteAuthentication: OAuth token endpoint failure: Status: InternalServerError;
Headers: WWW-Authenticate: OAuth "Facebook Platform" "invalid_code"
facebook-api-version: v2.12

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.

firebase facebook Login: auth/internal-error

I'm having issues with using the facebook login feature.
At the moment I have yet to deploy and am testing locally on my machine.
I've followed all the steps of:
1) Adding the facebook App ID and App Secret
2) changed the OAuth redirect URI to https://study-buddy-6646a.firebaseapp.com/__/auth/handler
However I am still getting the following error:
{"error":{"code":400,"message":"Error getting access token from
FACEBOOK, OAuth2 redirect uri is:
https://study-buddy-6646a.firebaseapp.com//auth/handler, response:
OAuth2TokenResponse{params:
error=OAuthException&error_description=Error%20validating%20client%20secret.,
httpMetadata: HttpMetadata{status=400, cachePolicy=NO_CACHE,
cacheDuration=null, cacheImmutable=false, staleWhileRevalidate=null,
filename=null, lastModified=null, headers=HTTP/1.1 200 OK\r\n\r\n,
cookieList=[]}}","errors":[{"message":"Error getting access token from
FACEBOOK, OAuth2 redirect uri is:
https://study-buddy-6646a.firebaseapp.com//auth/handler, response:
OAuth2TokenResponse{params:
error=OAuthException&error_description=Error%20validating%20client%20secret.,
httpMetadata: HttpMetadata{status=400, cachePolicy=NO_CACHE,
cacheDuration=null, cacheImmutable=false, staleWhileRevalidate=null,
filename=null, lastModified=null, headers=HTTP/1.1 200 OK\r\n\r\n,
cookieList=[]}}","domain":"global","reason":"invalid"}]}}
Any help would be greatly appreciated!

Keycloak state parameter invalid

When user clicks login, redirected to Keycloak login page & then after successful login, user comes back to application with 400 error page.
Server log shows following:
[Server:node-00] 13:40:00,709 WARN
[org.keycloak.adapters.OAuthRequestAuthenticator] (default task-30)
state parameter invalid
My application conf is:
<subsystem xmlns="urn:jboss:domain:keycloak:1.1">
<secure-deployment name="appWEB.war">
<realm>demo</realm>
<resource>app</resource>
<public-client>true</public-client>
<auth-server-url>http://localhost:8180/auth</auth-server-url>
<ssl-required>EXTERNAL</ssl-required>
</secure-deployment>
</subsystem>
Application URL is https://localhost:8443/app & redirect_url is https://localhost:8443/app/private.jsf.
When I use http, it works. But the error comes when I use same with https.
Any thoughts?
Here it can be many scenario which may failing with https
Keycloak running in https
Create self sign certification for keycloak.
Import this certificate to your local Java environment.SO handshake can be possible.
I hope you generate the certificates in keycloak you can find the the certificate inside keycloak/security/ssl.

PingFederate SLO - Status Message: Invalid signature

After I invoke single-log-out (SLO), by calling 'GET' on https://[PingFederate Server Instance]:[Port]/sp/startSLO.ping, my PingFederate server begins making requests to my SP logout services. [I know this because I can see it happening in Fiddler.]
But when one my SPs invokes “https://<PingFederate DNS>:XXXX” + request.getParameter(“resume”); (per #Scott T.'s answer here), I get an error message:
Error - Single Logout Nonsuccess Response status:
urn:oasis:names:tc:SAML:2.0:status:Requester Status Message: Invalid
signature Your Single Logout request did not complete successfully. To
logout out of your Identity Provider and each Service Provider, close
all your browser windows. Partner: XXXX:IDP Target Resource:
http://<domain>/<default SLO endpoint>
My Questions:
What is this error message referring to?
How can I resolve this error condition?
This error is likely due to a mismatch in configuration between IdP and SP. The signing keys/certificate for SAML messages used at one end, must match the verification certificate at the other end. Check your Credentials configuration on your connection for both IdP and SP. See this section in the PingFederate Administration Guide for some details.