Grails channel security causing a redirect loop - grails

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.

Related

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

'this page can't be displayed' when using HTTPS

for some actions in my Grails application i need to use HTTPS protocol , so i made the below filter :
def filters = {
all(controller:'checkout', action:'onlinePayment') {
before = {
if (!request.isSecure() /*&& !Environment.isDevelopmentMode()*/) {
def url = "https://" + request.serverName + request.forwardURI
redirect(url: url, permanent: true)
return false
}
}
but when i try to access this action , i get this page can't be displayed as seen in the screenshot and i'm geting in chrome's console net::ERR_CONNECTION_REFUSED, are there any configurations i missed to be able to use HTTPS protocol ?

Grails/SpringSecurity core and customizing logout behaviour

I'm using grails 2.3.7 with SpringSecurityCore 2.0 .. I have two separate signon screens tailored for specific devices with the appropriate one triggered by accessing a specific controller. To do this I customized the loginController ..
/**
* Show the login page.
*/
def auth() {
def config = SpringSecurityUtils.securityConfig
if (springSecurityService.isLoggedIn()) {
redirect uri: config.successHandler.defaultTargetUrl
return
}
String whereFrom = session.SPRING_SECURITY_SAVED_REQUEST.requestURI
def rdt = whereFrom.contains('RDT')
// Redirect for RDT as required ..
String view = rdt ? 'rauth' : 'auth'
String postUrl = "${request.contextPath}${config.apf.filterProcessesUrl}"
session.rdt = rdt
render view: view, model: [postUrl: postUrl,
rememberMeParameter: config.rememberMe.parameter]
}
which seems to work well .. On logout I want again to redirect to an appropriate screen .. I'm trying to use the session attribute I store on login along with a (admittedly old) link I found (http://grails.1312388.n4.nabble.com/Parameter-quot-logoutSuccessUrl-quot-in-spring-security-core-td2264147.html) to redirect back to an appropriate page ..
/**
* Index action. Redirects to the Spring security logout uri.
*/
def index() {
if (!request.post && SpringSecurityUtils.getSecurityConfig().logout.postOnly) {
response.sendError HttpServletResponse.SC_METHOD_NOT_ALLOWED // 405
return
}
// TODO put any pre-logout code here
def rdt = session.rdt
session.rdt = null
// redirect uri: "/j_spring_security_logout?spring-security-redirect=$logoutUrl"
if (rdt) {
def link = g.createLink(controller: "RDT")
def redirectUrl = "${SpringSecurityUtils.securityConfig.logout.filterProcessesUrl}?spring-security-redirect=${link}"
redirectStrategy.sendRedirect request, response, redirectUrl
} else {
redirectStrategy.sendRedirect request, response, SpringSecurityUtils.securityConfig.logout.filterProcessesUrl // '/j_spring_security_logout'
}
response.flushBuffer()
}
Both options return me to the 'default' auth login screen and not my alternate rauth one even with the addition of the extra parameter .. How can I route back to an appropriate screen ?? Thanks
In the end I manually set the session variables to null, invalidate the session and a standard redirect ... works ..

Not able to use grails database session plugin with mongodb

We are using grails 2.3.5 app with mongodb (no hibernate installed). I had forked & modified grails database session plugin with HQL queries to use simple queries so as to support mongodb.
Then when I'm trying to login via ajax, it fails. By fail, I mean that, session in created & persisted to the database but not able to login. When I enabled to logs, I saw cookies is present in the request path /j_spring_security_check after authentication but is not available after redirect i.e. in path /login/ajaxSuccess which causing authentication to be treated as false & a new session is created.
Our URL mapping config looks like this: (Does not matters)
"/$controller/$action?/$id?(.$format)?" {
constraints {
}
}
"/v2/$customController/action/$customAction" {
controller = {
return params.customController?.toUpperCamelCase()
}
action = {
return params.customAction?.toUpperCamelCase()
}
}
"/v2/$resource/$resourceId?/$subResource?/$subResourceId?" {
controller = {
if (params.subResource) {
return params.subResource.toUpperCamelCase()
}
return params.resource.toUpperCamelCase()
}
action = {
Map actionMethodMap = [GET: params.resourceId ? "show" : "index", POST: "save", PUT: "update", DELETE: "delete"]
return actionMethodMap[request.method.toUpperCase()]
}
id = {
if (params.subResource && params.subResourceId) {
return params.subResourceId
}
return params.resourceId
}
}
Our configuration looks like this for spring security:
grails.plugins.springsecurity.authority.className = 'com.test.Role'
grails.plugins.springsecurity.userLookup.userDomainClassName = 'com.test.User'
grails.plugins.springsecurity.userLookup.authorityJoinClassName = 'com.test.UserRole'
grails.plugins.springsecurity.useSessionFixationPrevention = true
//grails.plugins.springsecurity.redirectStrategy.contextRelative = true
grails.plugins.springsecurity.successHandler.defaultTargetUrl = "/app/ng/index.html"
grails.plugins.springsecurity.auth.loginFormUrl = "/app/ng/index.html#/auth/signin"
grails.plugins.springsecurity.auth.ajaxLoginFormUrl = "/v2/login/action/auth-ajax"
grails.plugins.springsecurity.ui.encodePassword = false
grails.plugins.springsecurity.controllerAnnotations.staticRules = [
'/j_spring_security_switch_user': ['ROLE_ADMIN'],
'/ck/standard/filemanager': ['ROLE_ADMIN'],
'/ck/standard/uploader': ['ROLE_ADMIN'],
'/ck/ofm/filemanager': ['ROLE_ADMIN'],
'/ck/ofm/filetree': ['ROLE_ADMIN'],
'/quartz/**': ["ROLE_ADMIN"],
'/**' : ['IS_AUTHENTICATED_ANONYMOUSLY']
]
Other than this, grails.serverURL config is commented for all environments to support wildcard subdomain.
Using:
Spring Security Core plugin version 1.2.7.3
Cookie plugin version 0.51
Webxml plugin version 1.4.1
Mongodb plugin version 2.0.1

Grails test user account creation manually

I am working in grails application, I was been asked to create a test user for our site. I did write the code in admin controller and gave the link in his page. The code worked and also I can see the details of this test user. But when I try to login using test user details, I am not able to login.
def createTestUser = {
String timeStr = System.currentTimeMillis() + ''
//def user = userService.createQuickUser(timeStr + '#test.supjam.com', timeStr, 'test-user') // TODO requires supajam-domain 2011.12.5.1
def user = userService.createQuickUser(timeStr + '#test.supajam.com', 'test-user')
user.passwd = timeStr
user.dailyNews = false
user.offers = false
user.emailConfirmed = true
user.enabled = true
user.save(failOnError: true)
}
This was the code. If anybody can please help, I would be thankful to them.
This similar question has some debugging tips:
Grails spring security login issue: /auth?login_error=1
i liked putting log.debug() statements in the authfail() if blocks.
if (exception instanceof AccountExpiredException) {
msg = SpringSecurityUtils.securityConfig.errors.login.expired
log.debug "exception - ${msg}" // added this
}

Resources