spring security core assertion error in grails [duplicate] - spring

I am using grails spring seurity core and very new to this. i am getting following error
Configuring Spring Security Core 1.2.7.3...
... finished configuring Spring Security Core
**| Error 2014-01-10 09:40:36,688 [localhost-startStop-1] ERROR context.GrailsContextLoader - Error initializing the application: Assertion failed:
assert SecUserSecRole.count() == 1
| |
0 false
Message: Assertion failed:
assert SecUserSecRole.count() == 1
| |
0 false**
Line | Method
The BootStrap class is as follows
class **BootStrap** {
def springSecurityService
def init = { servletContext ->
//def userRole= SecRole.findByAuthority("ROLE_USER") ?: new SecRole(authority : "ROLE_USER").save()
//def adminRole= SecRole.findByAuthority("ROLE_ADMIN") ?: new SecRole(authority : "ROLE_ADMIN").save()
def adminRole = new SecRole(authority: 'ROLE_ADMIN').save(flush: true)
def userRole = new SecRole(authority: 'ROLE_USER').save(flush: true)
// def testUser = new SecUser(username: username, enabled: true, password: springSecurityService.encodePassword("password"))
/// testUser.save(flush: true)
//SecUserSecRole.create testUser, adminRole, true
def testUser = new SecUser(username: 'admin', enabled: true, password: 'admin')
testUser.save(flush: true)
SecUserSecRole.create testUser, adminRole, true
assert SecUser.count() == 1
assert SecRole.count() == 2
assert SecUserSecRole.count() == 1
}
def *destroy* = {
}
}

Related

Retrieve #Authorization swagger codegen java

I work with swagger 2.0 to define a back end and trying to define security.
I end up with :
---
swagger: "2.0"
info:
version: 1.0.0
title: Foo test
schemes:
- https
paths:
/foo:
get:
security:
- Foo: []
responses:
200:
description: Ok
securityDefinitions:
Foo:
type: apiKey
name: X-BAR
in: header
Everything good till now, java codegen give me :
#ApiOperation(value = "", nickname = "fooGet", notes = "", authorizations = {
#Authorization(value = "Foo")
}, tags={ })
#ApiResponses(value = {
#ApiResponse(code = 200, message = "Ok") })
#RequestMapping(value = "/foo",
method = RequestMethod.GET)
default ResponseEntity<Void> fooGet() {
if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) {
} else {
log.warn("ObjectMapper or HttpServletRequest not configured in default FooApi interface so no example is generated");
}
return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);
}
I'm wondering, in the interface, how to retrieve "properly" the X-BAR header value.
I end up with :
#Autowired
private HttpServletRequest httpServletRequest;
httpServletRequest.getHeader("X-BAR")
which works , but is there a more proper way ?
Define a class "Foo" ? a doFilter ?
Thanks

Problem with DB container in TestContainers using SpringBootTest

I have an abstract class BaseIntegrationTest that use TestContainers. The problem is when I'm trying to run a simple DB test like UserRepositoryIntSpec I have an exception, which means that count starts from 114, but not from 1 as expected. Why index not starts from 1? Why every time setup is executed my local db user table is clear, since I expect test to be runned in container with container db usage, so only container table will be cleared.
It's definetly should be something easy I just missed or didn't understand. I will be appreciate for help.
For migrations I'm using Flyway, for testing Spock.
Condition not satisfied:
user1.getId() == 1 && user1.getRiskcustomerid() == 1 && user1.getDateCreated() != null
| | | | |
| 114 | false false
| false
BaseIntegrationTest
#ContextConfiguration
#SpringBootTest(webEnvironment = DEFINED_PORT)
#Testcontainers
#Slf4j
abstract class BaseIntegrationTest extends Specification {
protected static PostgreSQLContainer postgres = new PostgreSQLContainer()
.withDatabaseName("db")
.withUsername("root")
.withPassword("root")
def setupSpec() {
startPostgresIfNeeded()
['spring.datasource.url' : postgres.getJdbcUrl(),
'spring.datasource.username': postgres.getUsername(),
'spring.datasource.password': postgres.getPassword()
].each { k, v ->
System.setProperty(k, v)
}
}
private static void startPostgresIfNeeded() {
if (!postgres.isRunning()) {
log.info("[BASE-INTEGRATION-TEST] - Postgres is not started. Running...")
postgres.start()
}
}
def cleanupSpec() {
if (postgres.isRunning()) {
log.info("[BASE-INTEGRATION-TEST] - Stopping Postgres...")
postgres.stop()
}
}
}
UserRepositoryIntSpec
class UserRepositoryIntSpec extends BaseIntegrationTest {
#Autowired
private UserRepository UserRepository
def setup() {
UserRepository.deleteAll()
}
def "FindAll returns all users correctly"() {
given:
List<Integer> friends = [1,2]
User User1 = User.builder()
.riskcustomerid(1)
.possibleids([1000, 1001])
.preferableid(1000)
.totalfriendscount(2)
.friends(friends)
.build()
User User2 = User.builder()
.riskcustomerid(2)
.possibleids([8000, 8001])
.preferableid(8000)
.totalfriendscount(3)
.friends(friends)
.build()
when:
UserRepository.saveAll([User1, User2])
then:
List<User> Users = UserRepository.findAll()
assert Users.size() == 2
User user1 = Users.get(0)
User user2 = Users.get(1)
assert user1.getId() == 1 && user1.getRiskcustomerid() == 1 && user1.getDateCreated() != null
assert user2.getId() == 2 && user2.getRiskcustomerid() == 2 && user2.getDateCreated() != null
}
Application.yml
spring:
datasource:
url: jdbc:postgresql://localhost:5432/db
username: root
password: root
hikari:
connection-timeout: 10000
leak-detection-threshold: 60000
validation-timeout: 30000
connection-test-query: SELECT 1;
jdbc-url: jdbc:postgresql://localhost:5432/db
username: root
password: root
data-source-properties: stringtype=unspecified
maximum-pool-size: 16
max-lifetime: 1800000
transaction-isolation: TRANSACTION_READ_COMMITTED
pool-name: hikari.local
driver-class-name: org.postgresql.Driver
jpa:
hibernate:
ddl-auto: update
flyway:
schemas: schema1
baseline-on-migrate: false
server:
port: 8080
I see that you're using url: jdbc:postgresql://localhost:5432/db. You're literally saying "please run against my local DB" :)
For your use case, I suggest using JDBC-based containers in Testcontainers. It will start the container automatically and destroy it when you close your last connection to it.

Grails Login Not Working

I am using Grails 2.4 with spring security
compile "org.grails.plugins:spring-security-core:2.0.0"
The following is my bootstrap.groovy
import com.aarestu.grailstest.Role
import com.aarestu.grailstest.User
import com.aarestu.grailstest.UserRole
class BootStrap {
def init = { servletContext ->
def user = new User(usernmae: 'user', password: 'user').save(flush: true, failOnError: true)
def userSecond = new User(usernmae: 'user2', password: 'user').save(flush: true, failOnError: true)
def admin = new User(usernmae: 'admin', password: 'admin').save(flush: true, failOnError: true)
def userRole = new Role(authority: 'ROLE_USER').save(flush: true, failOnError: true)
def adminRole = new Role(authority: 'ROLE_ADMIN').save(flush: true, failOnError: true)
new UserRole(user: user, role: userRole).save(flush: true, failOnError: true)
new UserRole(user: admin, role: adminRole).save(flush: true, failOnError: true)
}
def destroy = {
}
}
It created 2 entries into the table Role but none of the others.
I then manually created a user in the database and when I try to login with the user it simply doesnt work even though I can view it in the database.
If the
failOnError:true
Is not included then it runs ok but I cannot login, if it is included I get the error included at the very end
I also accounted for the double encoding by modifying my USER controller to include the following
boolean beforeInsertRunOnce = false
boolean beforeUpdateRunOnce = false
Set<Role> getAuthorities() {
UserRole.findAllByUser(this)*.role
}
def beforeInsert() {
if (! beforeInsertRunOnce) {
beforeInsertRunOnce = true
encodePassword()
}
}
def afterInsert() {
beforeInsertRunOnce = false
}
def beforeUpdate() {
if (isDirty('password') && ! beforeUpdateRunOnce ) {
beforeUpdateRunOnce = true
encodePassword()
}
}
def afterUpdate() {
beforeUpdateRunOnce = false
}
Error
Error |
2016-02-09 11:42:58,434 [localhost-startStop-1] ERROR context.GrailsContextLoaderListener - Error initializing the application: Validation Error(s) occurred during save():
- Field error in object 'com.aarestu.grailstest.User' on field 'username': rejected value [null]; codes [com.aarestu.grailstest.User.username.nullable.error.com.aarestu.grailstest.User.username,com.aarestu.grailstest.User.username.nullable.error.username,com .aarestu.grailstest.User.username.nullable.error.java.lang.String,com.aarestu .grailstest.User.username.nullable.error,user.username.nullable.error.com.aar estu.grailstest.User.username,user.username.nullable.error.username,user.user name.nullable.error.java.lang.String,user.username.nullable.error,com.aarestu .grailstest.User.username.nullable.com.aarestu.grailstest.User.username,com.aarestu.grailstest.User.username.nullable.username,com.aarestu.grailstest.User.username.nullable.java.lang.String,com.aarestu.grailstest.User.username.nullable,user.username.nullable.com.aarestu.grailstest.User.username,user.username.nullable.username,user.username.nullable.java.lang.String,user.username.nullable,nullable.com.aarestu.grailstest.User.username,nullable.username,nullable.java.lang.String,nullable]; arguments [username,class com.aarestu.grailstest.User]; default message [Property [{0}] of class [{1}] cannot be null]
Message: Validation Error(s) occurred during save():
- Field error in object 'com.aarestu.grailstest.User' on field 'username': rejected value [null]; codes [com.aarestu.grailstest.User.username.nullable.error.com.aarestu.grailstest.User.username,com.aarestu.grailstest.User.username.nullable.error.username,com .aarestu.grailstest.User.username.nullable.error.java.lang.String,com.aarestu .grailstest.User.username.nullable.error,user.username.nullable.error.com.aarestu.grailstest.User.username,user.username.nullable.error.username,user.username.nullable.error.java.lang.String,user.username.nullable.error,com.aarestu .grailstest.User.username.nullable.com.aarestu.grailstest.User.username,com.aarestu.grailstest.User.username.nullable.username,com.aarestu.grailstest.User .username.nullable.java.lang.String,com.aarestu.grailstest.User.username.nullable,user.username.nullable.com.aarestu.grailstest.User.username,user.username.nullable.username,user.username.nullable.java.lang.String,user.username.nullable,nullable.com.aarestu.grailstest.User.username,nullable.username,nullable.java.lang.String,nullable]; arguments [username,class com.aarestu.grailstest.User]; default message [Property [{0}] of class [{1}] cannot be null]
Line | Method
->> 9 | doCall in BootStrap$_closure1
| 327 | evaluateEnvironmentSpecificBlock in grails.util.Environment
| 320 | executeForEnvironment . . . . . in ''
| 296 | executeForCurrentEnvironment in ''
| 266 | run . . . . . . . . . . . . . . in java.util.concurrent.FutureTask
| 1142 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 617 | run . . . . . . . . . . . . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 745 | run in java.lang.Thread
Error |
Forked Grails VM exited with error
Any help or point in the right direction would be much appreciated
The bootsrap.groovy code was wrong
This following needs to be changed from
def user = new User(usernmae: 'user', password: 'user').save(flush: true, failOnError: true)
def admin = new User(usernmae: 'admin', password: 'admin').save(flush: true, failOnError: true)
Role(user: user, role: userRole).save(flush: true, failOnError: true)
new UserRole(user: admin, role: adminRole).save(flush: true, failOnError: true)
to
def user = new User(username: 'user', password: 'password', enabled: true).save()
def admin = new User(username: 'admin', password: 'password', enabled: true).save()
UserRole.create user, roleUser
UserRole.create admin, roleUser
UserRole.create admin, roleAdmin, true

ValidationException on Update: Validation error whilst flushing entity on AbstractPersistenceEventListener

In my environment, i have grails.gorm.failOnError = true on Config.groovy.
package org.example
class Book {
String title
String author
String email
static constraints = {
title nullable: false, blank: false
email nullable: false, blank: false, unique: true //apparently this is the problem..
}
}
And, on controller, i have:
package org.example
class BookController {
def update() {
def bookInstance = Book.get(params.id)
if (!bookInstance) {
flash.message = message(code: 'default.not.found.message', args: [message(code: 'book.label', default: 'Book'), params.id])
redirect(action: "list")
return
}
if (params.version) {
def version = params.version.toLong()
if (bookInstance.version > version) {
bookInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
[message(code: 'book.label', default: 'Book')] as Object[],
"Another user has updated this Book while you were editing")
render(view: "edit", model: [bookInstance: bookInstance])
return
}
}
bookInstance.properties = params
bookInstance.validate()
if(bookInstance.hasErrors()) {
render(view: "edit", model: [bookInstance: bookInstance])
} else {
bookInstance.save(flush: true)
flash.message = message(code: 'default.updated.message', args: [message(code: 'book.label', default: 'Book'), bookInstance.id])
redirect(action: "show", id: bookInstance.id)
}
}
}
To save, it's ok. But, when updating without set the title field, i get:
Message: Validation error whilst flushing entity [org.example.Book]:
- Field error in object 'org.example.Book' on field 'title': rejected value []; codes [org.example.Book.title.blank.error.org.example.Book.title,org.example.Book.title.blank.error.title,org.example.Book.title.blank.error.java.lang.String,org.example.Book.title.blank.error,book.title.blank.error.org.example.Book.title,book.title.blank.error.title,book.title.blank.error.java.lang.String,book.title.blank.error,org.example.Book.title.blank.org.example.Book.title,org.example.Book.title.blank.title,org.example.Book.title.blank.java.lang.String,org.example.Book.title.blank,book.title.blank.org.example.Book.title,book.title.blank.title,book.title.blank.java.lang.String,book.title.blank,blank.org.example.Book.title,blank.title,blank.java.lang.String,blank]; arguments [title,class org.example.Book]; default message [Property [{0}] of class [{1}] cannot be blank]
Line | Method
->> 46 | onApplicationEvent in org.grails.datastore.mapping.engine.event.AbstractPersistenceEventListener
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 895 | runTask in java.util.concurrent.ThreadPoolExecutor$Worker
| 918 | run . . . . . . . in ''
^ 680 | run in java.lang.Thread
At q I understand it, the problem occurs when the flush hibernate session, hibernate tries to save the object again then the exception is thrown...
When trying to save the object again, is called the book.validate () again, which makes a new query in the database to ensure the uniqueness of the email field. Right now, the Validation Exception is thrown.
But, when i removed the unique validation of email property, the update is performed normally..
My question is: This behavior is correct? Hibernate calls book.save automatically?
This is the sample project, and the steps to simulate the error are:
source: https://github.com/roalcantara/grails_app_validation_exception
grails run-app
navigate to http:// localhost: 8080/ book/book/create
create an new instance filling all fields..
then edit this instance, in: http:// localhost: 8080/ book/book/edit/1
finally, drop the 'Title' field and click on Update, then the exception is thrown..
In my environment, this behavior has occurred on grails version 2.0.3 and 2.2.1
Thanks for any help! And sorry by my poor (and shame) english.. rs..
You are essentially validating twice, first with:
bookInstance.validate()
and second with:
bookInstance.save(flush: true)
When you call bookInstance.save(flush: true) a boolean is returned. Grails takes advantage of this by default when a controller is generated, but it appears you have changed the controller Grails generated by default for some reason.
Just replace this:
bookInstance.validate()
if(bookInstance.hasErrors()) {
render(view: "edit", model: [bookInstance: bookInstance])
} else {
bookInstance.save(flush: true)
flash.message = message(code: 'default.updated.message', args: [message(code: 'book.label', default: 'Book'), bookInstance.id])
redirect(action: "show", id: bookInstance.id)
}
With this:
if( !bookInstance.save( flush: true ) ) {
render(view: "edit", model: [bookInstance: bookInstance])
return
}

Sorry, we were not able to find a user with that username and password

I installed the Spring Security core plug-in 1.2.7.3 on Grails 2.1.1, ran the s2-quickstart command, and then initialized the initial user and roles in the bootstrap.groovy, but I still cannot login. Text of the relevant piece of BootStrap.groovy follows:
if (SecRole.count == 0) {
def fUserRole = SecRole.findByAuthority('ROLE_FlowUser') ?: new SecRole(authority: 'ROLE_FlowUser').save(failOnError: true, flush: true)
def fAdminRole = SecRole.findByAuthority('ROLE_FlowAdmin') ?: new SecRole(authority: 'ROLE_FlowAdmin').save(failOnError: true, flush: true)
def bf = SecUser.findByUsername('bill') ?: new SecUser(
username: 'bill',
password: 'eagle',
firstName: 'bill',
lastName: 'fly',
email: 'bill.fly#baylorhealth.edu',
accountExpired: false,
accountLocked: false,
passwordExpired: false,
enabled: true
).save(failOnError: true, flush: true)
if (!bf.authorities.contains(fAdminRole)) {
SecUserSecRole.create bf, fAdminRole, true
}
if (!bf.authorities.contains(fUserRole)) {
SecUserSecRole.create bf, fUserRole, true
}
}
I am not encrypting the password in bootstrap, as seems to be the answer to most of the questions of this type. All four records are getting written to the database tables, but of course, I cannot tell if the password is encrypted correctly. My initial controller has the following annotation ahead of the class statement:
#Secured(['IS_AUTHENTICATED_FULLY'])
Also, I added the following to the config.groovy:
// Added by the Spring Security Core plugin:
grails.plugins.springsecurity.userLookup.userDomainClassName = 'cocktail.SecUser'
grails.plugins.springsecurity.userLookup.authorityJoinClassName = 'cocktail.SecUserSecRole'
grails.plugins.springsecurity.authority.className = 'cocktail.SecRole'
grails.plugins.springsecurity.password.algorithm = 'SHA-256'
Your password may be encoded two times (problem may occure if you are using multi datasources).
Try this :
class User {
...
transient bEncoded = false
...
protected void encodePassword() {
if (!bEncoded ) {
password = springSecurityService.encodePassword(password);
bEncoded = true;
}
}
}
My guess is the authorities.contains check is failing because of missing hashCode and equals methods in your role class. But if there are no roles (your 1st check) then the user wouldn't have any granted, so you can just remove those checks:
SecUserSecRole.create bf, fAdminRole, true
SecUserSecRole.create bf, fUserRole, true
If that doesn't fix it, it's most likely a password encoding issue - add debug logging for Spring Security and it should show you why it's failing; add debug 'org.springframework.security' in your log4j block in Config.groovy
p.s. if (SecRole.count == 0) { should be if (SecRole.count() == 0) { or just if (!SecRole.count()) {

Resources