1

我有一些需要为 userA 复制的数据。由于我不知道 userA 的密码,我想以 adminUser 身份登录并切换到 userA 并发布数据。与此相关,我有两个问题:-

问题 1)我首先尝试使用此处响应中给出的示例登录和切换如何在 Spring 中使用 SwitchUserFilter 模拟用户?


    private final TokenProvider tokenProvider;
    protected UserDetailsService userDetailsService;//= (UserDetailsService) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    private final CorsFilter corsFilter;
    private final SecurityProblemSupport problemSupport;



    public SecurityConfiguration(UserDetailsService userDetailsService,TokenProvider tokenProvider, CorsFilter corsFilter, SecurityProblemSupport problemSupport) {
        this.tokenProvider = tokenProvider;
        this.corsFilter = corsFilter;
        this.userDetailsService = userDetailsService;
        this.problemSupport = problemSupport;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
            .antMatchers(HttpMethod.OPTIONS, "/**")
            .antMatchers("/swagger-ui/index.html")
            .antMatchers("/test/**");
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http
            .csrf()
            .disable()
            .addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class)
            .addFilterAfter(switchUserFilter(), FilterSecurityInterceptor.class)
            .exceptionHandling()
            .authenticationEntryPoint(problemSupport)
            .accessDeniedHandler(problemSupport)
        .and()
            .headers()
            .frameOptions()
            .disable()
        .and()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
            .authorizeRequests()
            .antMatchers("/api/authenticate").permitAll()
            .antMatchers("/api/register").permitAll()
            .antMatchers("/api/activate").permitAll()
            .antMatchers("/api/account/reset-password/init").permitAll()
            .antMatchers("/api/account/reset-password/finish").permitAll()
            .antMatchers("/api/**").authenticated()
            .antMatchers("/management/health").permitAll()
            .antMatchers("/management/info").permitAll()
            .antMatchers("/management/prometheus").permitAll()
            .antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN)
            .antMatchers("/login/switchUser").permitAll()
            .antMatchers("/login/impersonate").permitAll()
        .and()
            .apply(securityConfigurerAdapter());
        // @formatter:on
    }


    @Bean
    public SwitchUserFilter switchUserFilter() {

        SwitchUserFilter filter = new SwitchUserFilter();
            filter.setUserDetailsService(userDetailsService);
            filter.setSwitchUserUrl("/login/impersonate");
            filter.setSwitchFailureUrl("/login/switchUser");
            filter.setTargetUrl("/#/home");

        return filter;      
    }


    private JWTConfigurer securityConfigurerAdapter() {
        return new JWTConfigurer(tokenProvider);
    }
}

我尝试过的是,我以 adminUser 身份登录并在 url 中尝试通过将 url 更改为http://localhost:9000/login/impersonate?username=userA来切换

现在,我的问题是我成功重定向到主屏幕,但我的用户仍然是 adminUser。(我这样做是因为,当我从邮递员那里拨打 get/post 电话时,我收到回复说浏览器已过时并且需要启用 javascript)

PS :- 我有一个 jhipster 开发的应用程序,所以默认情况下已经添加了大多数类。

PPS :- 我知道我非常愚蠢

问题 2)正如我之前提到的,我需要复制数据并且我需要以编程方式进行,我该如何实现呢?SwitchUserFilter 可以调用休息网址并将一些自定义数据/值传递给它吗?

4

1 回答 1

1

在 UserJwTController 中添加此自定义方法

@PostMapping("/authenticate-externalnodes")
    public ResponseEntity<JWTToken> authenticateExternalnodes(@Valid @RequestBody LoginVM loginVM) {
        // Get Roles for user via username
        Set<Authority> authorities = userService.getUserWithAuthoritiesByLogin(loginVM.getUsername()).get()
                .getAuthorities();
        // Create Granted Authority Rules
        Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
        for (Authority authority : authorities) {
            grantedAuthorities.add(new SimpleGrantedAuthority(authority.getName()));
        }
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                loginVM.getUsername(), "", grantedAuthorities);
        Authentication authentication = authenticationToken;
        SecurityContextHolder.getContext().setAuthentication(authentication);
        boolean rememberMe = (loginVM.isRememberMe() == null) ? false : loginVM.isRememberMe();
        String jwt = tokenProvider.createToken(authentication, rememberMe);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add(JWTFilter.AUTHORIZATION_HEADER, "Bearer " + jwt);
        return new ResponseEntity<>(new JWTToken(jwt), httpHeaders, HttpStatus.OK);
    }
于 2019-07-01T10:52:04.787 回答