身份验证在Spring Boot 1.5.2和OAuth2中不起作用



我正在使用oauth2与Spring Boot 1.5.2.Release。当我试图覆盖ResourceerverConfigurerAdapter类的配置方法时,它给了我汇编错误。但这与Spring Boot 1.2.6.Release一起工作正常。

以下是我的代码,

@Override
public void configure(HttpSecurity http) throws Exception {
    http
        .exceptionHandling()
        .authenticationEntryPoint(customAuthenticationEntryPoint)
        .and()
        .logout()
        .logoutUrl("/oauth/logout")
        .logoutSuccessHandler(customLogoutSuccessHandler)
        .and()
        .csrf()
        .requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize"))
        .disable()
        .headers()
        .frameOptions().disable()
        .sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
        .authorizeRequests()
        .antMatchers("/hello/").permitAll()
        .antMatchers("/secure/**").authenticated();
}

上面的代码在Spring Boot 1.2.6中工作正常,但是当我尝试以1.5.2版本调用SessionManagement()方法时,存在汇编错误。我猜该方法已在新版本中删除。

但是,当我尝试使用disable()。和()。会sessionManagement()汇编错误删除,但身份验证无法正常工作。任何人都可以帮助我解决这个问题吗?

以下是我的完整代码

@Configuration
public class OAuth2Configuration {
    @Configuration
    @EnableResourceServer
    @ComponentScan(basePackages = "security")
    protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
        @Autowired
        private CustomAuthenticationEntryPoint customAuthenticationEntryPoint;
        @Autowired
        private CustomLogoutSuccessHandler customLogoutSuccessHandler;
        @Override
        public void configure(HttpSecurity http) throws Exception {
            http
                .exceptionHandling()
                .authenticationEntryPoint(customAuthenticationEntryPoint)
                .and()
                .logout()
                .logoutUrl("/oauth/logout")
                .logoutSuccessHandler(customLogoutSuccessHandler)
                .and()
                .csrf()
                .requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize"))
                .disable()
                .headers()
                .frameOptions().disable().and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/hello/").permitAll()
                .antMatchers("/secure/**").authenticated();
        }
    }
    @Configuration
    @EnableAuthorizationServer
    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;
        @Autowired
        private DataSource dataSource;
        @Bean
        public TokenStore tokenStore() {
            return new JdbcTokenStore(dataSource);
        }
        @Autowired
        @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(Authorities.ROLE_ADMIN.name(), Authorities.ROLE_USER.name())
                .authorizedGrantTypes("password", "refresh_token")
                .secret(propertyResolver.getProperty(PROP_SECRET))
                .accessTokenValiditySeconds(propertyResolver.getProperty(PROP_TOKEN_VALIDITY_SECONDS, Integer.class, 1800));
        }

        public void setEnvironment(Environment environment) {
            this.propertyResolver = new RelaxedPropertyResolver(environment, ENV_OAUTH);
        }
    }
}
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new StandardPasswordEncoder();
    }
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .userDetailsService(userDetailsService)
            .passwordEncoder(passwordEncoder());
    }
    @Override
    public void configure(WebSecurity web) throws Exception {
        web
            .ignoring()
            .antMatchers("/h2console/**")
            .antMatchers("/api/register")
            .antMatchers("/api/activate")
            .antMatchers("/api/lostpassword")
            .antMatchers("/api/resetpassword")
            .antMatchers("/api/hello");
    }
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
    @EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true)
    private static class GlobalSecurityConfiguration extends GlobalMethodSecurityConfiguration {
        @Override
        protected MethodSecurityExpressionHandler createExpressionHandler() {
            return new OAuth2MethodSecurityExpressionHandler();
        }
    }
}
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
    private final Logger log = LoggerFactory.getLogger(CustomAuthenticationEntryPoint.class);
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException ae) throws IOException, ServletException {
        log.info("Pre-authenticated entry point called. Rejecting access");
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Access Denied");
    }
}

根据Spring Boot 1.5发行说明:

oauth 2资源过滤器

OAuth2资源过滤器的默认顺序已从3更改为SecurityProperties.access_override_order-1。这将其放在执行器端点之后,但在基本身份验证过滤器链之前。可以通过设置Security.oAuth2.Resource.filter-order = 3

来恢复默认值

因此,只需将security.oauth2.resource.filter-order = 3添加到您的application.properties即可解决此问题。

是。API有位更改。可以使用httpsecurity的参考来调用SessionManagement方法。

http
    .exceptionHandling()
    .authenticationEntryPoint(customAuthenticationEntryPoint)
    .and()
    .logout()
    .logoutUrl("/oauth/logout")
    .logoutSuccessHandler(customLogoutSuccessHandler)
    .and()
    .csrf()
    .requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize"))
    .disable()
    .headers()
    .frameOptions().disable();
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
    .and()
    .authorizeRequests()
    .antMatchers("/hello/").permitAll()
    .antMatchers("/secure/**").authenticated();

但是,您没有提供足够的信息来解决您的身份验证问题。给出以下问题的答案可以解决您的问题。

春季靴子OAuth 2配置构成401即使使用许可证抗匹配者

最新更新