A component required a bean named '' that could not be found - spring
I'm trying to build my first grails application using grails-spring-security-rest plugin following this post's instructions.
However, when I try to run the application it gives me the following output:
| Running application...
2017-05-07 20:18:54.614 WARN --- [ main] g.p.s.SpringSecurityCoreGrailsPlugin :
Configuring Spring Security Core ...
Configuring Spring Security Core ...
2017-05-07 20:18:54.688 WARN --- [ main] g.p.s.SpringSecurityCoreGrailsPlugin : ... finished configuring Spring Security Core
... finished configuring Spring Security Core
Configuring Spring Security REST 2.0.0.M2...
... finished configuring Spring Security REST
... with GORM support
2017-05-07 20:19:00.278 DEBUG --- [ost-startStop-1] o.s.s.w.a.i.FilterSecurityInterceptor : Validated configuration attributes
2017-05-07 20:19:00.527 DEBUG --- [ost-startStop-1] g.p.s.r.t.g.jwt.FileRSAKeyProvider : Loading public/private key from DER files
2017-05-07 20:19:00.531 DEBUG --- [ost-startStop-1] g.p.s.r.t.g.jwt.FileRSAKeyProvider : Public key path: /mnt/dev/Workspaces/LZR.RAS/RAS-API/security/public_key.der
2017-05-07 20:19:00.538 DEBUG --- [ost-startStop-1] g.p.s.r.t.g.jwt.FileRSAKeyProvider : Private key path: /mnt/dev/Workspaces/LZR.RAS/RAS-API/security/private_key.der
2017-05-07 20:19:00.612 DEBUG --- [ost-startStop-1] g.p.s.rest.RestTokenValidationFilter : Initializing filter 'restTokenValidationFilter'
2017-05-07 20:19:00.612 DEBUG --- [ost-startStop-1] g.p.s.rest.RestTokenValidationFilter : Filter 'restTokenValidationFilter' configured successfully
2017-05-07 20:19:00.612 DEBUG --- [ost-startStop-1] o.s.s.w.a.ExceptionTranslationFilter : Initializing filter 'restExceptionTranslationFilter'
2017-05-07 20:19:00.612 DEBUG --- [ost-startStop-1] o.s.s.w.a.ExceptionTranslationFilter : Filter 'restExceptionTranslationFilter' configured successfully
2017-05-07 20:19:00.613 DEBUG --- [ost-startStop-1] o.s.security.web.FilterChainProxy : Initializing filter 'filterChainProxy'
2017-05-07 20:19:00.613 DEBUG --- [ost-startStop-1] o.s.security.web.FilterChainProxy : Filter 'filterChainProxy' configured successfully
2017-05-07 20:19:00.613 DEBUG --- [ost-startStop-1] g.p.s.rest.RestLogoutFilter : Initializing filter 'restLogoutFilter'
2017-05-07 20:19:00.613 DEBUG --- [ost-startStop-1] g.p.s.rest.RestLogoutFilter : Filter 'restLogoutFilter' configured successfully
2017-05-07 20:19:00.613 DEBUG --- [ost-startStop-1] g.p.s.rest.RestAuthenticationFilter : Initializing filter 'restAuthenticationFilter'
2017-05-07 20:19:00.613 DEBUG --- [ost-startStop-1] g.p.s.rest.RestAuthenticationFilter : Filter 'restAuthenticationFilter' configured successfully
2017-05-07 20:19:02.731 DEBUG --- [ main] o.s.s.a.h.RoleHierarchyImpl : setHierarchy() - The following role hierarchy was set:
2017-05-07 20:19:03.064 ERROR --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
A component required a bean named '' that could not be found.
Action:
Consider defining a bean named '' in your configuration.
Here is my application.yml content:
---
grails:
profile: rest-api
codegen:
defaultPackage: ras
spring:
transactionManagement:
proxies: false
info:
app:
name: '#info.app.name#'
version: '#info.app.version#'
grailsVersion: '#info.app.grailsVersion#'
spring:
main:
banner-mode: "off"
groovy:
template:
check-template-location: false
# Spring Actuator Endpoints are Disabled by Default
endpoints:
enabled: false
jmx:
enabled: true
---
grails:
mime:
disable:
accept:
header:
userAgents:
- Gecko
- WebKit
- Presto
- Trident
types:
json:
- application/json
- text/json
hal:
- application/hal+json
- application/hal+xml
xml:
- text/xml
- application/xml
atom: application/atom+xml
css: text/css
csv: text/csv
js: text/javascript
rss: application/rss+xml
text: text/plain
all: '*/*'
urlmapping:
cache:
maxsize: 1000
controllers:
defaultScope: singleton
converters:
encoding: UTF-8
---
hibernate:
cache:
queries: false
use_second_level_cache: true
use_query_cache: false
region.factory_class: org.hibernate.cache.ehcache.EhCacheRegionFactory
dataSource:
pooled: true
jmxExport: true
driverClassName: com.mysql.jdbc.Driver
dialect: org.hibernate.dialect.MySQL5InnoDBDialect
username: *******
password: *******
environments:
development:
dataSource:
dbCreate: create-drop
url: jdbc:mysql://localhost:3306/ras_dev?autoReconnect=true&useUnicode=yes&characterEncoding=UTF-8&useSSL=false
test:
dataSource:
dbCreate: create-drop
url: jdbc:mysql://localhost:3306/ras_test?autoReconnect=true&useUnicode=yes&characterEncoding=UTF-8&useSSL=false
production:
dataSource:
dbCreate: update
url: jdbc:mysql://localhost:3306/ras?autoReconnect=true&useUnicode=yes&characterEncoding=UTF-8
properties:
jmxEnabled: true
initialSize: 5
maxActive: 50
minIdle: 5
maxIdle: 25
maxWait: 10000
maxAge: 600000
timeBetweenEvictionRunsMillis: 5000
minEvictableIdleTimeMillis: 60000
validationQuery: SELECT 1
validationQueryTimeout: 3
validationInterval: 15000
testOnBorrow: true
testWhileIdle: true
testOnReturn: false
jdbcInterceptors: ConnectionState
defaultTransactionIsolation: 2 # TRANSACTION_READ_COMMITTED
application.groovy
grails.plugin.springsecurity.useSecurityEventListener = true
grails.plugin.springsecurity.securityConfigType = 'InterceptUrlMap'
grails.plugin.springsecurity.rememberMe.persistent = true
grails.plugin.springsecurity.rest.login.active = true
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.login.failureStatusCode = 401
grails.plugin.springsecurity.rest.login.endpointUrl = '/api/login'
grails.plugin.springsecurity.rest.logout.endpointUrl = '/api/logout'
grails.plugin.springsecurity.rest.token.storage.jwt.useEncryptedJwt = true
grails.plugin.springsecurity.rest.token.storage.jwt.privateKeyPath = 'security/private_key.der'
grails.plugin.springsecurity.rest.token.storage.jwt.publicKeyPath = 'security/public_key.der'
grails.plugin.springsecurity.rest.token.rendering.authoritiesPropertyName = 'permissions'
grails.plugin.springsecurity.rest.token.rendering.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.validation.useBearerToken = false
grails.plugin.springsecurity.filterChain.chainMap = [
['/api/**': 'JOINED_FILTERS,-exceptionTranslationFilter,-authenticationProcessingFilter,-securityContextPersistenceFilter'], // Stateless chain
['/data/**': 'JOINED_FILTERS,-exceptionTranslationFilter,-authenticationProcessingFilter,-securityContextPersistenceFilter'], // Stateless chain
['/**': 'JOINED_FILTERS,-restTokenValidationFilter,-restExceptionTranslationFilter'] // Traditional chain
]
grails.plugin.springsecurity.interceptUrlMap = [
[pattern: '/', access: ['permitAll']],
[pattern: '/assets/**', access: ['permitAll']],
[pattern: '/partials/**', access: ['permitAll']],
[pattern: '/**/js/**', access: ['permitAll']],
[pattern: '/**/css/**', access: ['permitAll']],
[pattern: '/**/images/**', access: ['permitAll']],
[pattern: '/**/favicon.ico', access: ['permitAll']],
[pattern: '/api/login', access: ['permitAll']],
[pattern: '/api/logout', access: ['isFullyAuthenticated()']],
[pattern: '/api/validate', access: ['isFullyAuthenticated()']],
[pattern: '/**', access: ['isFullyAuthenticated()']]
]
resources.groovy
import ras.bean.DefaultSecurityEventListener
import ras.auth.DefaultJsonPayloadCredentialsExtractor
beans = {
credentialsExtractor(DefaultJsonPayloadCredentialsExtractor)
defaultSecurityEventListener(DefaultSecurityEventListener)
}
grails version:
$ grails --version
| Grails Version: 3.2.6
| Groovy Version: 2.4.7
| JVM Version: 1.8.0_121
UPDATE 1
I have added following lines to logback.groovy
logger("org.springframework.security", DEBUG, ['STDOUT'], false)
logger("grails.plugin.springsecurity", DEBUG, ['STDOUT'], false)
logger("org.pac4j", DEBUG, ['STDOUT'], false)
Yet, the console output and stacktrace.log file have the same output as posted above
I would really appreciate any suggestions on how to fix this error.
Finally, I was able to fix the problem:
Issue 1:
I created User Role and UserRole classes manually instead of using
grails s2-quickstart com.app-name User Role
as described here
Issue 2:
I used the wrong format for chainMap filters. Here is the one that worked for me
grails.plugin.springsecurity.filterChain.chainMap = [
[pattern: '/assets/**', filters: 'none'],
[pattern: '/**/js/**', filters: 'none'],
[pattern: '/**/css/**', filters: 'none'],
[pattern: '/**/images/**', filters: 'none'],
[pattern: '/**/favicon.ico', filters: 'none'],
[pattern: '/api/**', filters: 'JOINED_FILTERS,-exceptionTranslationFilter,-authenticationProcessingFilter,-securityContextPersistenceFilter'], // Stateless chain
[pattern: '/data/**', filters: 'JOINED_FILTERS,-exceptionTranslationFilter,-authenticationProcessingFilter,-securityContextPersistenceFilter'], // Stateless chain
[pattern: '/**', filters: 'JOINED_FILTERS,-restTokenValidationFilter,-restExceptionTranslationFilter'] // Traditional chain
]
Field springSecurityService in com.form.application.UserPasswordEncoderListener required a bean of type 'grails.plugin.springsecurity.SpringSecurityService' that could not be found.
Action:
Consider defining a bean of type 'grails.plugin.springsecurity.SpringSecurityService' in your configuration
still getting this issue
Related
SpringBoot: HikariCP: leakDetectionThreshold returns always 0 regardless of set value
I have a simple SpringBoot Application and would like to investigate the issues related to DB connections. For this purpose, I've set leakDetectionThreshold in application.yml: spring: datasource: driver-class-name: org.postgresql.Driver type: com.zaxxer.hikari.HikariDataSource hikari: leak-detection-threshold: 300000 jpa: properties: hibernate: dialect: org.hibernate.dialect.PostgreSQL95Dialect and logging to debug: logging: level: com: zaxxer: hikari: debug And I see the following behaviour: HikariConfig is initialised and correct value is passed to setter public void setLeakDetectionThreshold(long leakDetectionThresholdMs) <-- 300000 However, when HikariPool is initialised - this.leakTaskFactory = new ProxyLeakTaskFactory(config.getLeakDetectionThreshold(), houseKeepingExecutorService); <-- config.getLeakDetectionThreshold() is always 0 The same in poolEntry.createProxyConnection(leakTaskFactory.schedule(poolEntry), now); ProxyLeakTask schedule(final PoolEntry poolEntry) { return (leakDetectionThreshold == 0) ? ProxyLeakTask.NO_LEAK : scheduleNewTask(poolEntry); <-- leakDetectionThreshold is always 0 } So, maybe, someone can help with it? What I'm doing wrong?
Thanks #M. Deinum The issue was quite simple: 2021-04-12 12:51:22.066 WARN 31701 --- [ main] com.zaxxer.hikari.HikariConfig : HikariPool-1 - leakDetectionThreshold is less than 2000ms or more than maxLifetime, disabling it.
spring Vault location [secret/my-application] not resolvable: Not found
I want to connect to the vault server and read my secret in the spring application vault config: spring: application: name: inquiry profiles: active: dev cloud: vault: kv: enabled: true backend: secret profile-separator: '/' application-name: inquiry host: development port: 8200 scheme: https authentication: token token: my-token ssl: trust-store: development-truststore.jks trust-store-password: pass in the vault, I have inquiry policy add attache inquiry token to it vault policy read inquiry path "secret/*" { capabilities = ["read", "list"] } path "secret/data/inquiry/*" { capabilities = ["read", "create", "update"] } curl --header "X-Vault-Token:my-token" -k https://localhost:8200/v1/secret/data/inquiry/dev return my data {"request_id":"35548b9e-3422-201b-6243-a600d7f61fc3","lease_id":"","renewable":false,"lease_duration":0,"data":{"data":{"DBPassword":"pass","DBUser":"user"},"metadata":{"created_time":"2020-07-08T09:02:42.237713857Z","deletion_time":"","destroyed":false,"version":1}},"wrap_info":null,"warnings":null,"auth":null} but in spring I got this error: 2020-07-08 13:55:50.131 INFO 83792 --- [ main] o.s.v.a.LifecycleAwareSessionManager : Scheduling Token renewal 2020-07-08 13:55:50.159 INFO 83792 --- [ main] o.s.v.c.e.LeaseAwareVaultPropertySource : Vault location [secret/inquiry] not resolvable: Not found 2020-07-08 13:55:50.167 INFO 83792 --- [ main] o.s.v.c.e.LeaseAwareVaultPropertySource : Vault location [secret/application/dev] not resolvable: Not found 2020-07-08 13:55:50.174 INFO 83792 --- [ main] o.s.v.c.e.LeaseAwareVaultPropertySource : Vault location [secret/application] not resolvable: Not found 2020-07-08 13:55:50.175 INFO 83792 --- [ main] b.c.PropertySourceBootstrapConfiguration : Located property source: [BootstrapPropertySource {name='bootstrapProperties-secret/inquiry/dev'}, BootstrapPropertySource {name='bootstrapProperties-secret/inquiry'}, BootstrapPropertySource {name='bootstrapProperties-secret/application/dev'}, BootstrapPropertySource {name='bootstrapProperties-secret/application'}] 2020-07-08 13:55:50.181 INFO 83792 --- [ main] i.c.i.sepam.inquiry.InquiryApplication : The following profiles are active: dev I use the jdk14. how can I solve it, thank you
The issue is in your Vault Policy. path "secret/data/inquiry/*" { capabilities = ["read", "create", "update"] } drop the trailing / and just have secret/data/inquiry* Spring is looking for access to a k/v store at inquiry, not in a sub-directory. Spring is requesting access to k/v stores at secret/app-name, secret/application and secret/app-name/spring-active-profile. For each path, it expects a single k/v store that contains all the secrets. I'm assuming this was solved a while ago by the poster, but I ran into this exact same thing when I had someone unfamiliar with spring setting up my app's permissions.
Grails Integration Testing by default creating datasource using H2 instead of datasource config from TEST environment
I have tried everything and every suggestion so far available. Problem: I'm trying to write integration test cases for Grails based application but while running tests it's picking by default H2 db for creating datasource instead of using DB config from Test Environment inside application.yml Command used: grails -Dgrails-env=test tesp-app -integration Version: grails=4.0.1 gorm=7.0.2.RELEASE application.yml --- grails: profile: web codegen: defaultPackage: myApp gorm: autowire: true reactor: # Whether to translate GORM events into Reactor events # Disabled by default for performance reasons events: false info: app: name: "my-grails-app" version: "0.0.10" grailsVersion: '4.0.1' spring: jmx: unique-names: true main: banner-mode: "off" groovy: template: check-template-location: false devtools: restart: additional-exclude: - '*.gsp' - '**/*.gsp' - '*.gson' - '**/*.gson' - 'logback.groovy' - '*.properties' management: endpoints: enabled-by-default: false --- grails: mime: disable: accept: header: userAgents: - Gecko - WebKit - Presto - Trident types: all: '*/*' 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 pdf: application/pdf rss: application/rss+xml text: text/plain hal: - application/hal+json - application/hal+xml xml: - text/xml - application/xml urlmapping: cache: maxsize: 1000 controllers: defaultScope: singleton converters: encoding: UTF-8 views: default: codec: html gsp: encoding: UTF-8 htmlcodec: xml codecs: expression: html scriptlet: html taglib: none staticparts: none management: endpoints: jmx: unique-names: true --- hibernate: cache: queries: false use_second_level_cache: false use_query_cache: false # cache.provider_class: 'org.hibernate.cache.EhCacheProvider' lazy: false max_fetch_depth: '5' environments: development: datasource: pooled: true dbCreate: update driverClassName: 'com.mysql.jdbc.Driver' url: 'jdbc:mysql://127.0.0.1:3306/mysqlDB_dev?useLegacyDatetimeCode=false&serverTimezone=UTC' username: 'root' password: 'root' logSql: true validationQuery: "SELECT 1" test: datasource: pooled: true dbCreate: create-drop driverClassName: 'com.mysql.jdbc.Driver' url: 'jdbc:mysql://127.0.0.1:3306/mysqlDB_test?useLegacyDatetimeCode=false&serverTimezone=UTC' username: 'root' password: 'root' logSql: true production: datasource: pooled: true dbCreate: update driverClassName: 'com.mysql.jdbc.Driver' url: 'jdbc:mysql://127.0.0.1:3306/mysqlDB_prod?useLegacyDatetimeCode=false&serverTimezone=UTC' username: 'xxxxx' password: 'xxxxx' logSql: true validationQuery: "SELECT 1" properties: jmxEnabled: true initialSize: 5 maxActive: 50 minIdle: 5 maxIdle: 25 maxWait: 10000 maxAge: 600000 timeBetweenEvictionRunsMillis: 5000 minEvictableIdleTimeMillis: 60000 validationQuery: SELECT 1 validationQueryTimeout: 3 validationInterval: 15000 testOnBorrow: true testWhileIdle: true testOnReturn: false jdbcInterceptors: ConnectionState defaultTransactionIsolation: 2 # TRANSACTION_READ_COMMITTED
My api/login post gets unauthorized on grails 3 with spring-security
I'm trying to do a Simple Grails RESTFUL API with access_token authorization. I was following an example as it were on a tutorial, but in this case I can't go on because my localhost:8080/api/login url, the one I should use to get the access_token, does not work. I first created my grails 3 api like this: grails create-app --profile rest-api --features hibernate5,json-views,security These are my Security Domain Classes: I did not touch them, they were created by the Spring Security s2-quickstart coopoliova.backend.security User Role command. This is my application.groovy grails.plugin.springsecurity.filterChain.chainMap = [ //Stateless chain [ pattern: '/**', filters: 'JOINED_FILTERS,-anonymousAuthenticationFilter,-exceptionTranslationFilter,-authenticationProcessingFilter,-securityContextPersistenceFilter,-rememberMeAuthenticationFilter' ], //Traditional, stateful chain [ pattern: '/stateful/**', filters: 'JOINED_FILTERS,-restTokenValidationFilter,-restExceptionTranslationFilter' ] ] // Added by the Spring Security Core plugin: grails.plugin.springsecurity.userLookup.userDomainClassName = 'coopoliva.backend.security.User' grails.plugin.springsecurity.userLookup.authorityJoinClassName = 'coopoliva.backend.security.UserRole' grails.plugin.springsecurity.authority.className = 'coopoliva.backend.security.Role' grails.plugin.springsecurity.controllerAnnotations.staticRules = [ [pattern: '/', access: ['permitAll']], [pattern: '/error', access: ['permitAll']], [pattern: '/index', access: ['permitAll']], [pattern: '/index.gsp', access: ['permitAll']], [pattern: '/shutdown', access: ['permitAll']], [pattern: '/assets/**', access: ['permitAll']], [pattern: '/**/js/**', access: ['permitAll']], [pattern: '/**/css/**', access: ['permitAll']], [pattern: '/**/images/**', access: ['permitAll']], [pattern: '/**/favicon.ico', access: ['permitAll']], [pattern: '/api/rest', access: ['permitAll']] ] grails.plugin.springsecurity.filterChain.chainMap = [ [pattern: '/assets/**', filters: 'none'], [pattern: '/**/js/**', filters: 'none'], [pattern: '/**/css/**', filters: 'none'], [pattern: '/**/images/**', filters: 'none'], [pattern: '/**/favicon.ico', filters: 'none'], [pattern: '/**', filters: 'JOINED_FILTERS'] ] So, I create a couple of users on the bootstrap, like this: def init = { servletContext -> def adminUser = new User(username: "adminuser", password: "1234", enabled: true); adminUser.save(flush:true) def userUser = new User(username: "useruser", password: "1234", enabled: true); userUser.save(flush:true) def userRole = Role.findByAuthority("ROLE_USER") ?: new Role("ROLE_USER") def adminRole = Role.findByAuthority("ROLE_ADMIN") ?: new Role("ROLE_ADMIN") userRole.save(flush:true) adminRole.save(flush:true) UserRole.create(adminUser, adminRole) UserRole.create(userUser, userRole) } So, theoretically; if I send a POST request with the credentials username: "useruser",password: "1234", it should work. But, this happens: 401 UNAUTHORIZED! So... why is this happening? I just need the access_token so I can pass it through all my other requests. Thanks in advance!
You need to permit access to your login url [pattern: 'api/login/**', access: ['permitAll']] Also, you have duplicate configuration for grails.plugin.springsecurity.filterChain.chainMap
Found the problem! These passwords: def adminUser = new User(username: "adminuser", password: "1234", enabled: true); adminUser.save(flush:true) def userUser = new User(username: "useruser", password: "1234", enabled: true); userUser.save(flush:true) Are not password encripted by spring security service, and thus, wont be correct when logging in: This is the correct way to add users: def adminUser = new User(username: "adminuser", password: springSecurityService.encodePassword("1234"), enabled: true); adminUser.save(flush:true) def userUser = new User(username: "useruser", password: springSecurityService.encodePassword("1234"), enabled: true); userUser.save(flush:true) Thank you all for your help!
jHipster H2 console not working
I am working on monolithic application in which there are some custom entities . When I access the H2 Console via Administration tab . It causes the app to restart when I click the connect button . I am not able to understand why this is happening . Can anyone help me to figure it out . In logs : DEBUG 971 --- [ Thread-51] com.mydomain.mytable1 : close successful. DEBUG 971 --- [ Thread-51] com.mydomain.mytable2 : close successful. DEBUG 971 --- [ Thread-51] com.mydomain.mytable3 : close successful. . . This is causing an issue to access the database via console although , there is no issue while accessing API . Executing queries also result in localhost refused to connect . I am new to jHipster and H2. Configuration : spring: profiles: active: dev include: swagger devtools: restart: enabled: true livereload: enabled: false # we use gulp + BrowserSync for livereload jackson: serialization.indent_output: true datasource: type: com.zaxxer.hikari.HikariDataSource url: jdbc:h2:file:./target/h2db/db/mydatabase;DB_CLOSE_DELAY=-1 username: frothers password: h2: console: enabled: false jpa: database-platform: io.github.jhipster.domain.util.FixedH2Dialect database: H2 show-sql: true properties: hibernate.id.new_generator_mappings: true hibernate.cache.use_second_level_cache: true hibernate.cache.use_query_cache: false hibernate.generate_statistics: true hibernate.cache.region.factory_class: io.github.jhipster.config.jcache.NoDefaultJCacheRegionFactory
Why disabling the h2 console if you want to access it? h2: console: enabled: false Just turn enabled to true.