0

I am developing an application with Angular 7 and Spring Boot. My Probleme is with the authorization request.

I've searched a lot and all the solutions that i found are the same as in my code but the problem is that requests works fine with Postman and it doesn't work with Angular.

this is the Error

enter image description here

and this is my profile service :

getEmployeeById(id: number) {

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    'Authorization': 'Basic ' + btoa('user:userPass'),
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
    'Access-Control-Allow-Headers': 'Origin, Content-Type, X-Auth-Token'
  })
};
return this.http.get<UserProfile>( this.baseUrl.oneEmployee.replace(':id', id),
  httpOptions) ;
}

and this is the security configuration in Spring boot :

@Override
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication()
            .withUser("admin").password(encoder().encode("adminPass")).roles("ADMIN")
            .and()
            .withUser("user").password(encoder().encode("userPass")).roles("USER");
}

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


@Override
protected void configure(HttpSecurity http) throws Exception {
    /*http
            .csrf().disable()
            .authorizeRequests().anyRequest().authenticated()
            .and()
            .httpBasic();*/

    //http.addFilterBefore(new CorsFilter(), ChannelProcessingFilter.class);
    http.authorizeRequests().antMatchers("/").permitAll()
            .anyRequest().fullyAuthenticated().and().httpBasic().and().csrf().disable();
}
Hamza Torjmen
  • 250
  • 1
  • 2
  • 10
  • CORS is throwed because you do a request an another url. I don't use spring but (in generally) you need do configure the request header . You can use this guide https://stackoverflow.com/questions/51640206/angular-client-enable-cors – Doflamingo19 Apr 02 '19 at 15:36
  • no, the problem is that my request works fine with PostMan but when i want to run it with Angular 7, it passes the correct headers but doesn't want to auhorize the request – Hamza Torjmen Apr 03 '19 at 09:16

1 Answers1

0

You are using two different servers on two different ports so is throwed this error. You can fix it adding @CrossOrigin on your rest controller or creating an interceptor like this one:

public class CrossOriginInterceptor extends HandlerInterceptorAdapter {

    public static final String REQUEST_ORIGIN_NAME = "Origin";

    public static final String CREDENTIALS_NAME = "Access-Control-Allow-Credentials";
    public static final String ORIGIN_NAME = "Access-Control-Allow-Origin";
    public static final String METHODS_NAME = "Access-Control-Allow-Methods";
    public static final String HEADERS_NAME = "Access-Control-Allow-Headers";
    public static final String MAX_AGE_NAME = "Access-Control-Max-Age";

    private List<String> origins=null;

    @Value("${origin.address}") private String origin;
    @Value("${origin.controlEnabled}") private boolean controlEnabled;

    @PostConstruct
    public void method() {
        List<String> stringList = new ArrayList<String>();
        stringList.add(origin);
        this.origins = stringList;
    }

    @Override 
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if(!controlEnabled){ return super.preHandle(request, response, handler);}

        response.setHeader(CREDENTIALS_NAME, "true");
        response.setHeader(METHODS_NAME, "GET, OPTIONS, POST, PUT, DELETE, PATCH");
        response.setHeader(HEADERS_NAME, "Origin, X-Requested-With, Content-Type, Accept");
        response.setHeader(MAX_AGE_NAME, "3600");

        String reqOrigin = request.getHeader(REQUEST_ORIGIN_NAME);
        if (StringUtils.isEmpty(reqOrigin) || origins.contains(reqOrigin)) {
            response.setHeader(ORIGIN_NAME, reqOrigin);
            return true; // Proceed
        } else {
            response.setHeader(ORIGIN_NAME, origins.iterator().next());
            return false; 
        }
    }
}

and adding this rows in your Spring Config:

<mvc:interceptors>
<bean id="crossOriginInterceptor"
    class="com.systemevolution.controller.CrossOriginInterceptor" /></mvc:interceptors>
Nicolas
  • 155
  • 1
  • 2
  • 12