2017-06-05 24 views
2

當前我嘗試使用角2來登錄以彈出oauth2。Angular 2,Oauth2,CORS錯誤:No'Access-Control-Allow-Origin'

我得到這個錯誤時,我的角鍵登錄:

的XMLHttpRequest無法加載http://localhost:8080/REM/oauth/token。否 「訪問控制 - 允許來源」標題出現在請求的 資源中。原因'http://localhost:3000'因此不允許 訪問。

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> 

請找到完整的服務器配置爲:https://github.com/robbyrahmana/Config

+0

簡單地說,你的服務器配置不正確設置。如果是的話,你不會看到錯誤。確保服務器中的CORS邏輯已正確配置,請嘗試重新啓動服務器等。 – Lansana

+0

Hi @lansana, 只有當我嘗試發送oauth /令牌時,cors纔會工作。如果正常請求,例如從服務器檢索所有用戶,請運行OK。 –

+0

然後你的兩個處理程序有什麼不同?如果一個人工作,一個人不工作,那麼不會錯過什麼? – Lansana

回答

0

我的用戶在春天開機 你可以看到,並提出一些差異

@Component 

@Order(Ordered.HIGHEST_PRECEDENCE)

公共類SimpleCORSFilter實現過濾器{

@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() { 
} 

}