Angular2如何通过发送凭据获得令牌 [英] Angular2 How to get token by sending credentials

查看:261
本文介绍了Angular2如何通过发送凭据获得令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Angular2从Java春后端应用程序获得访问令牌。
我可以通过卷曲而不是通过角形式获得令牌。

 卷曲本地主机:8085 / UAA / OAuth的/令牌--datagrant_type =密码&安培;范围=写&放大器;用户名= MY-USERNAME&放大器;密码= MY-PASSWORD--user用户:PWD

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

 公共无效的doFilter(ServletRequest中的servletRequest,ServletResponse的ServletResponse的,FilterChain链)抛出IOException异常,ServletException异常{
    最后HttpServletResponse的响应=(HttpServletResponse的)ServletResponse的;
    response.setHeader(访问控制允许原产地,*);
    response.setHeader(访问控制允许的凭据,真);
    response.setHeader(访问控制允许的方法,POST,PUT,DELETE,GET,HEAD,OPTIONS);
    response.setHeader(访问控制允许报头,原产地,接受,X-要求-着,内容类型,访问控制请求法,访问控制请求报头,如果-Modified-Since的);
    chain.doFilter(的servletRequest,ServletResponse的);
}

我的角code是这样的:

 进口{注射,组件}从'angular2 /核心;
从rxjs /接收进口{}观测;
从angular2 / HTTP'进口{HTTP,HTTP_PROVIDERS,头};@零件({
   viewProviders:[HTTP_PROVIDERS]
})@Injectable()
出口类认证{
  令牌:字符串;
  HTTP是:http;  构造函数(HTTP:HTTP){
    this.token = localStorage.getItem('令牌');
    this.http = HTTP;
  }  登录(用户名:字符串,密码:字符串){    VAR URL =的http://本地主机:8085 / UAA / OAuth的/令牌',
        体= JSON.stringify({
            用户名:用​​户名,
            密码:密码
        }),
        选项​​= {
            标题:新标题({
                '凭据':'真',
                grant_type':'密码',
                范围:写,
                接受:应用/ JSON,
                内容类型:应用程序/ x-WWW的形式urlen codeD
            })
        };      返回this.http.post(URL,身体,期权)
        .MAP((RES:任意)=> {
            让数据= res.json();
            this.token = data.token;
            localStorage.setItem('令牌',this.token);
        });
   }
}

来自服务器的响应是:

 请求URL:http://本地主机:8085 / UAA / OAuth的/令牌
请求方法:OPTIONS
状态code:401未授权
远程地址:[:: 1]:8085


解决方案

您可能有两个问题:


  1. 选项呼叫是preflight电话。即preflight调用的CORS标准规定不应当包括认证。如果未设置你的服务器以处理,你会得到一个 401 响应。如果您对服务器的控制,你应该能够添加一些东西,让选项通过调用。随着NGINX您可以添加这样的:

    如果($ REQUEST_METHOD ='选项'){返回200;}

    不知道你是特定的服务器。


  2. 您确定要发送的凭据的正确方法?它看起来像您发送都作为单独的头,而不是形式恩codeD数据就像你是卷曲的请求。这为我工作:

      VAR标题=新的报头();
    headers.append(Content-Type的','应用程序/ x-WWW的形式urlen codeD');VAR凭证=grant_type = authorization_ code
                    +&放大器;凭证=真正的
                    +&放大器;范围=写
                    / *等。* /
    this.http.post(的http://some.url,凭证{标题:标题})
        .subscribe((RES)=>令牌= res.json())


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

解决方案

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())
    

这篇关于Angular2如何通过发送凭据获得令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆