使用JHipster,Spring Security和oauth2控制身份验证重定向

问题描述 投票:0回答:1

我希望能够在用户未登录时控制自动重定向到oauth2授权服务器。

我生成了一个JHipster Gateway项目,下面的代码只是它的副本,添加了oAuth2ClientContextFilter变量,即autowired,然后我用它来setRedirectStrategy

然而,当使用它时,变量是NULL。我究竟做错了什么?

@EnableOAuth2Sso
@Configuration

public class OAuth2SsoConfiguration extends WebSecurityConfigurerAdapter {

    private final RequestMatcher authorizationHeaderRequestMatcher;

    private final CorsFilter corsFilter;

    @Autowired
    private OAuth2ClientContextFilter oAuth2ClientContextFilter;

    private final Logger log = LoggerFactory.getLogger(OAuth2SsoConfiguration.class);

    public OAuth2SsoConfiguration(@Qualifier("authorizationHeaderRequestMatcher")
                                  RequestMatcher authorizationHeaderRequestMatcher, CorsFilter corsFilter) {
        this.authorizationHeaderRequestMatcher = authorizationHeaderRequestMatcher;
        this.corsFilter = corsFilter;
        oAuth2ClientContextFilter.setRedirectStrategy(new RedirectStrategy() {

            @Override
            public void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url) throws IOException {
                // My Code Here
            }

        });

    }

    @Bean
    public AjaxLogoutSuccessHandler ajaxLogoutSuccessHandler() {
        return new AjaxLogoutSuccessHandler();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf()
            .disable()
            .addFilterBefore(corsFilter, CsrfFilter.class)
            .headers()
            .frameOptions()
            .disable()
        .and()
            .logout()
            .logoutUrl("/api/logout")
            .logoutSuccessHandler(ajaxLogoutSuccessHandler())
        .and()
            .requestMatcher(new NegatedRequestMatcher(authorizationHeaderRequestMatcher))
            .authorizeRequests()
            .antMatchers("/api/profile-info").permitAll()
            .antMatchers("/api/**").authenticated()
            .antMatchers("/management/health").permitAll()
            .antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN)
            .anyRequest().permitAll();
    }
}
java spring-security oauth-2.0 jhipster spring-security-oauth2
1个回答
2
投票

混合自动装配策略(现场自动装配和构造函数自动装配)并不好,因为构造发生在@Autowired之前。所以要么将filter注入构造函数:

private OAuth2ClientContextFilter oAuth2ClientContextFilter;

public OAuth2SsoConfiguration(
    @Qualifier("authorizationHeaderRequestMatcher")RequestMatcher authorizationHeaderRequestMatcher, 
    CorsFilter corsFilter, 
    OAuth2ClientContextFilter oAuth2ClientContextFilter
) {
    this.authorizationHeaderRequestMatcher = authorizationHeaderRequestMatcher;
    this.corsFilter = corsFilter;
    this.oAuth2ClientContextFilter = oAuth2ClientContextFilter;
    .....
}

或者将RequestMatcher和CorsFilter移出构造函数参数并将它们表示为@Autowired

© www.soinside.com 2019 - 2024. All rights reserved.