Получение ответа на предварительный запрос не проходит проверку контроля доступа Ошибка - Spring Security + Oauth2 Rest Api - PullRequest
0 голосов
/ 30 мая 2018

Я очень плохо знаком с концепциями безопасности Spring, а также реализовал защиту на основе токенов oauth2 с использованием Spring Security.

Версии My Spring Framework:

spring framework-4.3.6.RELEASE

spring security.version - 4.1.1.RELEASE

spring security oauth2.version - 2.0.10.RELEASE

Вот в чем моя проблема с использованием примеров в GoogleЯ установил oauth2 для моих остальных API, и он хорошо работает при тестировании моих API с использованием Postman.Таким образом, я смог получить access_token от oauth, после этого я протестировал вызовы ajax.При тестировании с использованием javascript я получаю ошибки cors и в соответствии с этим я также выполнил настройку cors в своем коде.Тем не менее я что-то пропустил, и я не знаю, правильный ли мой подход или нет?Пожалуйста, поправьте меня, если я делаю это неправильно.Ниже приведен мой код.

Building Rest Api с защитой Oauth:

AuthorizationServerConfig:

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private TokenStore tokenStore;

@Autowired
private UserApprovalHandler userApprovalHandler;

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

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    clients.inMemory()
    .withClient("oauthCrud")
        .secret("oauthSuperSecret")
        .authorizedGrantTypes("password", "refresh_token")
        .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
        .scopes("read", "write", "trust")
        //.accessTokenValiditySeconds(ONE_DAY)
        .accessTokenValiditySeconds(3600)
        .refreshTokenValiditySeconds(4000);
}

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

    .authenticationManager(authenticationManager);
}

@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
    oauthServer.realm(REALM);
}
}

Сервер ресурсов:

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

@Override
public void configure(HttpSecurity http) throws Exception {
    //-- define URL patterns to enable OAuth2 security
    http.
    anonymous().disable()
    .requestMatchers().antMatchers("/api/**")
    .and().authorizeRequests()
    .antMatchers("/api/**").access("hasRole('ADMIN') or hasRole('USER')")
    .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
}

}

Конфигурация безопасности:

@Configuration
@EnableWebSecurity
//@Order(Ordered.HIGHEST_PRECEDENCE)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private ClientDetailsService clientDetailsService;

@Autowired
private DataSource dataSource;

@Autowired
public void globalUserDetails(AuthenticationManagerBuilder
     auth) throws Exception { auth.inMemoryAuthentication()
     .withUser("crmadmin").password("crmpass").roles("ADMIN","USER").and()
      .withUser("crmuser").password("pass123").roles("USER");
 }

 @Override
 protected void configure(HttpSecurity http) throws Exception {
        http.cors().and()
                .sessionManagement()

.sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                 .csrf().disable()
                .authorizeRequests()
                .antMatchers("/about").permitAll().and()
                .authorizeRequests().antMatchers(HttpMethod.OPTIONS, 
                 "*").permitAll().anyRequest().permitAll().and()
                .httpBasic(); 

}


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

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

@Bean
@Autowired
public TokenStoreUserApprovalHandler userApprovalHandler(TokenStore 
            tokenStore) {
TokenStoreUserApprovalHandler handler = new 
          TokenStoreUserApprovalHandler();
handler.setTokenStore(tokenStore);
handler.setRequestFactory(new 
DefaultOAuth2RequestFactory(clientDetailsService));
handler.setClientDetailsService(clientDetailsService);
return handler;
}

@Bean
@Autowired
public ApprovalStore approvalStore(TokenStore tokenStore) throws Exception {
            TokenApprovalStore store = new TokenApprovalStore();
            store.setTokenStore(tokenStore);
            return store;
}


@Bean
public CorsConfigurationSource corsConfigurationSource() {
        final CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("HEAD", "GET", "POST", 
        "PUT", "DELETE", "PATCH"));
        configuration.setAllowCredentials(true);
        configuration.setAllowedHeaders(Arrays.asList("Authorization", 
"Cache-Control", "Content-Type"));
        final UrlBasedCorsConfigurationSource source = new 
UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
}

}

===========================

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

@Override
public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**").allowedMethods("GET", "POST", 
"OPTIONS").allowedOrigins("*");
}
}

Код клиента

var settings = {
          "async": true,
          "crossDomain": true,
          "url": "http://10.10.1.13:8080/OauthCrud/oauth/token",
          "method": "POST",
          "headers": {
            "authorization": "Basic b2F1dGhDcnVkOm9hdXRoU3VwZXJTZWNyZXQ=",
            "content-type": "application/x-www-form-urlencoded",
            "cache-control": "no-cache",
          },
         "data": {
            "username": "rama",
            "password": "rama",
            "grant_type": "password"
          } 
        }

        $.ajax(settings).done(function (response) {
          console.log(response);
        });

Моя ошибка:

Ошибка

Что не так в моем коде?Пожалуйста, помогите мне.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...