如何在Spring中模拟使用SwitchUserFilter的用

如何在Spring中模拟使用SwitchUserFilter的用

本文介绍了如何在Spring中模拟使用SwitchUserFilter的用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不了解Spring模拟用户.

I do not have knowledge on Spring Impersonating user.

我经历了一些用于模拟用户的配置示例代码,并注意到SwitchUserFilter用于此实现.

I have gone through some sample code of configuration for impersonating user and noticed that SwitchUserFilter is used for this implementation.

如何使用Spring SwitchUserFilter Filter实现模拟用户,它如何工作?冒充用户的内部流程是什么?

How to implement impersonate user using Spring SwitchUserFilter Filter and how does it works ?What is the internal flow of impersonating user ?

在我的应用程序中,我也在使用spring安全性.

In my application I am using spring security also.

任何人都可以通过简单的描述或任何示例示例来帮助我实现这一目标吗?

Can anyone please help me with simple description or any sample example to achieve this ?

推荐答案

您首先需要创建SwitchUserFilter的实例,如下所示:

You first need to create an instance of SwitchUserFilter, like this:

@Bean
public SwitchUserFilter switchUserFilter() {
    SwitchUserFilter filter = new SwitchUserFilter();
    filter.setUserDetailsService(userDetailsService);
    filter.setSuccessHandler(authenticationSuccessHandler);
    filter.setFailureHandler(authenticationFailureHandler());
    return filter;
}

然后,您可以通过以下方式添加过滤器:

Then, you can add the filter this way:

@Override
protected void configure(HttpSecurity http) throws Exception {

    http
     ...
     .addFilterAfter(switchUserFilter(), FilterSecurityInterceptor.class);

现在,要切换,您可以使用

Now, to switch, you can use

GET /login/impersonate?username=loginIdOfTheNewUser

然后切换回

GET /logout/impersonate

请注意,确保现有用户必须具有足够的权限才能进行切换是您的工作.常见的做法是将/login/impersonate仅限制为ADMIN,而将/logout/impersonate限制为经过身份验证的用户,例如:

Note that it’s your job to ensure that existing user must have enough rights for the switch. A common practice could be to restrict /login/impersonate only to ADMINs, and and /logout/impersonate to authenticated users, like this:

        .authorizeRequests()
            .antMatchers("/login/impersonate*").hasRole("ADMIN")
            .antMatchers("/logout/impersonate*").authenticated()
            .antMatchers("/**").permitAll();

请参见以获取完整示例.

See this for a complete example.

这篇关于如何在Spring中模拟使用SwitchUserFilter的用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-20 20:21