【问题标题】:Basic Authentication of spring with Restangular使用 Restangular 对 spring 进行基本身份验证
【发布时间】:2016-07-30 10:42:40
【问题描述】:

我使用带有 Spring 的 oauth 安全性的 Restangular,在客户端我使用 Restangular 进行登录请求。

OAuth2ServerConfiguration 中的代码:

   @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients
            .inMemory()

                .withClient("clientapp")
                    .authorizedGrantTypes("password", "refresh_token")
                    .authorities("USER")
                    .scopes("read", "write")
                    .secret("abc");
        }

使用邮递员登录需要这些配置:

1-Set Authorization as "Basic Auth".
2-Set username,password as {"username":"clientapp","password":"abc"}//credentials to access server side
3-In request body through "x-www-form-urlencoded" three parameters are sent.
  {"username":"abc@gmail.com","password":"abc123","grant_type":"password"}//credentials to login which are checked from database.

这将成功登录。但我不明白如何在 Angular JS Restangular 调用中使用这些配置。

目前我正在尝试这个。

在配置中:

    RestangularProvider.withConfig(function (RestangularConfigurer) {
   return RestangularConfigurer.setDefaultHeaders({ "Authorization": "Basic Y2xpZW50YXBwOkxNUw==",
        "username":"clientapp",
        "password":"abc",
        "Content-type": "application/x-www-form-urlencoded; charset=utf-8"
            });

在控制器中:

     Restangualar.all("oauth/login").post({username;$scope.user.username,
     password:"$scope.user.password","grant_type":"password"}).then(function(){
 console.log(res);
  });

但我收到此错误:

  error:"unauthorized",error_description:"Full authentication is required to access this resource"  

在浏览器中。

注意:此资源不安全。

任何解决方案???

更新:我忘了添加一个主要信息,即我的 Angular 前端在 localhost(通过 xampp) 上独立运行,而 spring 登录后端在 localhost :8080..

网络选项卡中的错误:

2-

public void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http
            .authorizeRequests()
            .anyRequest().permitAll()
            //.antMatchers("/users").permitAll()
         .antMatchers(HttpMethod.OPTIONS, "/oauth/token").permitAll()
         .and().csrf().disable();
    }

3-

  endpoints
            .tokenStore(this.tokenStore)
            .authenticationManager(this.authenticationManager)
            .userDetailsService(userDetailsService)
            .addInterceptor(new HandlerInterceptorAdapter() {

                public boolean preHandle(HttpServletRequest hsr,         HttpServletResponse rs, Object o,FilterChain chain) throws Exception {
                    rs.setHeader("Access-Control-Allow-Origin", "*");
                    rs.setHeader("Access-Control-Allow-Methods",  "GET,OPTIONS,POST");
                   // rs.setHeader("Access-Control-Max-Age", "7200");
                    rs.setHeader("Access-Control-Allow-Headers", "Origin, X-  Requested-With, Content-Type, Accept, Authorization");
                    HttpServletRequest httpServletRequest = (HttpServletRequest) hsr;
                    if (httpServletRequest.getMethod().equalsIgnoreCase("OPTIONS")) {
                      chain.doFilter(hsr, rs);
                    } else {
                        // In case of HTTP OPTIONS method, just return the response
                        return true;
                    }
                    return false;
                    }
                });

【问题讨论】:

    标签: angularjs spring restangular


    【解决方案1】:

    您可以使用 Restangular 自定义帖子。见documentation。

    例子:

    Restangular.service("/oauth/login").one().customPOST(
      {},
      '',
      {
        // Params...
        grant_type: 'password',
        client_id: 'clientapp',
        client_secret: 'abc',
        username: 'abc@gmail.com',
        password: 'abc123',
        scope: 'read, write'
      },
      {
        // headers...
      }).then(
        function (response) {
          // Manage successfull response
        },
        function () {
          // Manage error response
        }
    );
    

    希望对你有帮助

    【讨论】:

      【解决方案2】:

      更新:

      这似乎是一个 CORS 问题,已经有很多答案了,但是在您使用 XAMPP 的情况下,您需要配置您的 apache 服务器:

      https://enable-cors.org/server_apache.html.

      更新前的先前答案:

      使用restangular的优势在于能够以更加语义化的方式管理资源,以及获取嵌套资源的能力。所有这些优势都不适用于仅从 oauth2 提供者检索令牌的调用。

      我建议忘记对这个特定调用使用 restangular(你仍然可以将它用于应用程序中的其他所有内容)并将这个调用转换为简单的 $http.post。

      $http.post('oauth/login', 
                 {  username;$scope.user.username,
                    password:"$scope.user.password",
                    "grant_type":"password"
                 }, 
                 {
                      headers: { "Authorization": "Basic Y2xpZW50YXBwOkxNUw==",
                                 "username":"clientapp",
                                 "password":"abc",
                                 "Content-type": "application/x-www-form-urlencoded; charset=utf-8"
                               }
                  })
                  .then(function(response) {
                      Restangular.setDefaultHeaders({
                           "Authorization": "Bearer " + response.token
                      });
                  });
      

      因此,您只需使用 $http.post,并在其响应中将默认标头设置为 angular 以使用检索到的令牌。

      干杯,

      【讨论】:

      • 我在 http 中使用了相同的配置,并且在同一个域的前端也使用了 restangular(都在 localhost:8080 上)。它在那里工作,但同样不适用于单独的域。
      • 如果是这种情况,听起来像是 CORS 问题,您是否检查过失败时的失败响应是什么?
      • error:"unauthorized",error_description:"访问此资源需要完全认证"
      • 这将是您在应用程序中遇到的错误,但是如果您查看 chrome 调试器的网络选项卡,您会看到获取令牌的请求及其响应,它说明了什么?
      • 您需要配置您的服务器以提供正确的标头以允许 CORS。阅读它,问题就在那里,您的代码可能是正确的。 enable-cors.org/server_apache.html
      猜你喜欢
      • 2014-09-22
      • 2014-03-22
      • 1970-01-01
      • 2015-08-12
      • 2017-06-13
      • 2013-05-30
      • 2017-09-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多