本文介绍了春季安全性,启用Oauth2时出现cors错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查询我的oauth/token端点时出现错误.

我已经为我的资源配置了cors enable,也试图允许所有资源,但是没有任何作用.

vendor.js:1837 ERROR SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)
    at CatchSubscriber.selector (app.js:7000)
    at CatchSubscriber.error (vendor.js:36672)
    at MapSubscriber.Subscriber._error (vendor.js:282)
    at MapSubscriber.Subscriber.error (vendor.js:256)
    at XMLHttpRequest.onError (vendor.js:25571)
    at ZoneDelegate.invokeTask (polyfills.js:15307)
    at Object.onInvokeTask (vendor.js:4893)
    at ZoneDelegate.invokeTask (polyfills.js:15306)
    at Zone.runTask (polyfills.js:15074)
defaultErrorLogger @ vendor.js:1837
ErrorHandler.handleError @ vendor.js:1897
next @ vendor.js:5531
schedulerFn @ vendor.js:4604
SafeSubscriber.__tryOrUnsub @ vendor.js:392
SafeSubscriber.next @ vendor.js:339
Subscriber._next @ vendor.js:279
Subscriber.next @ vendor.js:243
Subject.next @ vendor.js:14989
EventEmitter.emit @ vendor.js:4590
NgZone.triggerError @ vendor.js:4962
onHandleError @ vendor.js:4923
ZoneDelegate.handleError @ polyfills.js:15278
Zone.runTask @ polyfills.js:15077
ZoneTask.invoke @ polyfills.js:15369

有了邮递员,一切都能完美完成.

我的cors安全配置:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedHeaders("*")
                .allowedMethods("*")
                .allowCredentials(true);
    }
}

还尝试在允许的来源中添加 http://localhost:1111

邮递员中的代码

require 'uri'
require 'net/http'

url = URI("http://localhost:8080/oauth/token")

http = Net::HTTP.new(url.host, url.port)

request = Net::HTTP::Post.new(url)
request["content-type"] = 'application/x-www-form-urlencoded'
request["authorization"] = 'Basic Y2hhdHRpbzpzZWNyZXRzZWNyZXQ='
request["cache-control"] = 'no-cache'
request["postman-token"] = 'daf213da-e231-a074-02dc-795a149a3bb2'
request.body = "grant_type=password&username=yevhen%40gmail.com&password=qwerty"

response = http.request(request)
puts response.read_body
解决方案

经过很多努力后,我重写了类 WebSecurityConfigurerAdapter 的方法 configure(WebSecurity web)授权服务器自行配置它,我只是还没有找到其他解决方案.另外,您还需要允许所有"/oauth/token" Http.Options方法.我的方法:

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers(HttpMethod.OPTIONS, "/oauth/token");
}

在此之后,我们需要添加cors过滤器以将Http状态设置为OK.现在我们可以理解Http.Options方法了.

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
@WebFilter("/*")
public class CorsFilter implements Filter {

    public CorsFilter() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        final HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization");
        response.setHeader("Access-Control-Max-Age", "3600");
        if ("OPTIONS".equalsIgnoreCase(((HttpServletRequest) req).getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            chain.doFilter(req, res);
        }
    }

    @Override
    public void destroy() {
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
    }
}

I'm getting an error while querying my oauth/token endpoint.

I've configured cors enable for my resource / also tried to allow all resources but nothing worked.

vendor.js:1837 ERROR SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)
    at CatchSubscriber.selector (app.js:7000)
    at CatchSubscriber.error (vendor.js:36672)
    at MapSubscriber.Subscriber._error (vendor.js:282)
    at MapSubscriber.Subscriber.error (vendor.js:256)
    at XMLHttpRequest.onError (vendor.js:25571)
    at ZoneDelegate.invokeTask (polyfills.js:15307)
    at Object.onInvokeTask (vendor.js:4893)
    at ZoneDelegate.invokeTask (polyfills.js:15306)
    at Zone.runTask (polyfills.js:15074)
defaultErrorLogger @ vendor.js:1837
ErrorHandler.handleError @ vendor.js:1897
next @ vendor.js:5531
schedulerFn @ vendor.js:4604
SafeSubscriber.__tryOrUnsub @ vendor.js:392
SafeSubscriber.next @ vendor.js:339
Subscriber._next @ vendor.js:279
Subscriber.next @ vendor.js:243
Subject.next @ vendor.js:14989
EventEmitter.emit @ vendor.js:4590
NgZone.triggerError @ vendor.js:4962
onHandleError @ vendor.js:4923
ZoneDelegate.handleError @ polyfills.js:15278
Zone.runTask @ polyfills.js:15077
ZoneTask.invoke @ polyfills.js:15369

With Postman everything works perfect.

My cors security configuration:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedHeaders("*")
                .allowedMethods("*")
                .allowCredentials(true);
    }
}

also tried to add http://localhost:1111 in allowed origins

Code in Postman:

require 'uri'
require 'net/http'

url = URI("http://localhost:8080/oauth/token")

http = Net::HTTP.new(url.host, url.port)

request = Net::HTTP::Post.new(url)
request["content-type"] = 'application/x-www-form-urlencoded'
request["authorization"] = 'Basic Y2hhdHRpbzpzZWNyZXRzZWNyZXQ='
request["cache-control"] = 'no-cache'
request["postman-token"] = 'daf213da-e231-a074-02dc-795a149a3bb2'
request.body = "grant_type=password&username=yevhen%40gmail.com&password=qwerty"

response = http.request(request)
puts response.read_body
解决方案

After a lot of struggling i've overrided method configure(WebSecurity web) of class WebSecurityConfigurerAdapter because Authorization server configures this by itself and i just haven't found another solution. Also you need to permitAll "/oauth/token" Http.Options method. My method:

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers(HttpMethod.OPTIONS, "/oauth/token");
}

After this we need to add cors filter to set Http status to OK. And we can now intecept Http.Options method.

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
@WebFilter("/*")
public class CorsFilter implements Filter {

    public CorsFilter() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        final HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization");
        response.setHeader("Access-Control-Max-Age", "3600");
        if ("OPTIONS".equalsIgnoreCase(((HttpServletRequest) req).getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            chain.doFilter(req, res);
        }
    }

    @Override
    public void destroy() {
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
    }
}

这篇关于春季安全性,启用Oauth2时出现cors错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 04:49