Grails rest spring security plugin does not store generated token using GORM in database - rest

I am using the GORM option to store the generated token in database for my Grails 3.x application using grails spring security rest plugin.
The application generates the token but does not get stored in database. Do we need to override the tokenStorage method and have our own implementation to store the token in database
The plugin properties configured in application.groovy are listed below
grails.plugin.springsecurity.rest.token.validation.useBearerToken = false
grails.plugin.springsecurity.rest.login.endpointUrl = '/api/login'
grails.plugin.springsecurity.rest.token.validation.headerName = 'X-Auth-Token'
grails.plugin.springsecurity.rest.token.storage.useJwt = false
grails.plugin.springsecurity.rest.token.storage.useGorm=true
grails.plugin.springsecurity.rest.token.storage.gorm.tokenDomainClassName='com.auth.AuthenticationToken'
grails.plugin.springsecurity.rest.token.storage.gorm.tokenValuePropertyName='token'
grails.plugin.springsecurity.rest.token.storage.gorm.usernamePropertyName='username'
grails.plugin.springsecurity.rest.login.passwordPropertyName = 'password'
grails.plugin.springsecurity.rest.login.useJsonCredentials = true
grails.plugin.springsecurity.rest.login.useRequestParamsCredentials = false
grails.plugin.springsecurity.rest.token.rendering.authoritiesPropertyName = 'permissions'

Make sure you have added the following to your build.gradle:
compile 'org.grails.plugins:spring-security-rest:2.0.0.M2'
compile 'org.grails.plugins:spring-security-rest-gorm:2.0.0.M2'
And you have defined the following in application.groovy or application.yml
grails.plugin.springsecurity.rest.token.storage.useGorm=true
grails.plugin.springsecurity.rest.token.storage.gorm.tokenDomainClassName = 'com.yourdomain.AuthenticationToken'
grails.plugin.springsecurity.rest.token.storage.gorm.tokenValuePropertyName = 'tokenValue'
grails.plugin.springsecurity.rest.token.storage.gorm.usernamePropertyName = 'username'

There is almost no information to help you. No build configuration, no logs, no idea how the requests are made...
But from the description of your problem, my guess is that you are missing the GORM module in your classpath. It's clearly stated in the documentation.
Be also sure to read the what's new in 2.0 chapter.

I had the same problem, token not stored and no error messages seen.
After installing the GORM plugin:
compile "org.grails.plugins:spring-security-rest-gorm:2.0.0.M2"
I could login and a token was saved into the table.

Related

Apache Meecrowave OAuth2 JPA

I succeedeed in creating my own OAuth2 server using JCache as token store but I'm facing an issue when moving to JPA.
My configuration is :
"--users","test=test",
"--roles","test=test",
"--oauth2-provider","jpa",
"--oauth2-jpa-database-driver","org.h2.Driver",
"--oauth2-jpa-database-url","jdbc:h2:mem:oauth",
"--oauth2-jpa-database-username","sa",
"--oauth2-jpa-database-password",""
But I got exception below during OpenJPA bootstrap :
here was an error while setting up the configuration plugin option "MetaDataFactory".
The plugin was of type "org.apache.openjpa.persistence.jdbc.PersistenceMappingFactory".
Setter methods for the following plugin properties were not available in that type: [
org.apache.cxf.rs.security.oauth2.tokens.bearer.BearerAccessToken,
org.apache.cxf.rs.security.oauth2.common.OAuthPermission,
org.apache.cxf.rs.security.oauth2.tokens.refresh.RefreshToken,
org.apache.cxf.rs.security.oauth2.grants.code.ServerAuthorizationCodeGrant,
org.apache.cxf.rs.security.oauth2.common.UserSubject].
Possible plugin properties are:
[AnnotationParser, ClasspathScan, FieldOverride, Files, JAR_FILE_URLS, MAPPING_FILE_NAMES, MODE_ALL, MODE_ANN_MAPPING, MODE_MAPPING, MODE_MAPPING_INIT, MODE_META, MODE_NONE, MODE_QUERY, PERSISTENCE_UNIT_ROOT_URL, Repository, Resources, STORE_DEFAULT, STORE_PER_CLASS, STORE_VERBOSE, StoreDirectory, StoreMode, Strict, Types, URLs, XMLAnnotationParser, XMLParser].
Ensure that your plugin configuration string uses key values that correspond to setter methods in the plugin class.
I suppose I missed something in configuration...
Any help would be appreciated.
Tx
Using --oauth2-jpa-properties you can set any persistence unit properties you want, I guess you will have to override openjpa.MetaDataFactory default value which is set to jpa(Types=org.apache.cxf.rs.security.oauth2.common.Client,org.apache.cxf.rs.security.oauth2.common.OAuthPermission,org.apache.cxf.rs.security.oauth2.common.UserSubject,org.apache.cxf.rs.security.oauth2.grants.code.ServerAuthorizationCodeGrant,org.apache.cxf.rs.security.oauth2.tokens.bearer.BearerAccessToken,org.apache.cxf.rs.security.oauth2.tokens.refresh.RefreshToken).
You can also check if your configuration is properly propagated and if there is no classpath conflict (another persistence.xml with an oauth2 unit?) because I just retested and your configuration seems to work.
Romain

Authenticate with ECE ElasticSearch Sink from Apache Fink (Scala code)

Compiler error when using example provided in Flink documentation. The Flink documentation provides sample Scala code to set the REST client factory parameters when talking to Elasticsearch, https://ci.apache.org/projects/flink/flink-docs-stable/dev/connectors/elasticsearch.html.
When trying out this code i get a compiler error in IntelliJ which says "Cannot resolve symbol restClientBuilder".
I found the following SO which is EXACTLY my problem except that it is in Java and i am doing this in Scala.
Apache Flink (v1.6.0) authenticate Elasticsearch Sink (v6.4)
I tried copy pasting the solution code provided in the above SO into IntelliJ, the auto-converted code also has compiler errors.
// provide a RestClientFactory for custom configuration on the internally created REST client
// i only show the setMaxRetryTimeoutMillis for illustration purposes, the actual code will use HTTP cutom callback
esSinkBuilder.setRestClientFactory(
restClientBuilder -> {
restClientBuilder.setMaxRetryTimeoutMillis(10)
}
)
Then i tried (auto generated Java to Scala code by IntelliJ)
// provide a RestClientFactory for custom configuration on the internally created REST client// provide a RestClientFactory for custom configuration on the internally created REST client
import org.apache.http.auth.AuthScope
import org.apache.http.auth.UsernamePasswordCredentials
import org.apache.http.client.CredentialsProvider
import org.apache.http.impl.client.BasicCredentialsProvider
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder
import org.elasticsearch.client.RestClientBuilder
// provide a RestClientFactory for custom configuration on the internally created REST client// provide a RestClientFactory for custom configuration on the internally created REST client
esSinkBuilder.setRestClientFactory((restClientBuilder) => {
def foo(restClientBuilder) = restClientBuilder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
override def customizeHttpClient(httpClientBuilder: HttpAsyncClientBuilder): HttpAsyncClientBuilder = { // elasticsearch username and password
val credentialsProvider = new BasicCredentialsProvider
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(es_user, es_password))
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)
}
})
foo(restClientBuilder)
})
The original code snippet produces the error "cannot resolve RestClientFactory" and then Java to Scala shows several other errors.
So basically i need to find a Scala version of the solution described in Apache Flink (v1.6.0) authenticate Elasticsearch Sink (v6.4)
Update 1: I was able to make some progress with some help from IntelliJ. The following code compiles and runs but there is another problem.
esSinkBuilder.setRestClientFactory(
new RestClientFactory {
override def configureRestClientBuilder(restClientBuilder: RestClientBuilder): Unit = {
restClientBuilder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
override def customizeHttpClient(httpClientBuilder: HttpAsyncClientBuilder): HttpAsyncClientBuilder = {
// elasticsearch username and password
val credentialsProvider = new BasicCredentialsProvider
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(es_user, es_password))
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)
httpClientBuilder.setSSLContext(trustfulSslContext)
}
})
}
}
The problem is that i am not sure if i should be doing a new of the RestClientFactory object. What happens is that the application connects to the elasticsearch cluster but then discovers that the SSL CERT is not valid, so i had to put the trustfullSslContext (as described here https://gist.github.com/iRevive/4a3c7cb96374da5da80d4538f3da17cb), this got me past the SSL issue but now the ES REST Client does a ping test and the ping fails, it throws an exception and the app shutsdown. I am suspecting that the ping fails because of the SSL error and maybe it is not using the trustfulSslContext i setup as part of new RestClientFactory and this makes me suspect that i should not have done the new, there should be a simple way to update the existing RestclientFactory object and basically this is all happening because of my lack of Scala knowledge.
Happy to report that this is resolved. The code i posted in Update 1 is correct. The ping to ECE was not working for two reasons:
The certificate needs to include the complete chain including the root CA, the intermediate CA and the cert for the ECE. This helped get rid of the whole trustfulSslContext stuff.
The ECE was sitting behind an ha-proxy and the proxy did the mapping for the hostname in the HTTP request to the actual deployment cluster name in ECE. this mapping logic did not take into account that the Java REST High Level client uses the org.apache.httphost class which creates the hostname as hostname:port_number even when the port number is 443. Since it did not find the mapping because of the 443 therefore the ECE returned a 404 error instead of 200 ok (only way to find this was to look at unencrypted packets at the ha-proxy). Once the mapping logic in ha-proxy was fixed, the mapping was found and the pings are now successfull.

Apache Spark: I always got org.apache.axis.AxisFault: (404)Not Found when using google-spark-adwords

I'm still a newbie in Apache Spark dev.
I'm using apache spark to query data from google ads words using spark-google-adwords. But, I always got this org.apache.axis.AxisFault: (404)Not Found
I'm using Scala 2.11 and latest stable Apache Spark. I've tried to look for the solution for this problem, but I still couldn't find out the cause.
Regards,
This issue was resolved by adding a copy of axis2.xml to classpath and overriding few connection manager params as follows:
HttpConnectionManagerParams params = new HttpConnectionManagerParams();
params.setDefaultMaxConnectionsPerHost(20); //SET VALUE BASED ON YOUR REQUIREMENTS/LOAD TESTING etc
MultiThreadedHttpConnectionManager multiThreadedHttpConnectionManager = new MultiThreadedHttpConnectionManager();
multiThreadedHttpConnectionManager.setParams(params);
HttpClient httpClient = new HttpClient(multiThreadedHttpConnectionManager);
ConfigurationContext configurationContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem("**PATH TO COPY OF AXIS2.XML**");
configurationContext.setProperty(HTTPConstants.CACHED_HTTP_CLIENT, httpClient);
credit : https://issues.apache.org/jira/browse/AXIS2-4807

Liberty LTPA SSO configuration failing with com.ibm.ws.security.registry.EntryNotFoundException

I am building the SSO between IBM ISAM & LIberty profile using LTPA token, The ISAM is configured with LDAP authentication and i have added same LDAP users into liberty server.xml basic registry. Now after the ISAM authentication i am not able to see the my liberty and i see the below error in the liberty log.
stack trace Stack Dump = com.ibm.ws.security.registry.EntryNotFoundException: cn=f4a3e7df53e9caf8dfd3,o=xxx,c=us,dc=xxx,dc=com does not exist at com.ibm.ws.security.registry.basic.internal.BasicRegistry.getUserSecurityName(BasicRegistry.java:506) at com.ibm.ws.security.authentication.jaas.modules.TokenLoginModule.setUpTemporaryUserSubject(TokenLoginModule.java:130) at com.ibm.ws.security.authentication.jaas.modules.TokenLoginModule.login(TokenLoginModule.java:76) at com.ibm.ws.kernel.boot.security.LoginModuleProxy.login(LoginModuleProxy.java:53) at
Configuration Details
In the liberty ltpa.keys the realm is "com.ibm.websphere.ltpa.Realm=BasicRealm" and this what used in the above junction.
In server.xml
basicRegistry id="basic" realm="BasicRealm"
user name="loginID=user#mail.com,cn=f4a3e7df53e9caf8dfd3,o=xxx,c=xx,dc=xxx,dc=com" password="qazwsx1234"
group name="LDAPgroupUsers"
member name="loginID=user#mail.com,cn=f4a3e7df53e9caf8dfd3,o=xxx,c=xx,dc=xxx,dc=com"
group
basicRegistry
webApplication contextRoot="my-demo" id="MyDemo" location="MyDemo.war" name="MyDemo"
application-bnd
security-role name="LDAPUsersRole"
group name="LDAPgroupUsers"
security-role
application-bnd
webApplication
I feel the ltpa2token passed to liberty and i can see it from the below log, So it must some issue the way i configured the user patterns in basicRegistry mentioned in server.xml .... Any clue?
Object type = com.ibm.ws.security.authentication.jaas.modules.TokenLoginModule
tc = class com.ibm.websphere.ras.TraceComponent#8f59a5c2
strings[0] = "TraceComponent[com.ibm.ws.security.authentication.jaas.modules.TokenLoginModule,class com.ibm.ws.security.authentication.jaas.modules.TokenLoginModule,[Authentication],com.ibm.ws.security.authentication.internal.resources.AuthenticationMessages,null]"
accessId = "user:BasicRealm/cn=f4a3e7df53e9caf8dfd3,o=xxx,c=us,dc=xxx,dc=com"
recreatedToken = class com.ibm.ws.security.token.ltpa.internal.LTPAToken2#255023a9
tc = class com.ibm.websphere.ras.TraceComponent#cb94b8a1
I have queried the user in LDAP and added the same pattern (name="cn=f4a3e7df53e9caf8dfd3,o=xxx,c=xx,dc=xxx,dc=com) as in server.xml
then it worked.
Thanks Tamboli.

python social auth load strategy and authenticate user manually with release 0.1.26

I used python social auth for social authentication in the last 2 months and it was great.
I needed QQ support, hence installed newest git commit (23e4e289ec426732324af106c7c2e24efea34aeb - not part of a release).
until now i used to authenticate the user using the following code:
# setup redirect uri in order to load strategy
uri = redirect_uri = "social:complete"
if uri and not uri.startswith('/'):
uri = reverse(redirect_uri, args=(backend,))
# load the strategy
try:
strategy = load_strategy(
request=request, backend=backend,
redirect_uri=uri, **kwargs
)
strategy = load_strategy(request=bundle.request)
except MissingBackend:
raise ImmediateHttpResponse(HttpNotFound('Backend not found'))
# get the backend for the strategy
backend = strategy.backend
# check backend type and set token accordingly
if isinstance(backend, BaseOAuth1):
token = {
'oauth_token': bundle.data.get('access_token'),
'oauth_token_secret': bundle.data.get('access_token_secret'),
}
elif isinstance(backend, BaseOAuth2):
token = bundle.data.get('access_token')
else:
raise ImmediateHttpResponse(HttpBadRequest('Wrong backend type'))
# authenticate the user
user = strategy.backend.do_auth(token)
which worked fine.
In the latest release this behaviour has changed, and an exception is raised since the "load_strategy" method has changed.
I can't seem to find any documentation on how to do it with the new release.
Any help would be appreciated!
Omri.
The last changes in the repository changed the importance of the strategy, instead of being the main entity to perform the authentication, it's just a helper class to glue the framework with the backends. Try with this snippet to load the strategy and the backend:
from social.apps.django_app.utils import load_strategy, load_backend
strategy = load_strategy(request)
backend = load_backend(strategy, backend, uri)
...
user = backend.do_auth(token)