【问题标题】:401 response when a POST request is sent to oauth/token from vuejs client从 vuejs 客户端向 oauth/token 发送 POST 请求时的 401 响应
【发布时间】:2018-06-30 02:09:32
【问题描述】:

当我使用邮递员时,我的 spring 应用程序身份验证工作正常。 但是,当我从客户端执行此操作时,我会收到 401 http 响应。

我为 cors 配置了我的服务器,如下所示:

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurerAdapter() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/*")
                    .allowedOrigins("http://localhost:8080")
                    .allowedHeaders("*")
                    .allowedMethods("*");
        }
    };
}

这是来自 vue 客户端的 post 请求:

    var params = new URLSearchParams();
    params.append('grant_type', 'password');
    params.append('username', 'username1');
    params.append('password', 'password1');

    axios({
      method:'POST',
      baseURL: `http://localhost:8088/`,
      url: 'oauth/token',
      auth: { username:'my-trusted-client', password:'secret' },
      headers: { 'Access-Control-Allow-Origin': 'http://localhost:8080',
        "Content-type": "application/x-www-form-urlencoded; charset=utf-8"},
      data: params
    }).then ((response) => {
      console.log (response)
    }).catch ((error) => {
      console.log (error)
    })

我期待的回应是这样的:

 {
 "access_token": "5766cc81-87e7-44c5-9aad-188f7b109d75",
 "token_type": "bearer",
 "expires_in": 4999,
 "scope": "read write trust"
 }

相反,我收到:无法加载 http://localhost:8088/oauth/token:预检响应包含无效的 HTTP 状态代码 401。

此外,当我检查从浏览器发送的请求时,我看到它发送的是 OPTIONS 请求而不是帖子。

服务器正在运行 om 端口 8088 并且客户端在 8080 端口上运行

我在这里缺少任何配置吗?

【问题讨论】:

    标签: spring authentication spring-security oauth-2.0 spring-security-oauth2


    【解决方案1】:

    为了将来参考,我是这样解决这个问题的: 我添加了以下bean

     @Configuration
     public class CorsConfig {
    
          @Bean
          public FilterRegistrationBean myCorsFilter() {
               UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
               CorsConfiguration config = new CorsConfiguration();
               config.setAllowCredentials(true);
               config.addAllowedOrigin("http://localhost:8080");
               config.addAllowedHeader("*");
               config.addAllowedMethod("*");
               source.registerCorsConfiguration("/**", config);
               FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
               bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
               return bean;
          }
     }
    

    请注意,虽然这可以完成工作,但建议根据您的应用程序的需要配置允许的标头和方法

    【讨论】:

    • FilterRegistrationBean 在 spring 4.3 版本中不存在,我该如何配置?
    猜你喜欢
    • 1970-01-01
    • 2018-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-30
    • 1970-01-01
    相关资源
    最近更新 更多