Angular2如何通过发送凭证获取令牌

utn*_*nas 8 curl http spring-security oauth-2.0 angular

我正在使用Angular2从Java Spring后端应用程序获取访问令牌.我可以通过CURL获取令牌,但不能通过Angular形式获取.

 curl localhost:8085/uaa/oauth/token --data "grant_type=password&scope=write&username=MY-USERNAME&password=MY-PASSWORD" --user user:pwd
Run Code Online (Sandbox Code Playgroud)

我在这样的Java后端启用了Cors:

 public void doFilter(ServletRequest servletRequest, ServletResponse   servletResponse, FilterChain chain) throws IOException, ServletException {
    final HttpServletResponse response = (HttpServletResponse) servletResponse;
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Credentials", "true");
    response.setHeader("Access-Control-Allow-Methods", "POST, PUT, DELETE, GET, HEAD, OPTIONS");
    response.setHeader("Access-Control-Allow-Headers", "Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, If-Modified-Since");
    chain.doFilter(servletRequest, servletResponse);
}
Run Code Online (Sandbox Code Playgroud)

我的Angular代码如下所示:

import {Injectable, Component} from 'angular2/core';
import {Observable} from 'rxjs/Rx';
import {Http, HTTP_PROVIDERS, Headers} from 'angular2/http';

@Component({
   viewProviders: [HTTP_PROVIDERS]
})

@Injectable()
export class Authentication {
  token:string;
  http:Http;

  constructor(http:Http) {
    this.token = localStorage.getItem('token');
    this.http = http;
  }

  login(username:String, password:String) {

    var url = 'http://localhost:8085/uaa/oauth/token',
        body = JSON.stringify({
            username: username,
            password: password
        }),
        options = {
            headers: new Headers({
                'credentials': 'true',
                'grant_type': 'password',
                'scope': 'write',
                'Accept': 'application/json',
                'Content-Type': 'application/x-www-form-urlencoded'
            })
        };

      return this.http.post(url, body, options)
        .map((res:any) => {
            let data = res.json();
            this.token = data.token;
            localStorage.setItem('token', this.token);
        });
   }
}
Run Code Online (Sandbox Code Playgroud)

服务器的响应是:

Request URL:http://localhost:8085/uaa/oauth/token
Request Method:OPTIONS
Status Code:401 Unauthorized
Remote Address:[::1]:8085
Run Code Online (Sandbox Code Playgroud)

Mar*_*yer 9

您可能有两个问题:

  1. OPTIONS呼叫预检电话.CORS标准规定预检调用不应包括身份验证.如果您的服务器未设置为处理该服务器,您将收到401响应.如果您可以控制服务器,则应该能够添加一些内容以允许OPTIONS通过.使用NGINX,您可以添加以下内容:

    if ($request_method = 'OPTIONS') {return 200;}

    不确定你是特定的服务器.

  2. 您确定以正确的方式发送凭证吗?看起来您将所有这些作为单独的标头发送而不是像curl请求一样的表单编码数据.这对我有用:

    var headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    
    var credentials = "grant_type=authorization_code 
                    + "&credentials=true"
                    + "&scope=write" 
                    /* etc. */
    
    
    this.http.post('http://some.url', credentials, { headers: headers })
        .subscribe((res) => token = res.json())
    
    Run Code Online (Sandbox Code Playgroud)