Using grails spring security to secure URLs with http method - grails

I'm using spring security 1.2.7.3, and I want to secure URLs with http method, in other words I want something like this in my config.groovy:
grails.plugins.springsecurity.interceptUrlMap = [
'/api/person/**': ['ROLE_ADMIN'], //IF HTTP "POST"
'/api/person/**': ['IS_AUTHENTICATED_ANONYMOUSLY'], //IF HTTP "GET"
}
Is it possible? I know that there are of course other ways to achieve this but I prefer to solve the problem in this way.
p.s. this question has already been asked here before.

I tested out the following and it seemed to work quite well:
grails.plugin.springsecurity.securityConfigType = SecurityConfigType.InterceptUrlMap
grails.plugin.springsecurity.interceptUrlMap = [
'/myFirst/**': ["request.getMethod().equals('GET') || hasRole('ROLE_ADMIN')"],
'/mySecond/**': ["permitAll"]
]
I based the usage of request.getMethod() on the documentation found at the link below and took a little liberty in using an || expression.
http://grails-plugins.github.io/grails-spring-security-core/guide/requestMappings.html
In your example you supplied two entries for 'api/person/**', but that unfortunately won't work because each entry would have the same key for the interceptUrlMap. Combine what you want for options with || and &&.

Related

telegraf http input plugin

I am trying to create a proof on concept using the TICK stack for monitoring. I have the helloworld stack running and showing CPU/Docker metrics.
I am trying to use the telegraf http input plugin to pull from an http endpoint:
From the docs i have simply configured the URL, GET and type (Set to json)
[[inputs.http]]
## One or more URLs from which to read formatted metrics
urls = [
"http://localhost:500/Queues"
]
method = "GET"
data_format = "json"
However nothing appears in Influx/Chronograf.
I can modify the endpoint to suit any changes there, but what am i doing wrong in telegraf config ?
I think I had the same struggle. For me the following conf worked:
[[inputs.http]]
name_override ="restservice_health"
urls = [
"https://localhost:5001/health"
]
method = "GET"
data_format = "value"
data_type = "string"
In this way, it appeared in Influxdb under the name "restservice_health" (allthough this option is not important for the example, so you could leave it out).
First, you would have to look at the result of the http://localhost:500/Queues request to make sure that it's a valid JSON object.
Then, depending on what is returned from that endpoint, you may have to configure the JSON parser, for example by setting json_query to a GJSON query to navigate the JSON response to the data you need.

Mailgun, Groovy HTTPBuilder and problems with HTTP Basic authentication

Looks like HTTPBuilder's behavior goes wrong when the server / api endpoint does not give a proper response. Mailgun's API does not respond 401, but instead gives something else. (Correct me if I'm wrong!)
The fact that there are no "Authentication required" headers sent, HTTPBuilder will not even try to authenticate.
I think I got the problem solved by the help of this thread: http://groovy.329449.n5.nabble.com/HTTPBuilder-Strange-behaviour-of-auth-basic-td344479.html
They suggest, that writing the authentication header manually will force the authentication each time. Needed to modify that a bit so it looks like this:
def user = 'tom'
def pass = 'secret'
def http = new HTTPBuilder('http://myhost.com')
http.headers[ 'Authorization' ] = "Basic " + "$user:$pass".getBytes('iso-8859-1').encodeBase64()
Seems to work now. Any better ideas? This looks like and perhaps is a hack.
Try to use something like:
def authSite = new HTTPBuilder( 'https://some-protected-site.com/' )
authSite.auth.basic 'myUserName', 'myPassword'
Read more at: http://groovy.codehaus.org/modules/http-builder/doc/auth.html

How to get the page origin in razor?

I'm looking for the equivalent of this javascript
window.location.origin
but server side, while building mvc pages.
For example, if you are here
http://website.com/123,
it would return
http://website.com
Its important that i have the "http://" part
I'm a fan of
string url = Request.Url.PathAndQuery.length > 1
? Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery, string.Empty)
: url;
Keeps your Http/Https, Port (if applicable), and HostName/IP.
DotNetFiddle Examples
Updated to Account for PathAndQuery length of 1.
you could try
#String.Format("{0}://{1}", Request.Url.Scheme, Request.Url.Authority)
Or
#String.Format("{0}://{1}", Request.Url.Scheme, Request.Url.Host)
Authority will include the port number
I think you looking for Request.Url or RawUrl.
Uri.Scheme of Request.Url will give you info on http/https difference.
The window.location.origin in javascript returns the protocol, port (if any), domain and extension of the current url.
If you want to get the same information from an URL, the accepted answers will provide that to you.
If you want the same behavior, ie a piece of javascript is calling your server method and you want to know where it is calling from, you can inspect the HttpRequest.URLReferrer. However this can be spoofed easily and thus is not reliable.

(#803) Some of the aliases you requested do not exist: access_token","type":"OAuthException"

I am trying to get access token using from facebook graph API in my rails 2.3 based web application. The request I am sending for that is :
https://graph.facebook.com/oauth/access_token?client_id=<client_id>
&redirect_uri=http://localhost:3001/facebook_callback
&client_secret=<client_secret>
&code=AQBgog2NvoUYQCXsa2bGpj--s9RD71F3zTKX344cUZ-
AWX4CNhdx3Yerl_wmzQkQ4zIUFVS_CRoN0zXaEW63dHcC9sH6_
vl7ljSxwA6TLSrkWVcfdfdrmwBTlMNIzyJr0h6irGW1LCdTw8
Racgd8MQ9RgVn1gFL26epWA
And it is redirecting me to
http://localhost/facebook_callback?code=AQBgog2NvoUYQCXsa2bGpj--
s9RD71F3zTKX344cUZ AWX4CNhdx3Yerl_wmzQkQ4zIUFVS_CRoN0mAB_Sr1H4K
dXIlzXaEW63dHcC9sH6_vl7ljSxwA6TLSrkWVcfdfdrmwBTlMNIzyJr0h6irG
SxsrRAXtdviNsBTMW1LCdTw8Racgd8MQ9RgVn1gFL26epWA
I am getting error in both development and production environment . I am not able to get the access token. Has anyone else face the problem ??
This looks correct - Facebook redirects to your redirect url with the code= parameter. You then need to exchange the code for an access token. See here: http://developers.facebook.com/docs/authentication/
edit: my bad, I misread the first section. You can sometimes have problems using localhost as a redirect. Are you using a live domain without port in your non-test environment?
Well, I found solution of my problem :
The problem was with the path which I was using for request of access_token . I placed a slash in front of the path and bingo. It worked like a charm.
So instead of
oauth/access_token?client_id=#{ #client_id }&redirect_uri=#{ #redirect_uri }&client_secret=#{ #client_secret }&code=#{ code }"
we just need to use
/oauth/access_token?client_id=#{ #client_id }&redirect_uri=#{ #redirect_uri }&client_secret=#{ #client_secret }&code=#{ code }".
Thanks to all people for your efforts.

Microsoft Translator API answers 500 internal server error

I'm trying to use Microsoft's Translator API in my Rails app. Unfortunately and mostly unexpected, the server answers always with an internal server error. I also tried it manually with Poster[1] and I get the same results.
In more detail, what am I doing? I'm creating an XML string which goes into the body of the request. I used the C# Example of the API documentation. Well, and then I'm just invoking the RESTservice.
My code looks like this:
xmlns1 = "http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2"
xmlns2 = "http://schemas.microsoft.com/2003/10/Serialization/Arrays"
xml_builder = Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do |xml|
xml.TranslateArrayRequest("xmlns:ms" => xmlns1, "xmlns:arr" => xmlns2) {
xml.AppId token #using temporary token instead of appId
xml.From source
xml.To target
xml.Options {
xml["ms"].ContentType {
xml.text "text/html"
}
}
xml.Texts {
translate.each do |key,val|
xml["arr"].string {
xml.text CGI::unescape(val)
}
end
}
}
end
headers = {
'Content-Type' => 'text/xml'
}
uri = URI.parse(##msTranslatorBase + "/TranslateArray" + "?appId=" + token)
req = Net::HTTP::Post.new(uri.path, headers)
req.body = xml_builder.to_xml
response = Net::HTTP.start(uri.host, uri.port) { |http| http.request(req) }
# [...]
The xml_builder produces something like the following XML. Differently to the example from the API page, I'm defining two namespaces instead of referencing them on the certain tags (mainly because I wanted to reduces the overhead) -- but this doesn't seem to be a problem, when I do it like the docu-example I also get an internal server error.
<?xml version="1.0" encoding="UTF-8"?>
<TranslateArrayRequest xmlns:ms="http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2" xmlns:arr="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<AppId>TX83NVx0MmIxxCzHjPwo2_HgYN7lmWIBqyjruYm7YzCpwnkZL5wtS5oucxqlEFKw9</AppId>
<From>de</From>
<To>en</To>
<Options>
<ms:ContentType>text/html</ms:ContentType>
</Options>
<Texts>
<arr:string>Bitte übersetze diesen Text.</arr:string>
<arr:string>Das hier muss auch noch übersetzt werden.</arr:string>
</Texts>
</TranslateArrayRequest>
Every time I request the service it answers with
#<Net::HTTPInternalServerError 500 The server encountered an error processing the request. Please see the server logs for more details.>
... except I do some unspecified things, like using GET instead of POST, then it answers with something like "method not allowed".
I thought it might be something wrong with the XML stuff, because I can request an AppIdToken and invoke the Translate method without problems. But to me, the XML looks just fine. The documentation states that there is a schema for the expected XML:
The request body is a xml string generated according to the schema specified at http:// api.microsofttranslator.com/v2/Http.svc/help
Unfortunately, I cannot find anything on that.
So now my question(s): Am I doing something wrong? Maybe someone experienced similar situations and can report on solutions or work-arounds?
[1] Poster FF plugin > addons.mozilla.org/en-US/firefox/addon/poster/
Well, after lot's of trial-and-error I think I made it. So in case someone has similar problems, here is how I fixed this:
Apparently, the API is kind of fussy with the incoming XML. But since there is no schema (or at least I couldn't find the one specified in the documentation) it's kind of hard to do it the right way: the ordering of the tags is crucial!
<TranslateArrayRequest>
<AppId/>
<From/>
<Options />
<Texts/>
<To/>
</TranslateArrayRequest>
When the XML has this ordering it works. Otherwise you'll only see the useless internal server error response. Furthermore, I read a couple of times that the API also breaks if the XML contains improper UTF-8. One can force untrusted UTF-8 (e.g. coming from a user form) this way:
ic = Iconv.new('UTF-8//IGNORE', 'UTF-8')
valid_string = ic.iconv(untrusted_string + ' ')[0..-2]

Resources