ERR_TOO_MANY_REDIRECTS in grails - grails

I have a filter that is applicable for all controllers and actions
all(controller:'*', action:'*')
If a certain condition is met, I am trying to redirect the user to another page. But I am getting the above stated error. I inserted some logs to see if the filter is being applied or not and I noticed that the
if(condition){} block was being executed multiple times and hence I believe the error is occurring.
Please let me know how I can overcome this. Thank you.

I have code, I hope this help you
def filters = {
sessionCheck(controller: '*', action: '*') {
before = {
if(!(controllerName=="valueSet" && (actionName=="MATReleases" || actionName=="downloadReleases"))) {
if ("your condition") {
def url =new ApplicationTagLib().createLink(controller:'router',action:'sessionExpired')
render(status: 500, contentType: 'text/html', text: "<script>var sessionExpired ; window.location.href='${url}';</script>")
return false
}else{
}
} else {
println "else part"
}
}
}
}

Related

grails application access after authentication with ldap role based authorization

Our grails application uses ldap authentication, without any problems, now I need to prevent access, to the entire application, if a user has no specific ldap role.
I can see the role and use it in my Config.groovy annotations or secure the actions in the controllers, but instead I need a scenario/way to just show a "Denied ..." message and logout. (POST Forbidden 403).
def filters = {
loginFilter(controller:'login', action:'ajaxSuccessSproutcore') {
before = {
switch(Environment.current.name) {
case { it == 'development' || it == 'hrm'}:
if (springSecurityService.isLoggedIn() && grails.plugin.springsecurity.SpringSecurityUtils.ifAnyGranted("ROLE_ADMIN, ROLE_SEA_HRM_LOGIN")){
} else {
if (springSecurityService.isLoggedIn()) {
render ([msg:''] as JSON)
session.invalidate()
return false
}
}
break
default:
if (springSecurityService.isLoggedIn() && grails.plugin.springsecurity.SpringSecurityUtils.ifAnyGranted("ROLE_ADMIN , ROLE_USER")){
} else {
if (springSecurityService.isLoggedIn()) {
render ([msg:''] as JSON)
session.invalidate()
return false
}
}
break
}
}
after = { Map model ->
}
afterView = { Exception e ->
}
}
}
In grails 3 you can set up an Interceptor to check every request and take the appropriate action. In your case you'd want to add a check in the before block.
Edit: As Jeff Brown notes in the comments, grails 2 used Filters rather than interceptors.
Edit: Something like this in your logout logic:
...
else {
if (springSecurityService.isLoggedIn()) {
session.invalidate()
redirect action:'youShallNotPass'
return false
}
}

HTTPS routing suddenly stopped working in Grails

In my Grails 2.5.1 application , i was using a filter to use HTTPS with some controllers , everything was working fine but suddenly this filter is not working any more .
Filter :
def filters = {
all(controller:'checkout', action:'onlinePayment') {
before = {
if (!request.isSecure() /*&& !Environment.isDevelopmentMode()*/) {
def url = "https://" + request.serverName+':8443' + request.forwardURI
println "in filter"
redirect(url: url, permanent: true)
return false
}
}
after = { Map model ->
}
afterView = { Exception e ->
}
}
}
Here is the checkout page :
Also i found that no requests came to the filter as in filter was not printed out, is there something i need to check to fix this issue rather than this filter

Grails channel security causing a redirect loop

I am new to Grails and I am working on an exisiting application. I am trying to force the anyone using our website to allways be on https. I added the Spring Security Core plugin
//BuildConfig.groovy
compile "org.grails.plugins:spring-security-core:2.0.0"
and I just added
///Config.groovy
grails.plugin.springsecurity.secureChannel.definition = [
'/**': 'REQUIRES_SECURE_CHANNEL'
When I try to go on localhost:8080/myapp, it redirects me to https://localhost:8443/myapp, but I get a "This webpage has a redirect loop ERR_TOO_MANY_REDIRECTS" message.
I added print statements in my SecurityFilters.groovy, and I can see the infinite loop going
baseFilter(controller: "*", action: "*")
{
before = {
println "baseFilter"
// If auth controller then ok to continue
if (controllerName.equals("auth"))
{
return true;
}
// If no subject (user) and not auth controller then user must authenticate
if (!session.subject && !(controllerName.equals("auth")))
{
params.targetUri = request.forwardURI - request.contextPath
if (params.action=="profile") {
params.targetUri=params.targetUri + "?page=" + params?.page
}
else if (params.action=="results") {
params.targetUri="/home"
}
println "baseFilter: Redirecting: PARAMS = $params"
redirect(controller:'auth', action:'login', params: params)
return false;
}
}
}
It's just:
baseFilter
baseFilter: Redirecting: PARAMS = [action:auth, format:null, controller:login, targetUri:/login/auth]
Over and over.
I've tried many other things I found on Stackoverflow and other websites, but they either do not work, or are too complicated.
Thank you.
Ok, so this isn't the answer to the question, but I managed to achieve what I was trying to do, which was to force SLL, and redirect any attempts to use http. I did this by using the shiro plugin, which was already being used by my application. In the Buildconfig.groovy, just add compile ":shiro:1.2.1" to you plugins. In the config.groovy I added the following properties:
security {
shiro {
filter {
loginUrl = "/login"
successUrl = "/"
unauthorizedUrl = "/unauthorized"
filterChainDefinitions = """
/** = ssl[443]
"""
}
}
}
You can modify your filterChainDefinitions to only force ssl on certain urls. I just used /** because I always want SSL.

Geb click executed before input is completed

I'm running a simple Geb test like so:
class IndexPage extends Page {
//static url = "http://localhost:8080/sampleGrailsApp"
static at = { title == "sampleGrailsApp" }
static content = {
signInButton { $("div", 0, class: "container-fluid").find("button", 0) }
modalFooterSignInButton(wait: true, to: MyPage) { $("footer", 0, class: "modal-footer").find("input", 0, class: "btn-primary") }
modalFooterUsernameInput { $("form").username = it }
modalFooterPasswordInput { $("form").password = it }
signIn { username, password ->
signInButton.click()
waitFor { modalFooterSignInButton.present }
modalFooterUsernameInput username
modalFooterPasswordInput password
modalFooterSignInButton.click()
}
}
}
In my test, the page is called as follows:
def "sigin"() {
given: "User is at index page"
at IndexPage
when: "User signs in"
signIn "username","password"
then: "Goes to MyPage"
at MyPage
}
On some occasions, the modalFooterSignInButton.click() happens before the username has been entered completely therefore failing the test. Has anyone encountered this before? How do I wait for input to complete first before click is activated? I'm using Geb 0.9.2.
Thanks in advance.
Try using isDisplayed() instead of present as present means is present in the code but isDisplayed() means it appears in the UI. Hope the following stuffs would solve your problem!
waitFor { modalFooterSignInButton.isDisplayed()}
Also, use waitFor{} in case of critical situations as I don't know anything about your app.
You could do something like :
waitFor { $(<username-input>).text().contains("username") } // after username is entered.
waitFor { $(<password-input>).text().contains("password") } // after password is entered.
before calling modalFooterSignInButton.click()
Also, is this behavior specific to any browser or it happens in all the browsers?

Logic block in Grails URLMappings

My site has urls like 'http://someRandomUsername.mysite.com'.
Sometimes users will try urls like
'http://www.someRandomeUsername.mysite.com'. I'd like to have some
logic in my url mappings to deal with this.
With the mappings below when I hit the page , with or without the
unneeded www, I get:
2012-03-01 14:52:16,014 [http-8080-5] ERROR [localhost].[/ambit] -
Unhandled exception occurred whilst decorating page
java.lang.IllegalArgumentException: URL mapping must either provide a
controller or view name to map to!
Any idea how to accomplish this? The mapping is below.
Thanks!
Jason
static mappings = {
name publicMap: "/$action?/$id?" {
def ret = UrlMappings.check(request)
controller = ret.controller
userName = ret.userName
}
}
static check =
{ request ->
def tokens = request?.serverName?.split(/\./) as List ?: []
def ret = [controller:'info']
if(tokens.size() > 3 && token[0] == 'www')
{
ret.userName = tokens[1]
ret.controller = 'redirect'
ret.action = 'removeWWW'
}
else if(tokens.size() == 3)
{
ret.userName = tokens[0]
ret.controller = 'info'
}
return ret
}
Honestly, like DmitryB said, the best way to do this is via the web server, whether it's IIS, Apache, or Tomcat.
Having said that, I feel the best way to accomplish this in Grails would be using filters.
You could create something like this in your ~/conf directory:
public class StripFilters {
def filters = {
stripWWWFilter(controller: '*', action: '*') {
before = {
def tokens = request.serverName.tokenize(/\./) ?: []
if(tokens.size() > 3 && tokens[0] == 'www') {
def url = request.request.requestURL.toString().replace('www.', '')
redirect([url:url, params: [userName: tokens[1]], permanent: true])
return false
}
}
}
}
}
This should do the trick.

Resources