2017-02-16 96 views
1

我使用ASP.net Web API 2作爲我的後端和Ionic 2應用程序作爲我的前端。使用asp.net web api驗證Ionic 2應用程序

我正在使用Microsoft的UserStore管理器進行身份驗證我的應用程序。

它使用基於令牌的身份驗證(請原諒我,如果我使用錯誤的namings,我還是新來的)。

我能夠通過Postman獲得一個令牌,然後在請求頭中使用這個令牌,像這個「Bearer [token]」從我的Web API獲取任何數據。

Getting the Token with Postman

正如你所看到的方法是郵政和內容類型是X WWW的形式,進行了urlencoded。

做到這一點,它會生成一個access_token,然後我把這個標記用在我的頭文件中以得到我需要的東西。

在我的應用離子我創建了一個auth-service.ts與公共方法稱爲登錄()

public login(credentials) { 
if (credentials.username === null || credentials.password === null) { 
    let error = this.alertController.create({ 
    title:'Lol', 
    message:'incomplete credentials, Fill them up and come back', 
    buttons: ['ok'] 
    }); 

    error.present(); 
} 
else { 
    return new Promise(resolve => { 
    this.http.post(`${this.baseUrl}/token`, 
    { 
     grant_type:'password', 
     username:credentials.username, 
     password:credentials.password 
    }).map(res => console.log(resolve(res.json()))); 
    }); 
} 

}

這裏是代碼在調用此方法circles.ts:

login(){ 
let credentials = { 
    username:"01286220336", 
    password:"[email protected]$$w0rd" 
} 
this.authService.login(credentials) 
.then(data => console.log(data)) 
.catch(data => console.log(data)); 

}

我的問題是,當我致電登錄方法Circles.ts沒有發生的事情我不知道爲什麼。我一直在嘗試2周,但我只是放棄了。

此外,我不知道如果我在authservice.ts權利實施登錄方法。

最後,我只是需要以某種方式獲得這個令牌,如果有人可以讓我在正確的方式,我會非常感謝!

+0

問題是格式..你必須設置你登錄的頭以正確的格式發送它(x-www-form-url編碼)beacuse默認它發送爲json ..並且你'已經到Concat的用戶名/密碼/ grant_type如..用戶名= XXXX和密碼= XXXX&grant_type =密碼 –

+0

返回新希望(解析=> { this.http.post('$ {} this.baseUrl/token', '用戶名= $ {credentials.username}&password = $ {credentials.password}&grant_type = password' ).map(res => resolve(res.json())); }); 這是新的片段,仍然沒有任何返回 – Willy

+0

等待你將vostride你的帖子的標題..something如:this.http.post($ {this.baseUrl}/token,username = $ {credentials.username} &password = $ {credentials.pass word}&grant_type = pas sword,{headers:{'Content-type:''x-www-form-urlencoded'}}) –

回答

0

嘗試用以下代碼替換其他部分。

else{ 
    let authObject = "username=xxxx&password=xxxx&grant_type=password"; 
    let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' }); 
    headers.append('Accept', 'application/json'); 
    let options = new RequestOptions({ headers: headers }); 
    return this.http.post(this.baseUrl + '/token', authObject, options) 
     .toPromise() 
     .then(res => { 
      alert(JSON.stringify(res.json(), null, 4)); 
     }); 
} 
相關問題