我正在为一家公司开发一个小型的Intranet系统,我使用WordPress后端+ Englient API V2的Engal2客户端应用程序。
用户进入客户端应用程序,然后会出现一个登录表单,并将其重定向到应用程序仪表板(而不是WordPress仪表板)
因为我是认证方面的新手,所以我想用http://cms.somecompany.com来实现这一点。
我正在appstate中保存令牌,它允许我将全局变量设置为所有组件都可以访问,然后我将使用此令牌执行所有basic auth操作…
我的问题是如何验证登录页面中的用户?
我想到,首先我应该将GET/POST/DELETE请求仅限于经过身份验证的用户。然后我可以尝试一些请求来检查响应代码!我不确定这是否正确,也不知道如何拒绝匿名用户的请求。

import {Component} from 'angular2/core';
import {AppState} from '../app.service';

@Component({
  selector: 'login',
  template: `
    <div class="container">
      <div class="login">
        <div class="login-triangle"></div>

        <h2 class="login-header">Log in</h2>

        <form class="login-container">
          <p><input type="email" placeholder="Email"></p>
          <p><input type="password" placeholder="Password"></p>
          <p><input type="submit" value="Log in"></p>
        </form>
      </div>
    </div>
  `,
  styles: [require('./login.scss')]
})

export class LoginCmp{

  constructor(private state: AppState){

  }
  login(username: string, password: string){
    let token = btoa(username + ':' + password);
    this.state.set('token', token);
  }
}

最佳答案

试试这个——

import {Component} from 'angular2/core';
import {AppState} from '../app.service';
import {Http, Headers, RequestOptions, Request, RequestMethod, Response} from 'angular2/http';

@Component({
  selector: 'login',
  template: `
    <div class="container">
      <div class="login">
        <div class="login-triangle"></div>

        <h2 class="login-header">Log in</h2>

        <form class="login-container">
          <p><input type="email" placeholder="Email"></p>
          <p><input type="password" placeholder="Password"></p>
          <p><input type="submit" value="Log in"></p>
        </form>
      </div>
    </div>
  `,
  styles: [require('./login.scss')]
})


export class LoginCmp{

  constructor(private state: AppState){

  }
  login(username: string, password: string){
    let token = btoa(username + ':' + password);
    <!--this.state.set('token', token);-->

        this.headers = new Headers(); //Set header for authunetication
        this.headers.append('Content-Type', 'application/json');
        this.headers.append('Authorization', 'Basic ' + token); //pass here your encoded string of username and password

        this.requestoptions = new RequestOptions({
            method: RequestMethod.Get, //Chose method you wish to use Get, Post, bla bla
            url: url,
            headers: this.headers
        })

     this.http.request(new Request(this.requestoptions))
            .map(res => {
                let json;
                if (res.status == 200) {
                    json = res.json();
                }
                else if (res.status == 401) {
                    json = null;
                }
                 console.log(res.status, json);
            });
  }
}

也见-
Using http rest apis with angular 2

10-04 11:06