验证在Spring Boot 1.5.2和Oauth2中不起作用

开普勒

我正在将Oauth2与Spring Boot 1.5.2.RELEASE一起使用。当我尝试覆盖ResourceServerConfigurerAdapter类的configure方法时,它给了我一个编译错误。但这在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()。and()。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");

    }
}
婚礼

是。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();

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

即使使用allowant antMatchers,Spring Boot Oauth 2配置也会导致401

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

RestController在oauth2 Spring Boot中不起作用

Spring Boot OAuth2单一登录概念不起作用

从Spring Boot Oauth2迁移到Spring Security 5

Spring Boot验证不起作用

使用Spring Boot 2和Spring Security 5进行多重身份验证

Spring Boot + JWT Oauth2:Spring 5 vs Spring <5

Spring Boot验证注释@Valid和@NotBlank不起作用

Spring Boot 2 和 QueryDSL 集成不起作用?

在Spring Boot中验证Bean

Angular 4/5 + Spring Boot + Oauth2支持

在Spring Boot OAuth2中跳过OAuth用户批准

如何在Angular5和spring-boot中使用自定义验证器

Spring Boot OAuth2 + JWT和UserDetailsService

Spring Boot和OAuth2,WebSecurityConfigurerAdapter与ResourceServerConfigurerAdapter

与 spring boot 和类似配置相比,没有 spring boot 的 Spring 安全身份验证不起作用

Spring Boot 2 + OAuth2:配置令牌的身份验证代码交换

Spring Boot基本身份验证和OAuth2在同一项目中?

在 Spring Boot 中处理 OAuth2 回调

如何在 Spring Boot 中使用预定义的令牌绕过 Oauth2 身份验证?

如何使用Spring Boot + Angular处理外部OAuth2身份验证

在Spring Boot OAuth2授权服务器中使用Active Directory身份验证

如何使用Spring Boot伪装客户端进行Oauth2身份验证?

Spring Boot + oauth2:访问此资源需要完全身份验证

使用Spring Boot进行OAuth2身份验证后无法正确重定向

Spring Boot Oauth2扩展DefaultTokenServices

了解Spring Boot的Oauth2入门

Spring Boot 2.0.0 + OAuth2

Oauth2 + Spring Boot 资源给大家

如何使用Spring Security 5在Spring Boot应用程序(而非Web应用程序)中获取oauth2访问令牌