-1

My server side code is..

public class SimpleCorsFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {

}

@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", "*");


    if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST,GET,DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("X-Frame-Options", "*");
        response.setHeader("Access-Control-Allow-Headers", "content-type,access-control-request-headers,access-control-request-method,accept,origin,authorization,x-requested-with");
        response.setStatus(HttpServletResponse.SC_OK);
    } else {
        chain.doFilter(req, res);
    }
}

@Override
public void destroy() {

}

}

My Client Side code is ...

viewUsers(): Observable<any> {
    let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');       
    headers.append('Access-Control-Allow-Origin', '*')
    headers.append('Accept', 'application/json');
    headers.append('Authorization', 'Basic dXNlcjpzdXJpeWFu');

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

    return this.http.get(myurl, options).map(getJson);
}

Please help me to resolve this issue... I am getting above and below error : Failed to load http://10.100.8.58:8080/user/view: Response for preflight has invalid HTTP status code 401. I don't know where i have done a mistake.

MY server side securityConfif CLass is..

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication().withUser("user").password("suriyan").roles("USER").and().withUser("admin")
            .password("suriyans").roles("USER", "ADMIN");
}

protected void configure(HttpSecurity http) throws Exception {
    http.httpBasic().and().authorizeRequests().antMatchers("/user/**").hasRole("USER").antMatchers("/**")
            .hasRole("ADMIN").and().csrf().disable().headers().frameOptions().disable();
}

}

My post man code is..

 OkHttpClient client = new OkHttpClient();

 Request request = new Request.Builder()
 .url("http://10.100.8.58:8080/user/view")
 .get()
 .addHeader("authorization", "Basic dXNlcjpzdXJpeWFu")
 .addHeader("cache-control", "no-cache")
 .addHeader("postman-token", "48b3ca10-fe72-4a1e-ce00-44c78afb636a")
 .build();

 Response response = client.newCall(request).execute();
Robin Green
  • 32,079
  • 16
  • 104
  • 187
Suriyan
  • 3
  • 5
  • I have used spring security and created scecurityConfig class for two roles in the name of user and admin in server side. By using postman i can get the data using my user and password but it not achievable via coding in client side. – Suriyan May 04 '18 at 05:52
  • can you post the all settings you are using in Postman? – harshpatel991 May 04 '18 at 05:54
  • is it working in the postman? – Shadab Faiz May 04 '18 at 05:55
  • OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("http://10.100.8.58:8080/user/view") .get() .addHeader("authorization", "Basic dXNlcjpzdXJpeWFu") .addHeader("cache-control", "no-cache") .addHeader("postman-token", "42485331-9259-1b83-e186-a0c563e4f44d") .build(); Response response = client.newCall(request).execute(); – Suriyan May 04 '18 at 05:57
  • @ShadabFaiz Faiz Its working fine in postman – Suriyan May 04 '18 at 05:58
  • then this is related to CORS issue..looks this https://stackoverflow.com/questions/49361030/post-request-does-not-work-from-angular5-code-but-works-from-postman/49361816#49361816 – Shadab Faiz May 04 '18 at 06:02
  • @ShadabFaiz I conclude its CORS issue by referring stackoverflow.com/questions/49361030/… but if its solvable then it will be helpful for me . Anyway thanks for your response – Suriyan May 04 '18 at 06:16

1 Answers1

0

Your request is preflighted by the browser because Same Origin Policy. I think this is a good description about SOP and CORS.

In order to allow http request from different origin you have to enable CORS but this is done on the server using the header:

Access-Control-Allow-Origin: '*'

You have declared this header on the client, which I think is wrong. Here you have some examples about enabling CORS with Spring:

Spring CORS No 'Access-Control-Allow-Origin' header is present

https://spring.io/guides/gs/rest-service-cors/

Ignasi
  • 5,887
  • 7
  • 45
  • 81
  • Yeah What you have said is Correct.. Now its working fine .. I have added a line @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**"); } in my securityConfig Class at bottom and i have removed the line "Access-Control-Allow-Origin: '*' " and Content Type header from client side now its working fine. Thank you for your Helpful answer. – Suriyan May 04 '18 at 09:36