简体   繁体   中英

How get API response using username and password?

The API is protected with a login. After I enter the login on the direct site, it shows curl result, which contains a token. At some point I was able get the result by doing:

const headers = new HttpHeaders()
    .set('accept', 'application/json')
    .set('Authorization', `Bearer xxxx<); //xxx is the token

and

    this.data = this.http.get(url, { headers: headers }) 

But it doesn't work anymore.

Also, I think I should be able able to do http.post with user credentials, get a token and get json from API using the token. I am kind of confused. I read a lot of SO posts, but neither were helpful in my case. I still get nothing.

Also, the token changes time after time. Could it be the reason?

This seems to work:

this.data = this.http.post(this.url, { headers: headers })
    .subscribe((res) => {
        return res
    })

But this doesn't

this.data = this.http.post(this.url, { username: 'username', password: 'password' }) //with real credentials
    .subscribe((res) => {
        return res
    })

This request gives 405 error:(

this.http.post(this.url, { username: 'username', password: 'password' })
            .subscribe((res) => {
                return res
            })

You likely need an auth interceptor, and need to utilize a refresh token. It's a lot to discover on a whim, but effectively you would store a refresh token (comes with a jwt) in your app, set up an auth interceptor, and on 400s you would try to get a new token with your refresh token, and try the endpoint again.

it's a bit convoluted, but at a high level it makes sense. Access tokens only last 15 minutes, whereas refresh tokens last longer and are used to continually cycle access tokens as they expire. You jut need to stick some fun middleware to handle error cases seamlessly, and never think about it again.

peep https://www.bezkoder.com/angular-12-refresh-token/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM