Springセキュリティ:ログインイベントリスナーの成功時の追加”

StackOverflow https://stackoverflow.com/questions/182160

  •  05-07-2019
  •  | 
  •  

質問

Spring Securityは初めてです。ユーザーが正常にログインしたときに呼び出されるイベントリスナーを追加するにはどうすればよいですか?また、このリスナーで何らかの種類の一意のセッションIDを取得する必要があります。別のサーバーと同期するにはこのIDが必要です。

役に立ちましたか?

解決

ApplicationListener

次に、コードで次のようにします:

public void onApplicationEvent(ApplicationEvent appEvent)
{
    if (appEvent instanceof AuthenticationSuccessEvent)
    {
        AuthenticationSuccessEvent event = (AuthenticationSuccessEvent) appEvent;
        UserDetails userDetails = (UserDetails) event.getAuthentication().getPrincipal();

        // ....
    }
}

その後、applicationContext.xmlファイルでそのBeanを定義するだけで、イベントの受信が自動的に開始されます:)

他のヒント

AuthenticationSuccessEventの問題は、remember-meログインで公開されないことです。 remember-me認証を使用している場合は、代わりにInteractiveAuthenticationSuccessEventを使用してください。通常のログインとremember-meログインの両方で機能します。

@Component
public class LoginListener implements ApplicationListener<InteractiveAuthenticationSuccessEvent> {

    @Override
    public void onApplicationEvent(InteractiveAuthenticationSuccessEvent event)
    {
        UserDetails userDetails = (UserDetails) event.getAuthentication().getPrincipal();
        // ...
    }
}

Phillの回答に似ていますが、ジェネリックを考慮に入れるように修正されました:

public class AuthenticationListener implements ApplicationListener<AuthenticationSuccessEvent> {

  @Override
  public void onApplicationEvent(final AuthenticationSuccessEvent event) {

      // ...

  }

}

Grailsでは、Spring Securityプラグインを使用して、Config.groovyでこれを実行できます。

grails.plugins.springsecurity.useSecurityEventListener = true

grails.plugins.springsecurity.onAuthenticationSuccessEvent = { e, appCtx ->

        def session = SecurityRequestHolder.request.getSession(false)
        session.myVar = true

}

@EventListener

を使用する別の方法
@EventListener
public void doSomething(InteractiveAuthenticationSuccessEvent event) { // any spring event
    // your code 

}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top