I am new with active directory and spring security, in fact, I want to change my spring security configuration so that use active directory in authentififcation so I use this in my SecurityConfig:
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(activeDirectoryLdapAuthenticationProvider());
auth.eraseCredentials(false);
}
#Bean
public AuthenticationProvider activeDirectoryLdapAuthenticationProvider() {
ActiveDirectoryLdapAuthenticationProvider authenticationProvider = new ActiveDirectoryLdapAuthenticationProvider(
"dc=example,dc=com", "ldap://localhost:10389/dc=example,dc=com");
authenticationProvider.setConvertSubErrorCodesToExceptions(true);
authenticationProvider.setUseAuthenticationRequestCredentials(true);
authenticationProvider.setUserDetailsContextMapper(mapper);
return authenticationProvider;
}
and active directory studio I have a partition: dc=example,dc=com which contains an entry ou=people.
When I try to put a username and password I have this error:
javax.naming.InvalidNameException: [LDAP: error code 34 - Incorrect DN given : admin#dc=example,dc=com (0x73 0x79 0x73 0x61 0x64 0x6D 0x69 0x6E 0x40 0x64 0x63 0x3D 0x70 0x75 0x70 0x70 0x75 0x74 0x2C 0x64 0x63 0x3D 0x63 0x6F 0x6D ) is invalid]
at com.sun.jndi.ldap.LdapCtx.processReturnCode(LdapCtx.java:3076)
at com.sun.jndi.ldap.LdapCtx.processReturnCode(LdapCtx.java:2883)
at com.sun.jndi.ldap.LdapCtx.connect(LdapCtx.java:2797)..
Have you any idea please?
ActiveDirectoryLdapAuthenticationProvider is intended to let you authenticate with usernames in the AD-specific form user#example.com, which are not standard LDAP DN format. As such, the first argument in the constructor should be the domain (example.com) not an LDAP DN. When you log in as admin, the code uses the configured domain to build the string admin#example.com and passes that to AD.
Since you are using dc=example,dc=com as the domain name, you end up with admin#dc=example,dc=com which is invalid.
Related
I have a trouble with configuring LDAP authentication with Spring.
Using LDAP Apache Directory Studio I have following working connection to LDAP Server:
Bind DN or USER: cn=HIDDEN_USERNAME,OU=HIDDEN_OU1,OU=HIDDEN2,OU=Admin,DC=MY_COMPANYNAME,DC=COM
Authorization ID: SASL PLAIN only
Bind Password: ******
Using this connection, I can find my account under root:
Root DSE/DC=MY_COMPANYNAME,DC=COM/OU=User Accounts/OU=Enabled Users/OU=Consultants/CN=MySurname My Name
Right click on my account gives following values:
DN: CN=MySurname MyName,OU=Consultants,OU=Enabled Users,OU=User Accounts,DC=MY_COMPANYNAME,DC=COM
URL: ldap://IP_ADRESS:389/CN=MySurname%20MyName,OU=Consultants,OU=Enabled%20Users,OU=User%20Accounts,DC=MY_COMPANYNAME,DC=COM
I am going to configure WebSecurityConfigurerAdapter in order to get authentication via ldap server in the following way:
#Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.ldapAuthentication()
.userDnPatterns("CN={0},OU=Consultants,OU=Enabled Users,OU=User Accounts,DC=MY_COMPANYNAME,DC=COM")
.contextSource()
.url("ldap://IP_ADRESS:389/")
.managerDn("HIDDEN_USERNAME")
.managerPassword("*****")
.and()
.passwordCompare()
.passwordEncoder(new LdapShaPasswordEncoder())
.passwordAttribute("userPassword");
}
I tried to set userDnPattern in many ways without result. What I am doing wrong?
Using the DN pattern you specify, your logon attempt would need to be made with user ID "MySurname MyName" (and the space may be an issue). The user provided logon ID string is inserted into the DN pattern you include above, and you'll be binding with
CN=MySurname MyName,OU=Consultants,OU=Enabled Users,OU=User Accounts,DC=MY_COMPANYNAME,DC=COM
Which matches what your fully qualified DN appears to be. If you want to be able to log on with your ID and not the surname/name string that makes up your CN, or if accounts which need to authenticate exist in multiple OU locations, userSearch may be preferable to DN patterns.
If you are authenticating against an Active Directory domain, you may be able to use {0}#domain.gTLD or DOMAIN{0} as the user pattern -- when a logon ID is supplied, these patterns form the userPrincipalName and sAMAccountName respectively.
In response to your comment above: Active Directory hides the password field and it cannot be read even by domain administrators.
I concur with the other user that for AD you need to use a user search filter and if you want to do it against the username you should use samaccountname={0}
I am using Spring Security(basic authentication) + LDAP authentication which works well with embedded test ldif but not with my domain LDAP. However, I can use a LDAP browser/edit tool to search my account using the same filter(SamAccountName=napo)
#Override
public void addServiceAuthenticationManager(AuthenticationManagerBuilder authBuilder) throws Exception {
authBuilder
.ldapAuthentication()
.ldapAuthoritiesPopulator(ldapAppAuthoritiesPopulator())
.userSearchBase("OU=Users,DC=napo,DC=com")
.userSearchFilter("(SamAccountName={0})")
.contextSource()
.root("dc=napo,dc=com")
.managerDn("admin#napo.com")
.managerPassword("XXX")
.url("ldap://ldap.napo.com/OU=Users,dc=napo,dc=com");
The error message is: LDAP: error code 32 - 0000208D: NameErr: DSID-0310020A, problem 2001 (NO_OBJECT)
The userSearchBase is relative to root. Remove DC=napo,DC=com from userSearchBase.
I am trying to integrate LDAP authentication for my Spring MVC app. The users are successfully able to log in, if I set the contextSource to a dummy user DN and respective password.
What I want to do is to be able to bind the ldap connection without using the dummy user.
Here's the code of what works -
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/css/**").permitAll()
.antMatchers("/","/login**").permitAll()
.antMatchers("/home_vm","/details/**").authenticated()
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.defaultSuccessUrl("/home_vm", true)
.and()
.logout()
.permitAll();
http.headers().httpStrictTransportSecurity();
}
#Configuration
#Profile({"default", "opt_ad_auth"})
protected static class ActiveDirectoryAuthenticationConfiguration extends
GlobalAuthenticationConfigurerAdapter {
#Value("${app.ldap.url}")
private String ldapURL;
#Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
DefaultSpringSecurityContextSource contextSource = new DefaultSpringSecurityContextSource(ldapURL);
contextSource.setUserDn("cn=Dummy User,cn=Users,dc=somecompany,dc=com");
contextSource.setPassword("mypassword");
contextSource.setReferral("follow");
contextSource.afterPropertiesSet();
auth.ldapAuthentication()
.userSearchFilter("(sAMAccountName={0})")
.contextSource(contextSource)
;
}
}
}
Now I have tried to remove the hardcoded userDn and password (updated init())-
public void init(AuthenticationManagerBuilder auth) throws Exception {
auth.ldapAuthentication()
.userSearchFilter("(sAMAccountName={0})")
.contextSource()
.url(ldapURL)
;
}
}
The app starts fine, but I get exception - "a successful bind must be completed on the connection".
Stacktrace -
org.springframework.security.authentication.InternalAuthenticationServiceException: Uncategorized exception occured during LDAP processing; nested exception is javax.naming.NamingException: [LDAP: error code 1 - 000004DC: LdapErr: DSID-0C0906E8, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, v1db1
[UPDATE] I have modified the init method to the following to more closely follow the spring tutorial(https://spring.io/guides/gs/authenticating-ldap/) -
public void init(AuthenticationManagerBuilder auth) throws Exception {
auth.ldapAuthentication()
.userDnPatterns("sAMAccountName={0}")
.contextSource().url(ldapURL)
;
}
I don't get the before-mentioned bind exception, but still not able to authenticate. Bad credentials.
You need to do this in two steps:
Bind to LDAP as an administrative user that has enough privileges to search the tree and find the user via whatever unique information you have about him.
Rebind to LDAP as the found user's DN using the supplied password.
Disconnect.
If all that succeeds, the username existed and the password was correct. If there was any failure you should treat it as a loging failure. Specifically, you should not tell the user whether it was the username not being found or the password being incorrect that was the reason for the failure: this is an information leak to an attacer.
You can authenticate with LDAP in 2 forms:
You can make a bind with the complete DN of the user (full path in the LDAP tree) and the password.
Or you can bind to LDAP as a superuser that can search on all the LDAP tree. The LDAP authenticator finds the user DN and compare the user password with the password in the user entry.
In your first code you use the second system. You need a user that can bind on the LDAP and find the user entry.
If you want user the second system, you must supply the complete DN of the user entry not the uid only.
From Pro Spring Security book by Carlo Scarioni, I'm trying to integrate Spring Application with CAS Server. I followed every step that the book instructed, still I'm stuck with this error. Please help me out.
SEVERE: sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathValidatorException: signature check failed
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathValidatorException: signature check failed
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1904)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:279)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:273)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1446)
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:209)
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:901)
at sun.security.ssl.Handshaker.process_record(Handshaker.java:837)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1023)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1332)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1359)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1343)
at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:563)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1301)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
at org.jasig.cas.client.util.CommonUtils.getResponseFromServer(CommonUtils.java:311)
at org.jasig.cas.client.util.CommonUtils.getResponseFromServer(CommonUtils.java:291)
at org.jasig.cas.client.validation.AbstractCasProtocolUrlBasedTicketValidator.retrieveResponseFromServer(AbstractCasProtocolUrlBasedTicketValidator.java:32)
at org.jasig.cas.client.validation.AbstractUrlBasedTicketValidator.validate(AbstractUrlBasedTicketValidator.java:187)
at org.springframework.security.cas.authentication.CasAuthenticationProvider.authenticateNow(CasAuthenticationProvider.java:140)
at org.springframework.security.cas.authentication.CasAuthenticationProvider.authenticate(CasAuthenticationProvider.java:126)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:156)
at org.springframework.security.cas.web.CasAuthenticationFilter.attemptAuthentication(CasAuthenticationFilter.java:242)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:195)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1336)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:483)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:119)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:524)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:233)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1065)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:412)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:192)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:999)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:117)
at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:250)
at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:149)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:111)
at org.eclipse.jetty.server.Server.handle(Server.java:351)
at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:454)
at org.eclipse.jetty.server.BlockingHttpConnection.handleRequest(BlockingHttpConnection.java:47)
at org.eclipse.jetty.server.AbstractHttpConnection.headerComplete(AbstractHttpConnection.java:890)
at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandler.headerComplete(AbstractHttpConnection.java:944)
at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:634)
at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:230)
at org.eclipse.jetty.server.BlockingHttpConnection.handle(BlockingHttpConnection.java:66)
at org.eclipse.jetty.server.bio.SocketConnector$ConnectorEndPoint.run(SocketConnector.java:254)
at org.eclipse.jetty.server.ssl.SslSocketConnector$SslConnectorEndPoint.run(SslSocketConnector.java:665)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:599)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:534)
at java.lang.Thread.run(Thread.java:745)
Caused by: sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathValidatorException: signature check failed
at sun.security.validator.PKIXValidator.doValidate(PKIXValidator.java:350)
at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:260)
at sun.security.validator.Validator.validate(Validator.java:260)
at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:326)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:231)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:126)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1428)
... 55 more
Caused by: java.security.cert.CertPathValidatorException: signature check failed
at sun.security.provider.certpath.PKIXMasterCertPathValidator.validate(PKIXMasterCertPathValidator.java:159)
at sun.security.provider.certpath.PKIXCertPathValidator.doValidate(PKIXCertPathValidator.java:347)
at sun.security.provider.certpath.PKIXCertPathValidator.engineValidate(PKIXCertPathValidator.java:191)
at java.security.cert.CertPathValidator.validate(CertPathValidator.java:279)
at sun.security.validator.PKIXValidator.doValidate(PKIXValidator.java:345)
... 61 more
Caused by: java.security.SignatureException: Signature does not match.
at sun.security.x509.X509CertImpl.verify(X509CertImpl.java:451)
at sun.security.provider.certpath.BasicChecker.verifySignature(BasicChecker.java:160)
at sun.security.provider.certpath.BasicChecker.check(BasicChecker.java:139)
at sun.security.provider.certpath.PKIXMasterCertPathValidator.validate(PKIXMasterCertPathValidator.java:133)
... 65 more
2015-08-29 02:46:50.472:WARN:oejs.ServletHandler:/j_spring_cas_security_check
java.lang.RuntimeException: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathValidatorException: signature check failed
at org.jasig.cas.client.util.CommonUtils.getResponseFromServer(CommonUtils.java:328)
at org.jasig.cas.client.util.CommonUtils.getResponseFromServer(CommonUtils.java:291)
at org.jasig.cas.client.validation.AbstractCasProtocolUrlBasedTicketValidator.retrieveResponseFromServer(AbstractCasProtocolUrlBasedTicketValidator.java:32)
at org.jasig.cas.client.validation.AbstractUrlBasedTicketValidator.validate(AbstractUrlBasedTicketValidator.java:187)
at org.springframework.security.cas.authentication.CasAuthenticationProvider.authenticateNow(CasAuthenticationProvider.java:140)
at org.springframework.security.cas.authentication.CasAuthenticationProvider.authenticate(CasAuthenticationProvider.java:126)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:156)
at org.springframework.security.cas.web.CasAuthenticationFilter.attemptAuthentication(CasAuthenticationFilter.java:242)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:195)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1336)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:483)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:119)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:524)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:233)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1065)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:412)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:192)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:999)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:117)
at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:250)
at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:149)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:111)
at org.eclipse.jetty.server.Server.handle(Server.java:351)
at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:454)
at org.eclipse.jetty.server.BlockingHttpConnection.handleRequest(BlockingHttpConnection.java:47)
at org.eclipse.jetty.server.AbstractHttpConnection.headerComplete(AbstractHttpConnection.java:890)
at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandler.headerComplete(AbstractHttpConnection.java:944)
at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:634)
at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:230)
at org.eclipse.jetty.server.BlockingHttpConnection.handle(BlockingHttpConnection.java:66)
at org.eclipse.jetty.server.bio.SocketConnector$ConnectorEndPoint.run(SocketConnector.java:254)
at org.eclipse.jetty.server.ssl.SslSocketConnector$SslConnectorEndPoint.run(SslSocketConnector.java:665)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:599)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:534)
at java.lang.Thread.run(Thread.java:745)
The SSL handshake exception will occur if cas server to cas client (jar files will behave as client) communication is not happened, First check the network things like communication between both servers, firewall and port blocking, if every thing is good then this problem is because of SSL certificate, make sure to use the same certificate in both CAS server and client(Spring security app) applications.
As i can't comment yet, i'll just extend to #Kamal's answer. I was learning through the same book, but i was using Tomcat as a difference, so i can't really give you the same answer as i've never used Jetty:
As he said, your SSL is not working as it should. The certificate is not being accepted by your browser and/or server, so it can't authenticate, and thus, SSL handshake gets rejected. You need to be sure that you've added the certificate CAS.crt to your JVM cacerts, as he explains on the book(198-199), and check if it's correctly there . And then you need to add the jetty-ssl.keystore to Jetty, with the password that you used, so that it can used to make the right connection. Also, you need to be positively sure that it's written localhost as the cn name, as it won't work otherwise. This would change depending on your enviroment(production, testing, just learning...), but this is the necessary for making it work as the book described.
Hope that i'm not too off here, but i hope it helped.
I have faced this issue and found that SSL certificate was expired.
After replacing expired SSL certificate by latest certificate the issue was resolved.
I am using Spring 2.2.5 now with Java 11
Try to add into the Spring Application context the RestTemplate bean, in order to accept all the certificates, just like this:
#Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) throws NoSuchAlgorithmException, KeyManagementException {
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
}
};
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
CloseableHttpClient httpClient = HttpClients.custom()
.setSSLContext(sslContext)
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.build();
HttpComponentsClientHttpRequestFactory customRequestFactory = new HttpComponentsClientHttpRequestFactory();
customRequestFactory.setHttpClient(httpClient);
return builder.requestFactory(() -> customRequestFactory).build();
}
Then, in your client class with the server communication, you have to add the bean RestTemplate restTemplate and pass it in the constructor.
Then, in a method, you have to write the remote rest end point invocation like this:
private YourSpecificResponseJSONClass getYourRemoteResponse() {
YourSpecificResponseJSONClass ret = getYourDefaultJSONResponseInCaseOfAnyException();
try {
ret = restTemplate.getForObject("<yourRemoteURL>", YourSpecificResponseJSONClass.class);
} catch (Throwable t) {
//log whatever
}
return ret;
}
Check your system date. It worked for me when I corrected it. This usually comes in SLES distros.
Below solution is working fine for me.
SslContext sslContext = SslContextBuilder
.forClient()
.trustManager(InsecureTrustManagerFactory.INSTANCE)
.build();
HttpClient httpClient = HttpClient.create().secure(t ->
t.sslContext(sslContext) );
WebClient webClient = WebClient.builder()
.baseUrl("any-url")
.clientConnector(new ReactorClientHttpConnector(httpClient))
.build();
Normally is accompained by this error as first entry "NotAfter: Sun Sep 25 02:51:03 PDT 2022" indicating cert not valid anymore
I'm trying to use the Social Business Toolkit to access SmartCloud using OAuth, but I'm getting this error. Using SmartCloudBasicEndpoint everything works fine.
[4/4/14 12:01:56:236 CEST] 00000038 SBTProxy I URL computed from SBTProxy is https://apps.na.collabserv.com/communities/service/atom/oauth/communities/all
[4/4/14 12:01:56:556 CEST] 00000038 E com.ibm.sbt.security.authentication.oauth.consumer.OAuth1Handler _performOAuth1Dance Failed to get request token. requestUrl:https://apps.na.collabserv.com/manage/oauth/getRequestToken, authorizeUrl: https://apps.na.collabserv.com/manage/oauth/authorizeToken, accessUrl: https://apps.na.collabserv.com/manage/oauth/getAccessToken, callback: null, truncated key:a919....1b25, truncated secret:9054....687d. OAuth callback is empty, please check with your application vendor to ensure a callback is not required.
com.ibm.sbt.security.authentication.oauth.OAuthException: Internal error - getRequestToken failed Exception: <br>
at com.ibm.sbt.security.authentication.oauth.consumer.OAuth1Handler.getRequestTokenFromServer(OAuth1Handler.java:169)
at com.ibm.sbt.security.authentication.oauth.consumer.OAuth1Handler._performOAuth1Dance(OAuth1Handler.java:656)
at com.ibm.sbt.security.authentication.oauth.consumer.OAuth1Handler.performOAuth1Dance(OAuth1Handler.java:649)
at com.ibm.sbt.security.authentication.oauth.consumer.OAuth1Handler._acquireToken(OAuth1Handler.java:625)
at com.ibm.sbt.security.authentication.oauth.consumer.OAuth1Handler.acquireToken(OAuth1Handler.java:580)
at com.ibm.sbt.services.endpoints.OAuthEndpoint.authenticate(OAuthEndpoint.java:234)
at com.ibm.sbt.services.client.ClientService.forceAuthentication(ClientService.java:281)
at com.ibm.sbt.services.client.ClientService.processResponse(ClientService.java:1123)
at com.ibm.sbt.services.client.ClientService._xhr(ClientService.java:1041)
at com.ibm.sbt.services.client.ClientService.execRequest(ClientService.java:1006)
at com.ibm.sbt.services.client.ClientService.xhr(ClientService.java:966)
at com.ibm.sbt.services.client.ClientService.get(ClientService.java:842)
at com.ibm.sbt.services.client.ClientService.get(ClientService.java:838)
at com.ibm.sbt.services.client.base.BaseService.retrieveData(BaseService.java:352)
at com.ibm.sbt.services.client.base.BaseService.retrieveData(BaseService.java:376)
at com.ibm.sbt.services.client.base.BaseService.retrieveData(BaseService.java:327)
at com.ibm.sbt.services.client.base.BaseService.getEntities(BaseService.java:187)
at com.ibm.sbt.services.client.connections.communities.CommunityService.getPublicCommunities(CommunityService.java:164)
at com.ibm.sbt.services.client.connections.communities.CommunityService.getPublicCommunities(CommunityService.java:146)
at servlets.SmartCloudTestServlet.doGet(SmartCloudTestServlet.java:82)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:575)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1224)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:774)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:456)
at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
at com.ibm.ws.webcontainer.filter.WebAppFilterChain.invokeTarget(WebAppFilterChain.java:136)
at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:97)
at com.ibm.sbt.util.SBTFilter.doFilter(SBTFilter.java:53)
at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:195)
at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:91)
at com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:928)
at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1025)
at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3751)
at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:304)
at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:962)
at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1662)
at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:195)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:452)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:511)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:305)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.ready(HttpInboundLink.java:276)
at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.sendToDiscriminators(NewConnectionInitialReadCallback.java:214)
at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.complete(NewConnectionInitialReadCallback.java:113)
at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:165)
at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1690)
Caused by: java.lang.NullPointerException
at java.net.URLEncoder.encode(URLEncoder.java:197)
at com.ibm.sbt.security.authentication.oauth.consumer.OAuth1Handler.getRequestTokenFromServer(OAuth1Handler.java:156)
... 51 more
[4/4/14 12:01:56:560 CEST] 00000038 SystemOut O Problem Occurred while fetching public communities: Problem occurred while fetching public communities
Here's what I've done so far:
Create a new Servlet application.
I'm using RuntimeFactoryStandalone.
Added managed-beans.xml and sbt.properties (both from samples app) to /WEB-INF/.
I'm running the application on WebSphere Application Server. (I also tried the same code in a Portlet on WebSphere Portal)
Added the SmartCloud key, secret and appId to the properties file.
I'm using this code:
try {
CommunityService svc = new CommunityService("smartcloud");
CommunityList communities = svc.getPublicCommunities();
System.out.println("Listing public communities , Total communities found : " + communities.getTotalResults());
} catch (Throwable e) {
System.out.println("Problem Occurred while fetching public communities: " + e.getMessage());
//e.printStackTrace();
}
I'm getting the same error if I manually use a SmartCloudOAuthEndpoint.
Am I forgetting something here?
Update:
My manual endpoint:
SmartCloudOAuthEndpoint endpoint = new SmartCloudOAuthEndpoint();
endpoint.setUrl("https://apps.na.collabserv.com");
endpoint.setConsumerKey("a91..----REMOVED FOR STACKOVERFLOW----..");
endpoint.setConsumerSecret("905..----REMOVED FOR STACKOVERFLOW----..");
endpoint.setRequestTokenURL("https://apps.na.collabserv.com/manage/oauth/getRequestToken");
endpoint.setAuthorizationURL("https://apps.na.collabserv.com/manage/oauth/authorizeToken");
endpoint.setAccessTokenURL("https://apps.na.collabserv.com/manage/oauth/getAccessToken");
endpoint.setAppId("RonnieTest");
endpoint.setApiVersion("apiVersion");
//endpoint.setHttpProxy("localhost:8888");
endpoint.setForceTrustSSLCertificate(true);
endpoint.setSignatureMethod("PLAINTEXT");
endpoint.setCredentialStore("SmartCloudStore");
endpoint.setAuthenticationService("communities/service/atom/communities/my");
I'm using this Internal App in SmartCloud:
I solved it. I wasn't passing ServletRequest and ServletResponse to my Context. Turns out that getCallbackUrl(Context context) in OAuthHandler is the first method that actually needs the request to build the callback URL.