简体   繁体   中英

Angular 2, Oauth2, CORS error : No 'Access-Control-Allow-Origin'

Currently I try to make login using angular 2 to spring oauth2.

I get this error when click login in my angular:

XMLHttpRequest cannot load http://localhost:8080/REM/oauth/token . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' http://localhost:3000 ' is therefore not allowed access.

Angular

login(username: string, password: string) {
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');
headers.append('Accept', 'application/json');

let options = new RequestOptions({ headers: headers });

let params = new URLSearchParams();
params.append('grant_type', "password");  
params.append('client_id', "client");
params.append('client_secret', "secret");
params.append('username', "user");
params.append('password', "pass");                             

return this.http.post(this.urlLogin, params.toString(), options).map(this.extractData);}

CORS

<mvc:cors>
    <mvc:mapping path="/**" allowed-origins="http://localhost:3000, *"
        allowed-methods="POST, GET, PUT, DELETE"
        allowed-headers="X-Requested-With, Content-Type, X-Codingpedia,Authorization, Accept, Origin"
        allow-credentials="false" max-age="3600" />
</mvc:cors>

Kindly find full server configuration at: https://github.com/robbyrahmana/Config

I user it in spring boot you can see that and make some differences

@Component

@Order(Ordered.HIGHEST_PRECEDENCE)

public class SimpleCORSFilter implements Filter {

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

@Override
public void doFilter(ServletRequest req, ServletResponse resp,
                     FilterChain chain) throws IOException, ServletException {
    HttpServletResponse response = (HttpServletResponse) resp;
    HttpServletRequest request = (HttpServletRequest) req;
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "PATCH,POST,GET,OPTIONS,DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization, Content-Type, Authorization, credential, X-XSRF-TOKEN");

    if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
        response.setStatus(HttpServletResponse.SC_OK);
    } else {
        chain.doFilter(req, resp);
    }

}

@Override
public void destroy() {
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM