如何使用RESTAPI在angular2中实现oauth2?

如何使用RESTAPI在angular2中实现oauth2?,rest,angular,oauth,Rest,Angular,Oauth,我使用RESTAPI在angular2中实现oauth2。后端开发人员给了我这些数据和登录数据 private OauthLoginEndPointUrl = 'http://localhost:8000/oauth/token'; private clientId ='2'; private clientSecret ='fsdfasdfaasdfasdfadsasdfadsfasdf'; 如何使用密码授权与后端连接?他正在使用 我照做了,但似乎已经过时了 我的登录 <h1&g

我使用RESTAPI在angular2中实现oauth2。后端开发人员给了我这些数据和登录数据

private OauthLoginEndPointUrl = 'http://localhost:8000/oauth/token';  

private clientId ='2';

private clientSecret ='fsdfasdfaasdfasdfadsasdfadsfasdf';
如何使用密码授权与后端连接?他正在使用

我照做了,但似乎已经过时了

我的登录

<h1>Login</h1>
<form role="form" (submit)="login($event, username.value, password.value)">
  <div class="form-group">
    <label for="username">Username</label>
    <input type="text" #username class="form-control" id="username" placeholder="Username">
  </div>
  <div class="form-group">
    <label for="password">Password</label>
    <input type="password" #password class="form-control" id="password" placeholder="Password">
  </div>
  <button type="submit" class="btn btn-primary btn-block btn-large">Submit</button>
</form>
登录服务

import { Injectable } from '@angular/core';
import { Http , URLSearchParams , Response  } from '@angular/http';
import { Observable } from 'rxjs/Rx';


@Injectable()
export class LoginService {
  private OauthLoginEndPointUrl = 'http://localhost:8000/oauth/token';  // Oauth Login EndPointUrl to web API
  private clientId ='2';
  private clientSecret ='A4iX0neXv4LCwpWf0d4m9a8Q78RGeiCzwqfuiezn';

  constructor(public http: Http) {}

  login(username, password) : Observable {
    console.log("obs");
    let params: URLSearchParams = new URLSearchParams();
    params.set('username', username );
    params.set('password', password );
    params.set('client_id', this.clientId );
    params.set('client_secret', this.clientSecret );
    params.set('grant_type', 'password' );

    return this.http.get(this.OauthLoginEndPointUrl , {
      search: params
    }).map(this.handleData)
      .catch(this.handleError);
  }

  private handleData(res: Response) {
    let body = res.json();
    return body;
  }

  private handleError (error: any) {
    // In a real world app, we might use a remote logging infrastructure
    // We'd also dig deeper into the error to get a better message
    let errMsg = (error.message) ? error.message :
      error.status ? `${error.status} - ${error.statusText}` : 'Server error';
    console.error(errMsg); // log to console instead
    return Observable.throw(errMsg);
  }

  public logout() {
    localStorage.removeItem('token');
  }
}

以下是您需要采取的步骤的概要:

  • 在Angular应用程序中,创建一个“登录”链接,将用户发送到
    http://localhost:8000/oauth/token?client_id=2
    (URL的确切语法取决于您的后端…)

  • 用户看到授权提示(“允许访问…?”)。他们可以单击“允许”或“拒绝”。如果他们单击“允许”,服务将使用身份验证代码将用户重定向回您的站点,类似于
    http://localhost:4200/cb?code=AUTH_CODE_HERE
    。请注意,URL现在是Angular应用程序的URL(在Angular中,您可以使用
    this.route.snapshot.queryParams['code']
    访问
    “URL”参数)

  • 最后,您可以通过HTTP将收到的身份验证代码发布到后端的另一个URL,以将其交换为令牌,例如
    HTTP.POST('http://localhost:8000/oauth/tokenstringify({code:AUTH_code_HERE}))

  • 此代码不应逐字使用,这只是一个大纲。调整它到您的后端,并查看深入的信息

    旁注。在#1和#3中使用的URL通常不同。第一个URL用于获取身份验证代码,另一个URL用于将身份验证代码交换为令牌。奇怪的是,您的后端开发人员只给了您一个URL。

    试试这个。组件中

    login() {
    
    this
     .authService
     .login()
     .subscribe(
       (success) => {
         // do whatever you want with success response here
    
       },
       (error) => {
         // handle error here
       })
    
    }
    
    在职:

    login() : observable {
    
    return 
       this
        .http
        .get(OauthLoginEndPointUrl, {clientId, clientSecret })
        .map((data) => {
          return data.json();
        })
        .catch(error)
    
    }
    
    我需要使用“密码授权类型,可用于直接为访问令牌交换用户名和密码。”。不允许用户授权app。在这种情况下,在步骤#1中,不是直接将用户带到URL,而是向用户显示一个用户名/密码表单,然后将他在表单中输入的值发布到URL。
    login() : observable {
    
    return 
       this
        .http
        .get(OauthLoginEndPointUrl, {clientId, clientSecret })
        .map((data) => {
          return data.json();
        })
        .catch(error)
    
    }