CORS Spring Security Oauth2 - PullRequest
       10

CORS Spring Security Oauth2

0 голосов
/ 11 октября 2019

У меня проблема с CORS Spring Security Oauth2.

Это мой класс CustomAuthenProvider.java

@Component
public class CustomAuthenProvider implements AuthenticationProvider {

  private static final Logger logger = LogManager.getLogger(CustomAuthenProvider.class);

  @Autowired(required = false)
  private HttpServletRequest request;

  @Autowired
  private LdapService ldapService;

  @Value("${key.twofactor}")
  private String key;

  @Override
  public Authentication authenticate(Authentication authentication) {

    boolean authorizeLdap = ldapService.authorizeLDAP(authentication.getName(),
        authentication.getCredentials().toString());
    Totp totp = new Totp(key);

    if (!authorizeLdap || !totp.verify(request.getParameter(Constant.OTP))) {
      logger.info("Login Fail");
      return null;
    }
    Authentication auth = new UsernamePasswordAuthenticationToken(authentication.getName(),
        authentication.getCredentials().toString(), getAuthorityAdmin());
    return auth;

  }

  private List<SimpleGrantedAuthority> getAuthorityAdmin() {
    return Arrays.asList(new SimpleGrantedAuthority("ROLE_ADMIN"));
  }

  @Override
  public boolean supports(Class<?> authentication) {
    return authentication.equals(UsernamePasswordAuthenticationToken.class);
  }
}

А это мой класс SecurityConfig.java

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  @Autowired
  private CustomAuthenProvider customAuthenProvider;

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

  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(customAuthenProvider);
  }

  @SuppressWarnings("deprecation") // For NoOpPasswordEncoder
  // Using NoOpPasswordEncoder for simplicity's sake
  @Bean
  public PasswordEncoder passwordEncoder() {
    return NoOpPasswordEncoder.getInstance();
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.cors().and().csrf().disable().anonymous().disable().authorizeRequests()
        .antMatchers("/api-docs/**").permitAll();
  }

  @Bean
  public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("*"));
    configuration
        .setAllowedMethods(Arrays.asList("GET", "POST", "PATCH", "DELETE", "OPTIONS"));
    configuration.setAllowedHeaders(Arrays.asList("authorization", "content-type", "x-auth-token"));
    configuration.setExposedHeaders(Arrays.asList("x-auth-token"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
  }

}

Я использую Angular 7 для внешнего интерфейса.

При вызове API 192.168.0.109:8182/oauth/token Отображается ошибка:

2zone-evergreen.js:2952 OPTIONS http://192.168.0.109:8182/oauth/token 401
 Access to XMLHttpRequest at 'http://192.168.0.109:8182/oauth/token' from origin 'http://192.168.0.113:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

Не знаю, почему появляется сообщение Unauthorized.

Кто-нибудь может мне помочь?

Заранее спасибо. :)

1 Ответ

0 голосов
/ 11 октября 2019
modify as below and try 

    @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.cors().and().csrf().disable().anonymous().disable().authorizeRequests()
                     .antMatchers("/api/auth/**")
                        .permitAll()
                    .antMatchers(HttpMethod.GET, "/api/**", "/api/**")
                        .permitAll();

}
...