请求地图将我引导到Grails中的登录页面 [英] Request map direct me to Login page in Grails

查看:130
本文介绍了请求地图将我引导到Grails中的登录页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Grails 3.10和spring-security-core插件创建一个网站。
我对此很新颖。我生成我的所有域类,然后运行该应用程序。
它引导我登录页面。这实际上是一件好事,但现在如何才能解决这个问题,并能看到我的其他控制者和观点。我读了一些博客。我想写一些代码,如

pre $ import $ org.codehaus.groovy.grails.plugins.springsecurity.Secured
类SecureAnnotatedController {

@Secured(['ROLE_ADMIN'])
def index = {
'您有ROLE_ADMIN'
}

@ Secured(['ROLE_ADMIN','ROLE_ADMIN2'])
def adminEither = {
渲染'您有ROLE_ADMIN或ROLE_ADMIN2'
}

def anybody = {
render'any people can see this'
}
}

但是我无法理解。感谢您的帮助。

解决方案

  import grails.plugin.springsecurity.annotation.Secured 
class SecureAnnotatedController {

@Secured(['ROLE_ADMIN'])
def index(){
render text:'您有ROLE_ADMIN'
}

@Secured(['ROLE_ADMIN','ROLE_ADMIN2'])
def adminEither(){
渲染文本:'您有ROLE_ADMIN或ROLE_ADMIN2'
}

def anybody(){
render text:'anybody can see this'
}
}

Burt指出你正在使用旧的控制器方法和一个旧的Secured import



除此之外:



查看grails-app / conf / application.groov:

  grails.plugin.springsecurity.controllerAnnotations.staticRules = [
[pattern:'/',access:['permitAll']],
[pattern:'/ error',acces s:['permitAll']],
[pattern:'/ SecureAnnotatedController / anybody',access:['permitAll']],
[pattern:'/ index / **',access:[ 'permitAll']],

在上面我直接添加/ SecureAnnotatedController /任何人,如果你有你可以不用更新applucation.groovy,而使用 @Secured(['permitAll' ])上面的方法。

上面的

应该使你所需要的工作。下面是更先进的,包括锁定失败的尝试
这是一个伟大的插件,需要时间来吸收它的微妙细节。



关于上述帖子:

  // grails.plugin.springsecurity.successHandler.defaultTargetUrl =/ helloAgain / $ {System.currentTimeMillis()} 
//grails.plugins.springsecurity.useSecurityEventListener = true

grails.plugin.springsecurity.successHandler.alwaysUseDefault = true
grails.plugin.springsecurity.useRoleGroups = true


brutforce {
loginAttempts {
time = 5
allowedNumberOfAttempts = 3
}
}

我原来打算用helloAgain做一次重定向,但此时注册入站用户的方式很糟糕。现在我正在使用

  grails.plugin.springsecurity.useSecurityEventListener = true 

然后输入grails-app / conf / spring / resources.groovy

  import myapp.utils.CustomSecurityEventListener 
import myapp.utils.CustomSecurityFailureEventListener
import myapp.utils.RedirectFailureToRegistration
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler

//将您的Spring DSL代码放在这里
beans = {
redirectFailureHandlerExample(SimpleUrlAuthenticationFailureHandler){
defaultFailureUrl ='/ failed'
}

redirectFailureHandler(RedirectFailureToRegistration){
defaultFailureUrl ='/ failed'
registrationUrl ='/'
}
/ *
multipartResolver(ContentLengthAwareCommonsMultipartResolver){
defaultEncoding ='UTF-8'
}
* /
customerSecurityEventListener(CustomSecurityEventListener)
customSecurityFailureEventListener(CustomSecurityFailureEventListener)

现在这些文件:在我的src / main / groovy / myapp / utils中我有

  package myapp.utils 

import grails.util.Holders
import org.springframework.context.ApplicationListener
import org.springframework.security.authentication.event.AuthenticationSuccessEvent
import org.springframework.security.core.userdetails.UserDetails

类CustomSecurityEventListener实现ApplicationListener< AuthenticationSuccessEvent> {
// private static Collection activeUsers = Collections.synchronizedList(new ArrayList())
def loginAttemptCacheService = Holders.grailsApplication.mainContext.getBean('loginAttemptCacheService')

void onApplicationEvent (AuthenticationSuccessEvent event){
def userDetails =(UserDetails)event.getAuthentication()。getPrincipal()
if(userDetails){
//SessionListener.userLoggedIn(userDetails.getUsername())
loginAttemptCacheService.loginSuccess(event.authentication.name)
}
}
// public static Collection getActiveUsers(){
// return Collections.unmodifiableList(activeUsers)
//}

}


软件包myapp.utils

导入myapp.users.LoginAttemptCacheService
导入grails.util.Holders
import org.springframework.context.ApplicationListener
import org.springframework.security.authentication.event.Authenticati onFailureBadCredentialsEvent

类CustomSecurityFailureEventListener实现ApplicationListener< AuthenticationFailureBadCredentialsEvent> {
$ b $ def loginAttemptCacheService = Holders.grailsApplication.mainContext.getBean('loginAttemptCacheService')

void onApplicationEvent(AuthenticationFailureBadCredentialsEvent event){
String username =(String)event .getAuthentication()。getPrincipal()
if(username){
loginAttemptCacheService.failLogin(event.authentication.name)
}
}

}

服务:

  import com.google.common.cache.CacheBuilder 
import com.google.common.cache.CacheLoader
import com.google.common.cache.LoadingCache
import grails .core.GrailsApplication
import grails.core.support.GrailsApplicationAware
import grails.transaction.Transactional

import java.util.concurrent.TimeUnit
import org.apache .commons.lang.math.NumberUtils
import javax.annotation.PostConstruct

LoginAttemptCacheService implements Gra ilsApplicationAware {
def config
GrailsApplication grailsApplication
Private LoadingCache尝试
private int allowedNumberOfAttempts


@PostConstruct
void init() {
allowedNumberOfAttempts = config.brutforce.loginAttempts.allowedNumberOfAttempts
int time = config.brutforce.loginAttempts.time
log.info为$ time分钟配置的帐户块
attempts = CacheBuilder.newBuilder()
.expireAfterWrite(time,TimeUnit.MINUTES)
.build({0} as CacheLoader);
}

/ **
*每个不成功登录尝试触发并增加本地累加器尝试次数
* @param登录名 - 正在尝试登录的用户名
* @return
* /
def failLogin(String login){
def numberOfAttempts = attempts.get(login)
log.debugfail login $ login previous编号为$ numberOfAttempts
numberOfAttempts ++
if(numberOfAttempts> allowedNumberOfAttempts){
blockUser(login)
attempts.invalidate(login)
} else {
trys.put(login,numberOfAttempts)
}
}

/ **
*每次成功登录尝试时触发并重置本地累加器尝试次数
* @param login - 登录的用户名
* /
def loginSuccess(字符串登录){
log.debug$登录成功登录
尝试pts.invalidate(登录)
}

/ **
*禁用用户帐户,因此无法登录
* @param登录 - 必须输入用户名被禁用
* /
@Transactional
private void blockUser(String login){
log.debug阻止用户:$ login
def user = User.findByUsername (登录)
if(user){
user.accountLocked = true
user.save(flush:true)
}
}

void setGrailsApplication(GrailsApplication ga){
config = ga.config
}
}

对于所有那些很酷的工作,你需要将它添加到你的build.gradle中。

  / /缓存用户失败尝试//CustomerSecurityFailureEventListener.groovy 
编译'com.google.guava:guava:11.0.1'

享受

I'm trying to make a website using Grails 3.10 and the spring-security-core plugin. I am so new on that. I genereate my all domain classses then run the application. And it direct me to login page. This is a good thing actually but for now how can get through this and can see my other controlers and views. I read some blogs. I guess write some codes like

import org.codehaus.groovy.grails.plugins.springsecurity.Secured
class SecureAnnotatedController {

  @Secured(['ROLE_ADMIN'])
  def index = {
    render 'you have ROLE_ADMIN'
   }

  @Secured(['ROLE_ADMIN', 'ROLE_ADMIN2'])
  def adminEither = {
     render 'you have ROLE_ADMIN or ROLE_ADMIN2'
   }

   def anybody = {
     render 'anyone can see this'
    }
  }

but I could not understand. Thanks for any help.

解决方案

import grails.plugin.springsecurity.annotation.Secured
class SecureAnnotatedController {

  @Secured(['ROLE_ADMIN'])
  def index() {
    render text: 'you have ROLE_ADMIN'
   }

  @Secured(['ROLE_ADMIN', 'ROLE_ADMIN2'])
  def adminEither() { 
     render text: 'you have ROLE_ADMIN or ROLE_ADMIN2'
   }

   def anybody () { 
     render text: 'anyone can see this'
    }
  }

As Burt has pointed out you are using old controller methods and an old Secured import

Beyond this:

Take a look at grails-app/conf/application.groov:

grails.plugin.springsecurity.controllerAnnotations.staticRules = [
        [pattern: '/',               access: ['permitAll']],
        [pattern: '/error',          access: ['permitAll']],
        [pattern: '/SecureAnnotatedController/anybody',          access: ['permitAll']],
        [pattern: '/index/**',          access: ['permitAll']],

In above I have directly added /SecureAnnotatedController/anybody if you have that in the midst of the existing default values then it should work.

You could also instead of updating applucation.groovy use @Secured(['permitAll']) above the method.

above should make what you need work. Below is more advanced and covers locking failed attempts This is a great plugin and needs time to absorb its delicate details.

In regards to above posts:

//grails.plugin.springsecurity.successHandler.defaultTargetUrl = "/helloAgain/${System.currentTimeMillis()}"
//grails.plugins.springsecurity.useSecurityEventListener = true

grails.plugin.springsecurity.successHandler.alwaysUseDefault = true
grails.plugin.springsecurity.useRoleGroups = true


brutforce {
    loginAttempts {
        time = 5
        allowedNumberOfAttempts = 3
    }
}

I originally had it going to helloAgain which did a redirect but at this point was a hackish way of registering the incoming user. Now I am using

grails.plugin.springsecurity.useSecurityEventListener = true

Which then feeds into grails-app/conf/spring/resources.groovy

import myapp.utils.CustomSecurityEventListener
import myapp.utils.CustomSecurityFailureEventListener
import myapp.utils.RedirectFailureToRegistration
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler

// Place your Spring DSL code here
beans = {
    redirectFailureHandlerExample(SimpleUrlAuthenticationFailureHandler) {
        defaultFailureUrl = '/failed'
    }

    redirectFailureHandler(RedirectFailureToRegistration) {
        defaultFailureUrl = '/failed'
        registrationUrl = '/'
    }
    /*
    multipartResolver(ContentLengthAwareCommonsMultipartResolver) {
        defaultEncoding = 'UTF-8'
    }
    */
    customerSecurityEventListener(CustomSecurityEventListener)
    customSecurityFailureEventListener(CustomSecurityFailureEventListener)

Now these files: in my src/main/groovy/myapp/utils I have

package myapp.utils

import grails.util.Holders
import org.springframework.context.ApplicationListener
import org.springframework.security.authentication.event.AuthenticationSuccessEvent
import org.springframework.security.core.userdetails.UserDetails

class CustomSecurityEventListener implements ApplicationListener<AuthenticationSuccessEvent> {
    //private static Collection activeUsers = Collections.synchronizedList(new ArrayList())
    def loginAttemptCacheService = Holders.grailsApplication.mainContext.getBean('loginAttemptCacheService')

    void onApplicationEvent(AuthenticationSuccessEvent event) {
        def userDetails = (UserDetails) event.getAuthentication().getPrincipal()
        if (userDetails) {
            //SessionListener.userLoggedIn(userDetails.getUsername())
            loginAttemptCacheService.loginSuccess(event.authentication.name)
        }
    }
    // public static Collection getActiveUsers() {
    //     return Collections.unmodifiableList(activeUsers)
    //  }

}


package myapp.utils

import myapp.users.LoginAttemptCacheService
import grails.util.Holders
import org.springframework.context.ApplicationListener
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent

class CustomSecurityFailureEventListener implements ApplicationListener<AuthenticationFailureBadCredentialsEvent> {

    def loginAttemptCacheService = Holders.grailsApplication.mainContext.getBean('loginAttemptCacheService')

    void onApplicationEvent(AuthenticationFailureBadCredentialsEvent event) {
        String username = (String) event.getAuthentication().getPrincipal()
        if (username) {
            loginAttemptCacheService.failLogin(event.authentication.name)
        }
    }

}

The service:

import com.google.common.cache.CacheBuilder
import com.google.common.cache.CacheLoader
import com.google.common.cache.LoadingCache
import grails.core.GrailsApplication
import grails.core.support.GrailsApplicationAware
import grails.transaction.Transactional

import java.util.concurrent.TimeUnit
import org.apache.commons.lang.math.NumberUtils
import javax.annotation.PostConstruct

class LoginAttemptCacheService implements GrailsApplicationAware {
    def config
    GrailsApplication grailsApplication
    private LoadingCache attempts
    private int allowedNumberOfAttempts


    @PostConstruct
    void init() {
        allowedNumberOfAttempts = config.brutforce.loginAttempts.allowedNumberOfAttempts
        int time = config.brutforce.loginAttempts.time
        log.info "account block configured for $time minutes"
        attempts = CacheBuilder.newBuilder()
                .expireAfterWrite(time, TimeUnit.MINUTES)
                .build({0} as CacheLoader);
    }

    /**
     * Triggers on each unsuccessful login attempt and increases number of attempts in local accumulator
     * @param login - username which is trying to login
     * @return
     */
    def failLogin(String login) {
        def numberOfAttempts = attempts.get(login)
        log.debug "fail login $login previous number for attempts $numberOfAttempts"
        numberOfAttempts++
        if (numberOfAttempts > allowedNumberOfAttempts) {
            blockUser(login)
            attempts.invalidate(login)
        } else {
            attempts.put(login, numberOfAttempts)
        }
    }

    /**
     * Triggers on each successful login attempt and resets number of attempts in local accumulator
     * @param login - username which is login
     */
    def loginSuccess(String login) {
        log.debug "successfull login for $login"
        attempts.invalidate(login)
    }

    /**
     * Disable user account so it would not able to login
     * @param login - username that has to be disabled
     */
    @Transactional
    private void blockUser(String login) {
        log.debug "blocking user: $login"
            def user = User.findByUsername(login)
            if (user) {
                user.accountLocked = true
                user.save(flush: true)
            }
    }

    void setGrailsApplication(GrailsApplication ga) {
        config = ga.config
    }
}

For all that cool stuff to work you will need to also add this to your build.gradle

//caching user failure attempts //CustomerSecurityFailureEventListener.groovy
    compile 'com.google.guava:guava:11.0.1'

Enjoy

这篇关于请求地图将我引导到Grails中的登录页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆