Angular身份验证服务-基于令牌

时间:2018-09-03 11:06:02

标签: angular api authentication web token

在我的AuthenticationService中,我有:

@Injectable()
export class AuthenticationService {
constructor(private http: HttpClient) { }

login(username: string, password: string) {                                
    return this.http.post<any>
    (`${environment.apiUrl}/token`, "grant_type=password&username="+username+"&password="+password).pipe(map(user => {                
            // login successful if there's a jwt token in the response                      
            if (user && user.token) {
                // store user details and jwt token in local storage to keep user logged in between page refreshes
                localStorage.setItem('currentUser', JSON.stringify(user));                    
            }                                
            return user;
        }));
}

if (user && user.token)中,user.token返回undefined,然后不创建currentUser localStorage。

如果我只写:if (user) ...,它可以工作并生成如下的access_token:

access_token:"eiGcvwEa0SsL0xml2Y5BcnR5W1g-vTniUB96YPFsnWe7AwG-pEmtLaOf1nurnYOFFJ-qpax5QceWD9qkEtXJIWU91DFvDwEOrrRqIrb1-gBFnspTk6dE6YjIXpZqkcA1JHWJezQx0dfqBINhZ08qocfIrqK0IqqOvguRh9-PUJCPRMg4JaYh3CJGAZVqbFi8WiO4OwRwrBVqXXGWSHqoCUgHxWDYolCZE7axCLDdbTcbCz2IluemsA0kdmvyQ2laub3iELFN-5m7dAvpCYtFvHjt2qkYijH_v2E3uV5dux5e_txj4XSTzoT8kikoCn7I"
expires_in:59
refresh_token:"c723ec64-c90e-482d-8292-390214d5324b"
token_type:"bearer"

我需要从user.token获取令牌,但是我不知道我在哪里错了。

2 个答案:

答案 0 :(得分:0)

您确定user对象具有属性token吗? (尝试将user记录到控制台)。

也许您要查找的属性是access_token

答案 1 :(得分:0)

因为属性是access_token而不是token。尝试if(user && user.access_token)