usernamepasswordauthenticationfilter not getting invoked in spring security with oauth2 and formlogin

风格不统一 提交于 2019-12-11 12:53:24

问题


Trying to make spring security oauth2 and form login work in a spring boot application.

I took cues from https://github.com/spring-projects/spring-security-oauth/tree/master/samples/oauth2/sparklr

and

https://github.com/royclarkson/spring-rest-service-oauth/issues/11

Below is my configuration

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

 @Inject
 private AjaxAuthenticationSuccessHandler ajaxAuthenticationSuccessHandler;

 @Inject
 private AjaxAuthenticationFailureHandler ajaxAuthenticationFailureHandler;

 @Inject
 private AjaxLogoutSuccessHandler ajaxLogoutSuccessHandler;

@Inject
private UserDetailsService userDetailsService;

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

@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}

@Inject
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth
        .userDetailsService(userDetailsService)
            .passwordEncoder(passwordEncoder());
}

@Bean
public SecurityEvaluationContextExtension securityEvaluationContextExtension() {
    return new SecurityEvaluationContextExtension();
}

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring()
        .antMatchers("/scripts/**/*.{js,html}")
        .antMatchers("/bower_components/**")
        .antMatchers("/i18n/**")
        .antMatchers("/assets/**")
        .antMatchers("/swagger-ui/index.html")
        .antMatchers("/api/register")
        .antMatchers("/api/activate")
        .antMatchers("/api/account/reset_password/init")
        .antMatchers("/api/account/reset_password/finish")
        .antMatchers("/api/home/**")
        .antMatchers("/api/product/**")
        .antMatchers("/test/**")
        .antMatchers("/devadmin/**")
        .antMatchers("/signin")
        .antMatchers("/static/api-guide.html");
}



@Override
@Order(Ordered.HIGHEST_PRECEDENCE)
    protected void configure(HttpSecurity http) throws Exception {

        http
            .csrf().disable().authorizeRequests().antMatchers("/web/**","/for","/admin","/here").authenticated()
            .and()
            .formLogin()
            .loginProcessingUrl("/web/authentication")
            .successHandler(ajaxAuthenticationSuccessHandler)
            .failureHandler(ajaxAuthenticationFailureHandler)
            .usernameParameter("j_username")
            .passwordParameter("j_password")
            .permitAll()
            .and()
            .logout()
            .logoutUrl("/web/logout")
            .logoutSuccessHandler(ajaxLogoutSuccessHandler)
            .deleteCookies("JSESSIONID")
            .permitAll()
            .and()
            .exceptionHandling()
        ;

    }


@Configuration
@EnableAuthorizationServer
@EnableConfigurationProperties(SecurityConfigurationProperties.class)
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter implements EnvironmentAware {

    private static final String ENV_OAUTH = "authentication.oauth.";
    private static final String PROP_CLIENTID = "clientid";
    private static final String PROP_SECRET = "secret";
    private static final String PROP_TOKEN_VALIDITY_SECONDS = "tokenValidityInSeconds";

    private RelaxedPropertyResolver propertyResolver;

    @Inject
    private DataSource dataSource;

    @Bean
    public TokenStore tokenStore() {
        return new JdbcTokenStore(dataSource);
    }

    @Inject
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints)
            throws Exception {

        endpoints
                .tokenStore(tokenStore())
                .authenticationManager(authenticationManager);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients
            .inMemory()
            .withClient(propertyResolver.getProperty(PROP_CLIENTID))
            .scopes("read", "write")
            .authorities(AuthoritiesConstants.ADMIN, AuthoritiesConstants.USER)
            .authorizedGrantTypes("password", "refresh_token")
            .secret(propertyResolver.getProperty(PROP_SECRET))
            .accessTokenValiditySeconds(propertyResolver.getProperty(PROP_TOKEN_VALIDITY_SECONDS, Integer.class, 1800));
    }

@Override
public void setEnvironment(Environment environment) {
  this.propertyResolver = new RelaxedPropertyResolver(environment, ENV_OAUTH);
    }

    }


  @Order(2)
  @Configuration
  @EnableResourceServer
  protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http
            .requestMatchers().antMatchers("/api/**")
        .and()
            .authorizeRequests().antMatchers("/api  /**").access("#oauth2.hasScope('read') and hasRole('ROLE_USER')");
        // @formatter:on
    }
  }

  }

With above configuration oauth2 login works fine when I try authenticating via

/oauth/token

However login via

/web/authentication

always shows

405 Request method 'POST' not supported

usernamepasswordauthenticationfilter is not getting invoked.

After commenting the ResourceServerConfiguration part in above code,

form login via

/web/authentication

is working fine.

Also I can see usernamepasswordauthenticationfilter being invoked from the logs.

My question is that even the end points are configured different for oauth2 resource server and form login, why oauth2 is overriding the httpsecurity for formlogin and why not usernamepasswordauthenticationfilter being called when resource server is configured?

来源:https://stackoverflow.com/questions/34465798/usernamepasswordauthenticationfilter-not-getting-invoked-in-spring-security-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!