我如何使用Angular 2发出请求spring-security-oauth2 REST

时间:2016-11-10 00:56:39

标签: rest authentication oauth token

我使用https://github.com/royclarkson/spring-rest-service-oauth

中的示例创建了一个Spring Security OAuth2服务器

CURL命令中的OAuth2身份验证请求如下所示。我想要Angular2中的等效语法。

curl -X POST -vu clientapp:123456 http://localhost:8080/oauth/token -H "Accept: application/json" -d "password=spring&username=roy&grant_type=password&scope=read%20write&client_secret=123456&client_id=clientapp"

以下是我的尝试:

import { Injectable } from '@angular/core';
import {Http, Headers, RequestOptions, RequestMethod} from '@angular/http';
import {Router} from '@angular/router';

@Injectable()
export class AuthService {
    isAuthenticated: boolean = false;
    userId;

    constructor(private http: Http, private router: Router) { }

    login(usercreds){
      let client_id = 'clientapp';
      let client_secret = '123456';
      var basicheader = btoa(client_id + ':' + client_secret);
      console.log(basicheader);
      var headers = new Headers();

      headers.append('Authorization', 'Basic' + basicheader);
      headers.append('Accept', 'application/json');
      headers.append('Content-Type', 'application/json');
      //let options = new RequestOptions( {method: RequestMethod.Post,   headers: headers });

      var creds = 'username=' + usercreds.username + '&password=' +  usercreds.password+'credentials=true&grant_type=password&scope=read%20write&client_secret=123456&client_id=clientapp';
      console.log(creds); 

     return new Promise((resolve) => {
        this.http.post('http://localhost:8080/oauth/token',    JSON.stringify(creds), {headers:headers}).subscribe((data) => {
        if(data.json().success) {
            this.userId = data.json().userId;      
            this.isAuthenticated = true;
        }
            resolve(this.isAuthenticated);
    })
  })
}
}

但是当我启动此应用程序时,Google Chrome浏览器会在开发者模式下返回此错误:

  
      
  • XMLHttpRequest无法加载http://localhost:8080/oauth/token。预检的响应具有无效的HTTP状态代码401
  •   
  • EXCEPTION:状态响应:URL为0:null
  •   

2 个答案:

答案 0 :(得分:1)

找到问题的原因!

如果CorsFilter处理了OPTIONS请求,我只需要结束过滤链并立即返回结果! 所以,我在使用spring oauth2 security开发的Web服务中添加了这个类。

SimpleCorsFilter.java

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class SimpleCorsFilter implements Filter {

   public SimpleCorsFilter() {}

   @Override
   public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
      HttpServletResponse response = (HttpServletResponse) res;
      HttpServletRequest request = (HttpServletRequest) req;
      response.setHeader("Access-Control-Allow-Origin", "*");
      response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
      response.setHeader("Access-Control-Max-Age", "3600");
      response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization");

      if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
          response.setStatus(HttpServletResponse.SC_OK);
      } else {
          chain.doFilter(req, res);
     }
 }

  @Override
  public void init(FilterConfig filterConfig) {}

  @Override
  public void destroy() { }
}

答案 1 :(得分:1)

使用代码:

let headers = new Headers({
            "Content-Type": "application/x-www-form-urlencoded",
            "Accept": "application/json",
            "Authorization": "Basic " + btoa("yourclientid" + ':' + "yourclientsecret")
        });
let options = new RequestOptions({ headers: headers });

let data = "username=" + yourlogin + "&password=" + encodeURIComponent(yourpass) + "&grant_type=password&" +
            "client_secret=yoursecret&client_id=yourclientid";

return this.http.post("http://localhost:8080/oauth/token", data, options)
            .map(res => res.json());

关注我的文件:

import { Injectable } from '@angular/core'
import { Resources } from '../../config/resources';
import { Http } from '@angular/http';
import { Headers, RequestOptions } from '@angular/http';

@Injectable()
export class LoginService {
    private urlLogin: string;

    constructor(private http: Http) {
        this.urlLogin = Resources.getUrlBackend() + "oauth/token";
    }

    public login(usuario) {

        let headers = new Headers({
            "Content-Type": "application/x-www-form-urlencoded",
            "Accept": "application/json",
            "Authorization": "Basic " + btoa("clientapp" + ':' + "springSecurity")
        });

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

        let client = "username=" + usuario.email + "&password=" + encodeURIComponent(usuario.senha) + "&grant_type=password&" +
            "client_secret=springSecurity&client_id=clientapp";

        return this.http.post(this.urlLogin, client, options)
            .map(res => res.json());
    }

}