如何使用授权请求解决错误401

时间:2019-04-02 14:24:40

标签: angular spring-boot spring-security

我正在使用Angular 7和Spring Boot开发一个应用程序。 我的问题与授权请求有关。

我已经搜索了很多东西,发现的所有解决方案都与我的代码相同,但是问题是请求在Postman上可以正常工作,而在Angular中不起作用。

这是错误

enter image description here

这是我的个人资料服务:

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) ;
}

这是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();
}

1 个答案:

答案 0 :(得分:0)

您在两个不同的端口上使用两个不同的服务器,因此引发此错误。 您可以在rest控制器上添加@CrossOrigin或创建像这样的拦截器来修复它:

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; 
        }
    }
}

并在Spring Config中添加以下行:

<mvc:interceptors>
<bean id="crossOriginInterceptor"
    class="com.systemevolution.controller.CrossOriginInterceptor" /></mvc:interceptors>