Configuring grails spring security ldap plugin - spring

here is a part of my perl cgi script (which is working..):
use Net::LDAP;
use Net::LDAP::Entry;
...
$edn = "DC=xyz,DC=com";
$quser ="(&(objectClass=user)(cn=$username))";
$ad = Net::LDAP->new("ip_address...");
$ldap_msg=$ad->bind("$username\#xyz.com", password=>$password);
my $result = $ad->search( base=>$edn,
scope=>"sub",
filter=>$quser);
my $entry;
my $myname;
my $emailad;
my #entries = $result->entries;
foreach $entry (#entries) {
$myname = $entry->get_value("givenName");
$emailad = $entry->get_value("mail");
}
So basically, there is no admin/manager account for AD, users credentials are used for binding. I need to implement the same thing in grails..
+Is there a way to configure the plugin to search several ADs, I know I can add more ldap IPs in context.server but for each server I need a different search base...
++ I dont wanna use my DB, just AD. User logins through ldap > I get his email, and use the email for another ldap query but that will probably be another topic :)
Anyway the code so far is:
grails.plugin.springsecurity.ldap.context.managerDn = ''
grails.plugin.springsecurity.ldap.context.managerPassword = ''
grails.plugin.springsecurity.ldap.context.server = 'ldap://address:389'
grails.plugin.springsecurity.ldap.authorities.ignorePartialResultException = true
grails.plugin.springsecurity.ldap.search.base = 'DC=xyz,DC=com'
grails.plugin.springsecurity.ldap.authenticator.useBind=true
grails.plugin.springsecurity.ldap.authorities.retrieveDatabaseRoles = false
grails.plugin.springsecurity.ldap.search.filter="sAMAccountName={0}"
grails.plugin.springsecurity.ldap.search.searchSubtree = true
grails.plugin.springsecurity.ldap.auth.hideUserNotFoundExceptions = false
grails.plugin.springsecurity.ldap.search.attributesToReturn =
['mail', 'givenName']
grails.plugin.springsecurity.providerNames=
['ldapAuthProvider',anonymousAuthenticationProvider']
grails.plugin.springsecurity.ldap.useRememberMe = false
grails.plugin.springsecurity.ldap.authorities.retrieveGroupRoles = false
grails.plugin.springsecurity.ldap.authorities.groupSearchBase ='DC=xyz,DC=com'
grails.plugin.springsecurity.ldap.authorities.groupSearchFilter = 'member={0}'
And the error code is: [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
And it's the same code for any user/pass I try :/
Heeeeelp! :)

The most important thing with grails and AD is to use ActiveDirectoryLdapAuthenticationProvider rather than LdapAuthenticationProvider as it will save a world of pain. To do this, just make the following changes:
In resources.groovy:
// Domain 1
ldapAuthProvider1(ActiveDirectoryLdapAuthenticationProvider,
"mydomain.com",
"ldap://mydomain.com/"
)
// Domain 2
ldapAuthProvider2(ActiveDirectoryLdapAuthenticationProvider,
"mydomain2.com",
"ldap://mydomain2.com/"
)
In Config.groovy:
grails.plugin.springsecurity.providerNames = ['ldapAuthProvider1', 'ldapAuthProvider2']
This is all the code you need. You can pretty much remove all other grails.plugin.springsecurity.ldap.* settings in Config.groovy as they don't apply to this AD setup.
Documentation:
http://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html#ldap-active-directory

Related

Google Analytics Reporting v4 with streams instead of views

I've just created a new Google Analytics property and it now defaults to data streams instead of views.
I had some code that was fetching reports through the API that I now need to updated to work with those data streams instead of views since there are not views anymore.
I've looked in the docs but i don't see anything related to data streams, anybody knows how this is done now?
Here's my current code that works with a view ID (I'm using the ruby google-api-client gem):
VIEW_ID = "XXXXXX"
SCOPE = 'https://www.googleapis.com/auth/analytics.readonly'
client = AnalyticsReportingService.new
#server to server auth mechanism using a service account
#creds = ServiceAccountCredentials.make_creds({:json_key_io => File.open('account.json'), :scope => SCOPE})
#creds.sub = "myserviceaccount#example.iam.gserviceaccount.com"
client.authorization = #creds
#metrics
metric_views = Metric.new
metric_views.expression = "ga:pageviews"
metric_unique_views = Metric.new
metric_unique_views.expression = "ga:uniquePageviews"
#dimensions
dimension = Dimension.new
dimension.name = "ga:hostname"
#range
range = DateRange.new
range.start_date = start_date
range.end_date = end_date
#sort
orderby = OrderBy.new
orderby.field_name = "ga:pageviews"
orderby.sort_order = 'DESCENDING'
rr = ReportRequest.new
rr.view_id = VIEW_ID
rr.metrics = [metric_views, metric_unique_views]
rr.dimensions = [dimension]
rr.date_ranges = [range]
rr.order_bys = [orderby]
grr = GetReportsRequest.new
grr.report_requests = [rr]
response = client.batch_get_reports(grr)
I would expect that there would be a stream_id property on the ReportRequest object that I could use instead of the view_id but that's not the case.
Your existing code uses the Google Analytics Reporting api to extract data from a Universal analytics account.
Your new Google analytics property is a Google Analytics GA4 account. To extract data from that you need to use the Google analytics data api These are two completely different systems. You will not be able to just port it.
You can find info on the new api and new library here: Ruby Client for the Google Analytics Data API
$ gem install google-analytics-data
Thanks to Linda's answer i was able to get it working, here's the same code ported to the data API, it might end up being useful to someone:
client = Google::Analytics::Data.analytics_data do |config|
config.credentials = "account.json"
end
metric_views = Google::Analytics::Data::V1beta::Metric.new(name: "screenPageViews")
metric_unique_views = Google::Analytics::Data::V1beta::Metric.new(name: "totalUsers")
dimension = Google::Analytics::Data::V1beta::Dimension.new(name: "hostName")
range = Google::Analytics::Data::V1beta::DateRange.new(start_date: start_date, end_date: end_date)
order_dim = Google::Analytics::Data::V1beta::OrderBy::DimensionOrderBy.new(dimension_name: "screenPageViews")
orderby = Google::Analytics::Data::V1beta::OrderBy.new(desc: true, dimension: order_dim)
request = Google::Analytics::Data::V1beta::RunReportRequest.new(
property: "properties/#{PROPERTY_ID}",
metrics: [metric_views, metric_unique_views],
dimensions: [dimension],
date_ranges: [range],
order_bys: [orderby]
)
response = client.run_report request

Hide password in Genexus beforeConnect procedure

I'm using the BeforeConnect option in Genexus. I put this code in a procedure...
&UserID = &websession.Get("db")
//select the Database depending on websession
Do Case
Case &UserID = "1"
&DataBase = "CambioDB1"
Case &UserID = "2"
&DataBase = "CambioDB2"
Otherwise
&DataBase = "CambioDB1" //default database
EndCase
//Change connection properties
&dbconn = GetDatastore("Default")
&dbconn.UserName = 'username'
&dbconn.UserPassword = 'password'
&dbconn.ConnectionData = "DATABASE=" + &DataBase.Trim() //SQLServer
... set the BeforeConnect property and it works.
But how can I avoid to put the password of the db in the code?
I was thinking to use a file to read from, but it would be an unencrypted password anyway.
How can I solve this? Is there a way to manage this or do I have to risk the password in clear text?
Nicola,
You may use the ConfigurationManager to read a value from the standard config file (client.cfg for Java, web.config for .net).
&MyPassword = ConfigurationManager.GetValue('MY_PASSWORD')
Add a value to your configuration file with the password.
For example:
MY_PASSWORD=my-db-password
You probably want to save the password encrypted for an extra layer of security.
Simple:
&EncPass = Encrypt64(&Password, &SysEncKey)
Stonger encryption:
https://wiki.genexus.com/commwiki/servlet/wiki?42682,Symmetric+Stream+Encryption
&EncPass = &SymmetricStreamCipher.DoEncrypt(symmetricStreamAlgorithm, key, iv, plainText)

Traefik forward auth per frontend

I am trying to divide microservices and their auth.
Demo config is looks like:
[frontends]
[frontends.frontend1]
entryPoints = ["http"]
backend = "rancher1"
passHostHeader = true
forwardAuth = "http://127.0.0.1:8090"
[frontends.frontend1.routes.test_1]
rule = "PathPrefixStrip:/order"
[frontends.rancher2]
backend = "rancher2"
passHostHeader = true
[frontends.rancher2.routes.test_1]
rule = "PathPrefixStrip:/test"
How to apply forwardAuth to frontends.frontend1
Thanks to Daniel he helped me.
So, it's really easy to do:
Check your traefik version its should be at least 1.7 (i am not sure in which version this feature was added but its working in 1.7 and 1.7.1).
Make your config like this:
[frontends.service]
backend = "service"
passHostHeader = true
[frontends.ordersWorker.auth.forward]
address = "http://127.0.0.1:8090"

Dynamic destination in Apache Apollo MQ

Is there a way to authorize destinations with Apache Apollo MQ?
What I would like is to make it so that
1) users may write only to a shared topic but restrict read to an server/admin. This topic is to send messages to a server.
2) Users may read from their own private topic but no one but the server/admin may write to it.
For Example:
Topic User rights Server/Admin rights
/public Write only Read only
/user/foo ONLY the user foo may read Write only
/user/bar ONLY the user bar may read Write only
/user/<username> ONLY the <username> may read Write only
Now for the interesting part. This must work with dynamic topics. The user's name is NOT known ahead of time.
I had this working with Apache ActiveMQ using a custom BrokerFilter but am not sure how to do with with Apollo.
Thanks for any help.
After a lot of head scratching I figured it out.
In apollo.xml:
<broker xmlns="http://activemq.apache.org/schema/activemq/apollo" security_factory="com.me.MyAuthorizationPlugin">
In com.me.MyAuthorizationPlugin:
package com.me
import org.fusesource.hawtdispatch.DispatchQueue.QueueType
import org.apache.activemq.apollo.broker.security._
import org.apache.activemq.apollo.broker.{ Queue, Broker, VirtualHost }
import java.lang.Boolean
class MyAuthorizationPlugin extends SecurityFactory {
def install(broker: Broker) {
DefaultSecurityFactory.install(broker)
}
def install(virtual_host: VirtualHost) {
DefaultSecurityFactory.install(virtual_host)
val default_authorizer = virtual_host.authorizer
virtual_host.authorizer = new Authorizer() {
def can(ctx: SecurityContext, action: String, resource: SecuredResource): Boolean = {
println("Resource: " + resource.id + " User: " + ctx.user)
resource.resource_kind match {
case SecuredResource.TopicKind =>
val id = resource.id
println("Topic Resource: " + id + " User: " + ctx.user)
var result : Boolean = id.startsWith("user." + ctx.user) || id.startsWith("MDN." + ctx.user + ".")
println("Result: " + result)
return result
case _ =>
return default_authorizer.can(ctx, action, resource)
}
}
}
}
}
The following URLs seemed VERY useful and indeed nearly a perfect match:
https://github.com/apache/activemq-apollo/blob/trunk/apollo-stomp/src/test/resources/apollo-stomp-custom-security.xml#L18
https://github.com/apache/activemq-apollo/blob/trunk/apollo-stomp/src/test/scala/org/apache/activemq/apollo/stomp/test/UserOwnershipSecurityFactory.scala#L29
Now I only need to clean up my nasty scala and put it in Git.
I am thinking of doing two tests:
Speed of EXACTLY what I need
A Regex pattern matcher with username / clientID replacements and +/*/?/etc This pattern will be pulled from the config file.
If they are nearly identical I may see about adding it to Apollo by contacting commiters.

SocketStream: Accessing #session outside of /server/app.coffee

I'm just getting started with SocketStream. (v0.1.0) I created the file /app/server/auth.coffee with an exports.actions.login function. I'd like to access #session.setUserId in this file, but I'm have a hard time figuring out where #session lives and how to access it outside of /app/server/app.coffee
Here is my auth.coffee with comments where I'd like to access the session.
users = [
username: 'craig'
password: 'craig',
username: 'joe'
password: 'joe',
]
authenticate = (credentials, cb) ->
user = _.detect users, (user) ->
user.username == credentials.username and user.password == credentials.password
authenticated = true if user?
callback cb, authenticated
exports.actions =
login: (credentials, cb) ->
authenticate credentials, (user) ->
# here is where i'd like to set the userId like so:
# #session.setUserId credentials.username
callback cb user
Interesting you bring a question about sessions up at the moment as I've been re-writing a lot of this code over the last few days as part of SocketStream 0.2.
The good news is the #session variable will be back in 0.2 as I have found an efficient way to pass the session data through to the back end without having to use the ugly #getSession callback.
To answer your question specifically, the #session variable is simply another property which is injected into the export.actions object before the request is processed. Hence you cannot have an action called 'session' (though the name of this 'magic variable' will be configurable in the next release of 0.2).
The exports.authenticate = true setting does not apply in your case.
I'm interested to know how/why you'd like to use the #session object outside of your /app/server code.
I will be committing all the latest session code to the 0.2 preview branch on github in a few days time.
Hope that helps,
Owen
You get the current session only within your server-side code (app/server) using the #getCurrentSession method.
Also you have to add:
exports.authenticate = true
to that file.

Resources