Grails Spring Security plugin and dbconsole - spring

I use grails 2.4.3 and have installed the official grails security plugin
compile ":spring-security-core:2.0-RC4"
Before installing the plugin, i was able to access the Database console page in using the url
http://localhost:8080/tobu/dbconsole
However, after installing the plugin, i am not able to do so. I get the default login screen when i try to access the above mentioned URl and logging in through any user account shows the "access denied" page. How do i resolve this issue?
grails.project.groupId = appName
grails.mime.disable.accept.header.userAgents = ['Gecko', 'WebKit', 'Presto', 'Trident']
grails.mime.types = [ // the first one is the default format
all: '*/*', // 'all' maps to '*' or the first available format in withFormat
atom: 'application/atom+xml',
css: 'text/css',
csv: 'text/csv',
form: 'application/x-www-form-urlencoded',
html: ['text/html','application/xhtml+xml'],
js: 'text/javascript',
json: ['application/json', 'text/json'],
multipartForm: 'multipart/form-data',
rss: 'application/rss+xml',
text: 'text/plain',
hal: ['application/hal+json','application/hal+xml'],
xml: ['text/xml', 'application/xml']
]
grails.views.default.codec = "html"
grails.controllers.defaultScope = 'singleton'
grails {
views {
gsp {
encoding = 'UTF-8'
htmlcodec = 'xml' // use xml escaping instead of HTML4 escaping
codecs {
expression = 'html' // escapes values inside ${}
scriptlet = 'html' // escapes output from scriptlets in GSPs
taglib = 'none' // escapes output from taglibs
staticparts = 'none' // escapes output from static template parts
}
}
// escapes all not-encoded output at final stage of outputting
// filteringCodecForContentType.'text/html' = 'html'
}
}
grails.converters.encoding = "UTF-8"
grails.scaffolding.templates.domainSuffix = 'Instance'
grails.json.legacy.builder = false
grails.enable.native2ascii = true
grails.spring.bean.packages = []
grails.web.disable.multipart=false
grails.exceptionresolver.params.exclude = ['password']
grails.hibernate.cache.queries = false
grails.hibernate.osiv.readonly = false
environments {
development {
grails.logging.jul.usebridge = true
}
production {
grails.logging.jul.usebridge = false
// TODO: grails.serverURL = "http://www.changeme.com"
}
}
log4j.main = {
// Example of changing the log pattern for the default console appender:
//
//appenders {
// console name:'stdout', layout:pattern(conversionPattern: '%c{2} %m%n')
//}
error 'org.codehaus.groovy.grails.web.servlet', // controllers
'org.codehaus.groovy.grails.web.pages', // GSP
'org.codehaus.groovy.grails.web.sitemesh', // layouts
'org.codehaus.groovy.grails.web.mapping.filter', // URL mapping
'org.codehaus.groovy.grails.web.mapping', // URL mapping
'org.codehaus.groovy.grails.commons', // core / classloading
'org.codehaus.groovy.grails.plugins', // plugins
'org.codehaus.groovy.grails.orm.hibernate', // hibernate integration
'org.springframework',
'org.hibernate',
'net.sf.ehcache.hibernate'
}
// Added by the Spring Security Core plugin:
grails.plugin.springsecurity.userLookup.userDomainClassName = 'tobu.Actor'
grails.plugin.springsecurity.userLookup.authorityJoinClassName = 'tobu.ActorRole'
grails.plugin.springsecurity.authority.className = 'tobu.Role'
grails.plugin.springsecurity.controllerAnnotations.staticRules = [
'/': ['permitAll'],
'/dbconsole': ['permitAll'],
'/index': ['permitAll'],
'/index.gsp': ['permitAll'],
'/assets/**': ['permitAll'],
'/**/js/**': ['permitAll'],
'/**/css/**': ['permitAll'],
'/**/images/**': ['permitAll'],
'/**/favicon.ico': ['permitAll']
]

I had to make the following changes to the static rules in the config file.
'/dbconsole/**': ['ROLE_USER'],

2019 UPDATE
I needed to tweak Shashank's answer a bit for it to work for me. I'm using Grails 3.3.9 and spring-security-core 3.2.3.
I had to add this line to the file grails-app/conf/application.groovy
grails.plugin.springsecurity.controllerAnnotations.staticRules = [
//.......
[pattern: '/dbconsole/**', access: ['ROLE_USER']]
]

I wanted to have the dbconsole accessible without my custom authentication made using the Spring Security Core plugin (the dbconsole has its own login page and it's enabled for the dev environment only). Originally, I was trying the following static rule in the grails-app/conf/application.groovy file:
grails.plugin.springsecurity.controllerAnnotations.staticRules = [
[pattern: '/dbconsole', access: ['permitAll']],
...which didn't have any effect. I have always been redirected to Spring Security Core's login page.
After reading other answers of this question, I have managed to create a working static rule so http://localhost:8080/dbconsole is not secured by the Spring Security Core plugin anymore:
grails.plugin.springsecurity.controllerAnnotations.staticRules = [
[pattern: '/dbconsole/**', access: ['permitAll']],
The trick is to create a static rule for /dbconsole and all sub-paths (when dbconsole is accessed, it redirects to a login page located at dbconsole/login.jsp), that's why the double-stars are needed.

Related

ERR_TOO_MANY_REDIRECTS on vercel after deploying Nextjs App

I deployed my nextjs app to Vercel and it was a success.
I can see a preview of the website and even the log saying it works well.
But i try to access the website via the default Vercel domain :
https://tly-nextjs.vercel.app/
I get an ERR_TOO_MANY_REDIRECTS.
I do not have this problem locally.
I tried :
Disabling a language redirect that I use (/en for english folks, and / for french people).
Disabling the language detector of i18next.
But none of these solutions changed anything.
Any ideas ?
i18n.js file
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import Cache from 'i18next-localstorage-cache';
import LanguageDetector from 'i18next-browser-languagedetector';
const fallbackLng = ['fr'];
const availableLanguages = ['fr', 'en'];
const en = require('./locales/en/common.json');
const fr = require('./locales/fr/common.json');
const options = {
order: ['querystring', 'navigator'],
lookupQuerystring: 'lng'
}
const cacheOptions = {
// turn on or off
enabled: true,
// prefix for stored languages
prefix: 'i18next_res_',
// expiration
expirationTime: 365*24*60*60*1000,
// language versions
//versions: {}
}
i18n
.use(Cache)
.use(initReactI18next)
.use(LanguageDetector)
.init({
cache: cacheOptions,
fallbackLng: fallbackLng,
debug: true,
detection: options,
supportedLngs: availableLanguages,
nonExplicitSupportedLngs: true,
resources: {
en: {translation: en},
fr: {translation: fr},
},
interpolation: {
escapeValue: false,
},
react: {
wait: true,
useSuspense: true,
},
});
export default i18n;
My change Language function :
const changeLanguageInHouse = (lang, bool) => {
setLoading(true);
i18next.changeLanguage(lang).then((t) => {
setLanguage(lang);
bake_cookie("langChoice", lang);
setLoading(false);
if (bool === true) {
var newUrl2 = (lang === "fr" ? "" : "/en") + asPath;
window.location.replace(newUrl2);
}
});
};
What happend at your server is following:
You enter https://tly-nextjs.vercel.app/ and it is redirected to /en with HTTP-Status-Code 307 (Temporary Redirect).
And /en redirect with 301 (Permanent Redirect) to /.
You can reproduce this by open the Browser-Dev-Tools and have a look at the Network Tab.
It might be, that you have some kind of url-rewriting activated at your server, which redirect everything to your domain-root.
Is there a public repo available for this? Here is how it worked for me.
Try changing the order of the locales and the default locale (not sure this helps, but it changed something for me. Undocumented if that is the case!)
So I put the default locale first (which is nl for me) in both the locales array and the domains array.
Let me know if that helps!
module.exports = {
i18n: {
localeDetection: false,
// These are all the locales you want to support in
// your application
locales: ['nl', 'en'],
// This is the default locale you want to be used when visiting
// a non-locale prefixed path e.g. `/hello`
defaultLocale: 'nl',
// This is a list of locale domains and the default locale they
// should handle (these are only required when setting up domain routing)
domains: [
{
domain: 'example.be',
defaultLocale: 'nl',
},
{
domain: 'example.com',
defaultLocale: 'en',
},
],
},
trailingSlash: true,
};
I changed all my getInitialProps to getServerSideProps
and realised I was doing a redirect on response :
res.writeHead(301, { Location: "/" })
I just delete it.
And now I don't have this endless redirect.
Doing this worked for me...
https://ardasevinc.tech/cloudflare-vercel-too-many-redirects
I think it's the actual solution to the cause of the problem rather than a bandage!

Grails spring security oauth2 provider request for resource with correct bearer token redirects to login

As the title implies, I have a controller method protected by the oAuth2 plugin, but when I send a request to it including a correct Authorization: Bearer <token> (using Postman), the response I get is the HTML for the login page.
Method in question:
#Secured(["ROLE_USER", "#oauth2.clientHasAnyRole('ROLE_CLIENT', 'ROLE_TRUSTED_CLIENT')"])
def getUserData(){
response.setContentType("application/json")
User u = springSecurityService.currentUser
println u
render u.mseUserInfo
}
Config.groovy:
// Added by the Spring Security Core plugin:
grails.plugin.springsecurity.auth.loginFormUrl = '/mse/login'
grails.plugin.springsecurity.userLookup.userDomainClassName = 'cz.improvisio.MSEauthProvider.user.User'
grails.plugin.springsecurity.userLookup.authorityJoinClassName = 'cz.improvisio.MSEauthProvider.user.UserRole'
grails.plugin.springsecurity.authority.className = 'cz.improvisio.MSEauthProvider.user.Role'
grails.plugin.springsecurity.controllerAnnotations.staticRules = [
'/oauth/authorize.dispatch':[
"ROLE_USER",
"isFullyAuthenticated()"
],
'/oauth/token.dispatch':[
"ROLE_USER",
"isFullyAuthenticated()"
],
'/mse/login':["permitAll"],
'/mse/':["permitAll"],
'/**':["permitAll"]]
// Added by the Spring Security OAuth2 Provider plugin:
grails.plugin.springsecurity.oauthProvider.clientLookup.className = 'cz.improvisio.MSEauthProvider.user.Client'
grails.plugin.springsecurity.oauthProvider.authorizationCodeLookup.className = 'cz.improvisio.MSEauthProvider.user.AuthCode'
grails.plugin.springsecurity.oauthProvider.accessTokenLookup.className = 'cz.improvisio.MSEauthProvider.user.AccessToken'
grails.plugin.springsecurity.oauthProvider.refreshTokenLookup.className = 'cz.improvisio.MSEauthProvider.user.RefreshToken'
grails.plugin.springsecurity.filterChain.chainMap = [
'/oauth/token': 'JOINED_FILTERS,-oauth2ProviderFilter,-securityContextPersistenceFilter,-logoutFilter,-authenticationProcessingFilter,-rememberMeAuthenticationFilter,-exceptionTranslationFilter',
'/securedOAuth2Resources/**': 'JOINED_FILTERS,-securityContextPersistenceFilter,-logoutFilter,-authenticationProcessingFilter,-rememberMeAuthenticationFilter,-oauth2BasicAuthenticationFilter,-exceptionTranslationFilter',
'/**': 'JOINED_FILTERS,-statelessSecurityContextPersistenceFilter,-oauth2ProviderFilter,-clientCredentialsTokenEndpointFilter,-oauth2BasicAuthenticationFilter,-oauth2ExceptionTranslationFilter'
]
This is the client creation from Bootstrap.groovy:
new Client(
clientId: 'testClient',
authorizedGrantTypes: [
'authorization_code',
'refresh_token',
'implicit',
'password',
'client_credentials'
],
authorities: ['ROLE_CLIENT'],
scopes: ['read', 'write'],
redirectUris: ['http://test.com']).save(flush: true)
And one more slightly related question: I couldnt find a way to get the User to whose resources the access token should be linked to, so I assumed Id be able to get it through springSecurityService. Is this the correct way of doing so? Or do I need to pass the userId to the method (and will OpenAM do it?)?
Turns out I didnt have the proper filter chain set up for my action. Changing config to
grails.plugin.springsecurity.filterChain.chainMap = [
'/oauth/token': 'JOINED_FILTERS,-oauth2ProviderFilter,-securityContextPersistenceFilter,-logoutFilter,-authenticationProcessingFilter,-rememberMeAuthenticationFilter,-exceptionTranslationFilter',
'/securedOAuth2Resources/**': 'JOINED_FILTERS,-securityContextPersistenceFilter,-logoutFilter,-authenticationProcessingFilter,-rememberMeAuthenticationFilter,-oauth2BasicAuthenticationFilter,-exceptionTranslationFilter',
'/myController/getUserData': 'JOINED_FILTERS,-securityContextPersistenceFilter,-logoutFilter,-authenticationProcessingFilter,-rememberMeAuthenticationFilter,-oauth2BasicAuthenticationFilter,-exceptionTranslationFilter',
'/**': 'JOINED_FILTERS,-statelessSecurityContextPersistenceFilter,-oauth2ProviderFilter,-clientCredentialsTokenEndpointFilter,-oauth2BasicAuthenticationFilter,-oauth2ExceptionTranslationFilter'
]
fixed it.

Grails + Spring Security Rest + How to login

I have created as sample rest application using grails and added a security using spring security rest plugin. I am trying to test it using rest client POSTMAN but getting 404 to '$MYAPP/api/login' and 401 '$MYAPP/api/login/' to when I sent post request with username and password as json in raw data.
I have followed all the blogs and stackoverflow but non of the things worked for me. Here is my code.
In Config.groovy
// Added by the Spring Security Core plugin:
grails.plugin.springsecurity.userLookup.userDomainClassName = 'com.example.api.auth.APIUser'
grails.plugin.springsecurity.userLookup.authorityJoinClassName = 'com.example.api.auth.APIUserRole'
grails.plugin.springsecurity.authority.className = 'com.example.api.auth.Role'
grails.plugin.springsecurity.securityConfigType = 'InterceptUrlMap'
grails.plugin.springsecurity.interceptUrlMap = [
'/': ['permitAll'],
'/index': ['permitAll'],
'/index.gsp': ['permitAll'],
'/assets/**': ['permitAll'],
'/partials/**': ['permitAll'],
'/api/**': ['permitAll'],
'/**': ['isFullyAuthenticated()']
]
grails.plugin.springsecurity.filterChain.chainMap = [
'/api*//**': 'JOINED_FILTERS,-exceptionTranslationFilter,-authenticationProcessingFilter,-securityContextPersistenceFilter', // Stateless chain
'*//**': 'JOINED_FILTERS,-restTokenValidationFilter,-restExceptionTranslationFilter' // Traditional chain
]
grails.plugin.springsecurity.rest.login.active=true
grails.plugin.springsecurity.rest.login.endpointUrl = '/api/login'
grails.plugin.springsecurity.rememberMe.persistent = false
grails.plugin.springsecurity.rest.login.useJsonCredentials = true
grails.plugin.springsecurity.rest.login.useRequestParamsCredentials = false
grails.plugin.springsecurity.rest.login.failureStatusCode = 401
grails.plugin.springsecurity.rest.login.usernamePropertyName = 'username'
grails.plugin.springsecurity.rest.login.passwordPropertyName = 'password'
grails.plugin.springsecurity.rest.token.storage.useGorm = true
grails.plugin.springsecurity.rest.token.storage.gorm.tokenDomainClassName = 'com.example.api.auth.AuthenticationToken'
grails.plugin.springsecurity.rest.token.storage.gorm.tokenValuePropertyName = 'token'
grails.plugin.springsecurity.rest.token.storage.gorm.usernamePropertyName = 'username'
grails.plugin.springsecurity.rest.token.storage.gorm.passwordPropertyName = 'password'
grails.plugin.springsecurity.rest.logout.endpointUrl = '/api/logout'
grails.plugin.springsecurity.rest.token.validation.headerName = 'X-Auth-Token'
grails.plugin.springsecurity.rest.token.validation.useBearerToken = false
In BuildConfig.groovy
// security
compile ":spring-security-core:2.0-RC4"
compile ":spring-security-rest:1.4.0.RC5", {
excludes ('cors','spring-security-core')
}
Please provide feedback if something is wrong in my configuration or the way of testing using POSTMAN.
This is my final config.groovy code which works.
// Added by the Spring Security Core plugin:
grails.plugin.springsecurity.userLookup.userDomainClassName = 'example.User'
grails.plugin.springsecurity.userLookup.authorityJoinClassName = 'example.UserRole'
grails.plugin.springsecurity.authority.className = 'example.Role'
grails.plugin.springsecurity.interceptUrlMap = [
'/': ['permitAll'],
'/index': ['permitAll'],
'/index.gsp': ['permitAll'],
'/assets/**': ['permitAll'],
'/partials/**': ['permitAll'],
'/api/**': ['isFullyAuthenticated()'],
'/**': ['isFullyAuthenticated()']
]
grails.plugin.springsecurity.filterChain.chainMap = [
'/auth/**': 'JOINED_FILTERS,-exceptionTranslationFilter,-authenticationProcessingFilter,-securityContextPersistenceFilter, -rememberMeAuthenticationFilter', // Stateless chain
'/api/**': 'JOINED_FILTERS,-exceptionTranslationFilter,-authenticationProcessingFilter,-securityContextPersistenceFilter', // Stateless chain
'/**': 'JOINED_FILTERS,-restTokenValidationFilter,-restExceptionTranslationFilter' // Traditional chain
]
grails.plugin.springsecurity.rest.login.active=true
grails.plugin.springsecurity.rest.login.endpointUrl='/auth/login'
grails.plugin.springsecurity.rest.login.failureStatusCode=401
grails.plugin.springsecurity.rest.login.useJsonCredentials=true
grails.plugin.springsecurity.rest.login.usernamePropertyName='username'
grails.plugin.springsecurity.rest.login.passwordPropertyName='password'
grails.plugin.springsecurity.rest.logout.endpointUrl='/auth/logout'
grails.plugin.springsecurity.rest.token.storage.useGorm=true
grails.plugin.springsecurity.rest.token.storage.gorm.tokenDomainClassName='example.AuthenticationToken'
grails.plugin.springsecurity.rest.token.storage.gorm.tokenValuePropertyName='tokenValue'
grails.plugin.springsecurity.rest.token.storage.gorm.usernamePropertyName='username'
grails.plugin.springsecurity.rest.token.generation.useSecureRandom=true
//grails.plugin.springsecurity.rest.token.validation.headerName='X-Auth-Token'
grails.plugin.springsecurity.rest.token.generation.useUUID=false
grails.plugin.springsecurity.rest.token.validation.active=true
grails.plugin.springsecurity.rest.token.validation.endpointUrl='/auth/validate'

grails spring security rest plugin how to skip url from authentication

I am using spring security rest plugin as well as core in my grails app,i want to have some calls those can be accessed without authentication and for this i am adding #Secured('permitAll') on action but it is not working,it is still asking for token.
I have also tried '/api/getdata': ['permitAll'] in config.groovy,but no result!!!
You need to add the anonymous filter to your filter chain.
If you followed the grails spring security rest configuration tutorial you probably got the following code:
grails.plugin.springsecurity.filterChain.chainMap = [
//Stateless chain
[
pattern: '/**',
filters: 'JOINED_FILTERS,-anonymousAuthenticationFilter,-exceptionTranslationFilter,-authenticationProcessingFilter,-securityContextPersistenceFilter,-rememberMeAuthenticationFilter'
]
]
Note that you have "-anonymousAuthenticationFilter" , which removes this filter from your filter chain.
By removing this part (-anonymousAuthenticationFilter) from your code, this filter will back to your filter chain,
so you can use the #Secured("permitAll") or #Secured(['IS_AUTHENTICATED_ANONYMOUSLY']) again.
My final filter chain map was the following and worked like a charm.
grails.plugin.springsecurity.filterChain.chainMap = [
//Stateless chain
[
pattern: '/**',
filters: 'JOINED_FILTERS,-exceptionTranslationFilter,-authenticationProcessingFilter,-securityContextPersistenceFilter,-rememberMeAuthenticationFilter'
]
]
Add this to you logback.groovy in the development environment when you need to see more details about the authentication process
logger("org.springframework.security", DEBUG, ['STDOUT'], false)
logger("grails.plugin.springsecurity", DEBUG, ['STDOUT'], false)
logger("org.pac4j", DEBUG, ['STDOUT'], false)
logger("StackTrace", ERROR, ['FULL_STACKTRACE'], false)
root(ERROR, ['STDOUT', 'FULL_STACKTRACE'])
The same idea applies if you do not use spring security rest.
Same answer I gave in another post, didn't knew what to do.
use static mapping..
grails.plugin.springsecurity.controllerAnnotations.staticRules = [
'/': ['permitAll'],
'/user/someaction1': ['permitAll'],
'/user/someaction1': ['permitAll'],
]

Grails spring security defaultTargetUrl going wrong path

Grails 2.4 with Spring security 2 3RC
I have this on my Config.groovy
grails.plugin.springsecurity.controllerAnnotations.staticRules = [
'/': ['permitAll'],
'/index': ['permitAll'],
'/index.gsp': ['permitAll'],
'/**/js/**': ['permitAll'],
'/**/css/**': ['permitAll'],
'/**/images/**': ['permitAll'],
'/**/favicon.ico': ['permitAll']
]
grails.plugin.springsecurity.successHandler.defaultTargetUrl = "/home/index"
But this keeping me redirecting to
assets/favicon.ico
And my HomeController is like that
#Secured(['ROLE_ADMIN', 'ROLE_USER'])
def index() {
if (SpringSecurityUtils.ifAllGranted('ROLE_ADMIN')) {
redirect controller: 'admin', action: 'index'
return
}
}
And I modify this in my UrlMapping:
"/"(controller: 'home', action:'index')
Why it keeps me sending wrong path?
Update: using another computer, it redirects me to /asset/grails_logo.png
It sounds like you are having a similar problem to the one I experienced upgrading a Grails 1.x application to 2.4.2. When you attempt to access a URL/page that is protected by Spring Security authorization rules and you are not logged in, it redirects you to the login page. Upon successful login, it redirects you to the URL you requested. In this case, your favicon.ico and grails_logo.png are being protected by authorization rules, unintentionally I'm guessing, so it redirects you to the login page. Upon successful login, it redirects you to the favicon.ico or grails_logo.png URL because that is protected URL that was being requested when authorization failed. Change your authorization rules accordingly (may want to do both if you have assets in both locations):
If you are using the Asset Pipeline Plugin, use:
'/assets/**': ['permitAll']
If you are using something like the Resources Plugin, use:
'/css/**': ['permitAll'],
'/js/**': ['permitAll'],
'/images/**': ['permitAll']

Resources