Spring Boot Oauth2 с JWT - реагирует на проблему с CORS - PullRequest
0 голосов
/ 18 мая 2019

Я устанавливаю сервер авторизации с помощью Spring Security Oauth2.С почтальоном все работает так, как и ожидалось, однако у меня возникают проблемы с CORS при попытке получить токен JWT из внешнего интерфейса ReactJS с помощью axios.

Я пробовал способ фильтрации сервлетов и пружинное внедрение бина CorsConfigurationSource.Кажется, никто не работает.Я получаю 401 сразу после того, как внешний интерфейс отправляет запрос OPTIONS в API, после чего 'http://localhost:9000/uaa/oauth/token?grant_type=password&username=user&password=password' from origin' http://localhost:3001' заблокирован политикой CORS: Ответ на запрос перед полетом не проходит контроль доступапроверка: у него нет статуса HTTP ok.

Класс фильтра My Cors:

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilterJwt implements Filter {


@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    response.setHeader("Access-Control-Allow-Origin", "http://localhost:3001");
    response.setHeader("Access-Control-Allow-Credentials", "true");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "Authorization,Content-Type, Accept, X-Requested-With, remember-me");

    chain.doFilter(req, res);
}

@Override
public void init(FilterConfig filterConfig) {
}

@Override
public void destroy() {
}
}

WebSecurityConfig:

@Configuration
@Order(2147483636)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

private final DataSource dataSource;
private final CustomUserDetailsService userDetailsService;

@Autowired
public WebSecurityConfig(DataSource dataSource,CustomUserDetailsService userDetailsService) {
    this.dataSource=dataSource;
    this.userDetailsService=userDetailsService;
}

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

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors().and().csrf().disable()
            .authorizeRequests()
            .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
            .antMatchers("/login").permitAll()
            .anyRequest()
            .authenticated()
            .and()
            .httpBasic();
}


@Override
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService)
            .and()
            .jdbcAuthentication()
            .passwordEncoder(encoder())
            .dataSource(dataSource);
}

@Bean
public PasswordEncoder encoder() {
    return new BCryptPasswordEncoder(11);
}

@Bean
CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("*"));
    configuration.addAllowedHeader("*");
    configuration.addAllowedMethod("*");
    configuration.setAllowCredentials(true);
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}}

WebMvcConfig:

@EnableWebMvc
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/login").setViewName("login");
    registry.addViewController("/oauth/confirm_access").setViewName("authorize");
}

@Bean
FilterRegistrationBean forwardedHeaderFilter() {
    FilterRegistrationBean filterRegBean = new FilterRegistrationBean();
    filterRegBean.setFilter(new ForwardedHeaderFilter());
    filterRegBean.setOrder(Ordered.HIGHEST_PRECEDENCE);
    return filterRegBean;
}

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE").allowedOrigins("*")
                    .allowedHeaders("*");
        }
    };
}

Реагирует код AXIOS:

signInWithEmailAndPassword = (username, password) => {
    return new Promise((resolve, reject) => {
        axios.post('http://localhost:9000/uaa/oauth/token?grant_type=password&username=user&password=password', {
            data: {
                username: username,
                password: password,
                grant_type:'password',
                scope:'ui',

            },
        }).then(response => {
            if ( response.data.user )
            {
                this.setSession(response.data.access_token);
                resolve(response.data.user);
            }
            else
            {
                reject(response.data.error);
            }
        });
    });
};

Как только я отправляю запрос на отправку axios конечной точке токена, я получаю код состояния 401 для запроса OPTIONS, затем Доступ к XMLHttpRequest по адресу http://localhost:9000/uaa/oauth/token?grant_type=password&username=user&password=password' from origin 'http://localhost:3001' заблокировано политикой CORS: Ответ на предпечатный запрос не проходит проверку контроля доступа: у него нет статуса HTTP ok.

Работает нормально при вызовеAPI от Почтальона.

...