2

我使用Oauth2与弹簧引导1.5.2.RELEASE。当我试图覆盖ResourceServerConfigurerAdapter类的配置方法时,它给我一个编译错误。但是,这与Spring引导1.2.6.RELEASE正常工作。身份验证不起作用在弹簧引导1.5.2和Oauth2

下面是我的代码,

@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(); 
} 

上面的代码是在春季启动1.2.6工作正常,但有一个编译错误,当我尝试调用sessionManagement()方法在1.5.2版本。我猜这个方法已经在新版本中被删除了。

但是,当我尝试使用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"); 

    } 
} 
+0

的可能的复制[OAuth2和春季启动REST应用 - 不能访问与令牌资源(http://stackoverflow.com/questions/42320756/oauth2-with-spring-boot-rest-application-不能访问资源与令牌) – Tom

+0

@汤姆号这不是重复的问题。请仔细看看。这完全不同。 – Kepler

+0

过滤顺序不是这里的问题。问题是他们改变了WebSecurityConfigurerAdapter的api。我的问题是关于更改与api更改相关的配置方法实现?请不要试图仅仅看问题的表面而发表无用的评论。在做出判断之前,先仔细看看问题。 – Kepler

回答

2

是的。该API有点改变。 sessionManagement方法可以通过引用HttpSecurity来调用。

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

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

Spring boot Oauth 2 configuration cause to 401 even with the permitall antMatchers

9

根据Spring Boot 1.5 Release Notes

的OAuth 2资源筛选

的OAuth2用户资源滤波器的默认顺序从3改为SecurityProperties.ACCESS_OVERRIDE_ORDER - 1.将它放在执行器端点之后,但位于基本认证过滤器链之前。默认可以通过设置security.oauth2.resource.filter顺序恢复= 3

所以只需添加security.oauth2.resource.filter-order = 3application.properties将解决这个问题。

+1

这不适合我。 – Kepler

+0

@Cryse感谢这有帮助 –

+0

@Cryse感谢它解决了我的问题。 – dhrubo