Angular2 How to get token by sending credentials

2019-03-27 07:36发布

I'm using Angular2 to get access token from a Java Spring back-end application. I can get the token via CURL but not via Angular form.

 curl localhost:8085/uaa/oauth/token --data "grant_type=password&scope=write&username=MY-USERNAME&password=MY-PASSWORD" --user user:pwd

I enabled Cors on Java back-end like this:

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

My Angular code looks like this:

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

The response from the server is:

Request URL:http://localhost:8085/uaa/oauth/token
Request Method:OPTIONS
Status Code:401 Unauthorized
Remote Address:[::1]:8085

3条回答
狗以群分
2楼-- · 2019-03-27 08:23

You might have two problems:

  1. The OPTIONS call is a preflight call. The CORS standard states that preflight calls should not include authentication. If your server isn't set up to handle that, you will get a 401 response. If you have control over the server you should be able to add something to allow the OPTIONS call through. With NGINX you can add something like:

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

    Not sure about you're particular server.

  2. Are you sure you are sending the credentials the right way? It looks like you are sending all this as individual headers rather than form-encoded data like you are with the curl request. This has worked for me:

    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())
    
查看更多
时光不老,我们不散
3楼-- · 2019-03-27 08:30

You should provide the username / password hints within the Authorization header with the "Basic" scheme. The value must encoded with base64 with the btoa function:

headers.append('Authorization', 'Basic ' + btoa('username:password');

Moreover, after having alook at your curling request, it seems that what you put in headers should be provided in the payload. This can be done using the UrlSearchParams class.

See rhis question for more details:

查看更多
贪生不怕死
4楼-- · 2019-03-27 08:36

Problem is probably in your angular service. I think you should't send body as object which contains username and password, but you should send string which contains "grant_type", "username" and "password". This is example of my working service method:

    postAuth(url: string, data?: LoginCredentials){

    let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });  
    let options = new RequestOptions({ headers: headers });

    //here I am setting username and password which I got from html form
    var body = "grant_type=password&username="+ data.Email + 
               "&password=" + data.Password; 

    return this.http.post(url, body, options);
  }
查看更多
登录 后发表回答