Spring Security Grails Spring安全性默认配置:如何定义默认用户和密码

d6kp6zgx  于 2023-02-04  发布在  Spring
关注(0)|答案(5)|浏览(169)

在纯净的Spring我可以这样做

<security:authentication-manager>
<security:authentication-provider user-service-ref="customUserDetailsService">       
    <security:password-encoder ref="passwordEncoder"/>
</security:authentication-provider>
<security:authentication-provider>
    <security:user-service>
        <security:user name="admin" password="admin" authorities="ROLE_USER, ROLE_ADMIN" />
    </security:user-service>

有没有办法在Grails中使用Spring Security插件做同样的事情?
我可以实现自己的身份验证提供,但在本例中,我将把凭据硬编码存储在类中。

acruukt9

acruukt91#

您可以使用InMemoryUserDetailsManager(在resources.groovy中)来完成此操作:

import org.springframework.security.provisioning.InMemoryUserDetailsManager
import org.springframework.security.core.userdetails.User
import org.springframework.security.core.authority.SimpleGrantedAuthority

beans = {
    userDetailsService(InMemoryUserDetailsManager,
            [new User('admin', 'password hash', [new SimpleGrantedAuthority('ROLE_ADMIN')])])
}
lnvxswe2

lnvxswe22#

这通常是在BootStrap.groovy中完成的,例如

import com.foo.Role
import com.foo.User
import com.foo.UserRole

class BootStrap {

   def init = {
      def userRole = Role.findOrSaveByAuthority('ROLE_USER')
      def adminRole = Role.findOrSaveByAuthority('ROLE_ADMIN')

      if (!User.findByUsername('admin')) {
         def admin = new User(username: 'admin', password: 'admin').save()

         UserRole.create admin, userRole
         UserRole.create admin, adminRole

         User.withSession { it.flush() }
      }
   }
}
ymzxtsji

ymzxtsji3#

This link包含一个示例,您可以利用InMemoryUserDetailsManagerBooStrap.groovy创建用户。
下面是BootStrap.groovy中的内容(在本例中,我从环境变量加载密码):

import org.springframework.security.provisioning.UserDetailsManager
import org.springframework.security.core.authority.SimpleGrantedAuthority
import org.springframework.security.core.userdetails.User
import org.springframework.security.core.userdetails.UserDetails

class BootStrap {

    UserDetailsManager userDetailsService

    def init = { servletContext ->

        UserDetails user1 = new User('user1', "${System.getenv("USER1_PWD")}", [new SimpleGrantedAuthority('ROLE_USER')])
        userDetailsService.createUser(user1)

        UserDetails user2 = new User('user2', "${System.getenv("USER2_PWD")}", [new SimpleGrantedAuthority('ROLE_USER')])
        userDetailsService.createUser(user2)

    }
    def destroy = {
    }
}

这是我的resources.groovy

import org.springframework.security.provisioning.InMemoryUserDetailsManager
import org.springframework.security.authentication.encoding.PlaintextPasswordEncoder

beans = {

    userDetailsService(InMemoryUserDetailsManager,[])
    passwordEncoder(PlaintextPasswordEncoder)
}
ldfqzlk8

ldfqzlk84#

使用我们的DomainService实现引导“默认”用户(见下文)
import grails.gorm.transactions.Transactional
import org.grails.datastore.gorm.GormEntity
import java.util.function.Supplier
class DomainService {

@Transactional
<T extends GormEntity> T createIfNotExists(Supplier<T> existingFinder, Supplier<T> newInstance) {
    T model = existingFinder.get()
    if (!model) {
        model = newInstance.get()
        model.save()
    }
    model
}

}
class BootStrap {

def grailsApplication

def domainService

def init = { servletContext ->

    log.info 'BOOTSTRAPPING start'

    createSuperAdminIfNotExist()

    log.info 'BOOTSTRAPPING end'

}

def destroy = {
}

void createSuperAdminIfNotExist() {
    def superAdminProperties = grailsApplication.config.academy.user.super_admin

    domainService.createIfNotExists({ AcademyAdmin.findByEmail(superAdminProperties.email) },
            {
                new AcademyAdmin(
                        createdOn: new Date(),
                        name     : superAdminProperties.name,
                        surname  : superAdminProperties.surname,
                        email    : superAdminProperties.email,
                        password : superAdminProperties.password,
                        passwordConfirm: superAdminProperties.password
                )
            })
}

}

643ylb08

643ylb085#

您可以使用Grails Spring Security提供的这些自定义标记。

<sec:ifLoggedIn>
<li><a><sec:username /></a></li>
<li><g:link controller="logout">Logout</g:link></li>
</sec:ifLoggedIn>
<sec:ifNotLoggedIn>
<li><g:link controller='controller' action='action'>Login</g:link></li>
<li><g:link controller="controller" action="action">Signup</g:link></li>
</sec:ifNotLoggedIn>

相关问题