Upgrading AuthService

From Solution Explorer, navigate to the /ClientApp/app/services/ folder, open the auth.service.ts file, and add the following code to the existing content, after the login() method:

[...]

// try to refresh token
refreshToken(): Observable<boolean> {
var url = "api/token/auth";
var data = {
client_id: this.clientId,
// required when signing up with username/password
grant_type: "refresh_token",
refresh_token: this.getAuth()!.refresh_token,
// space-separated list of scopes for which the token is issued
scope: "offline_access profile email"
};

return this.getAuthFromServer(url, data);
}

// retrieve the access & refresh tokens from the server
getAuthFromServer(url: string, data: any): Observable<boolean> {
return this.http.post<TokenResponse>(url, data)
.map((res) => {
let token = res && res.token;
// if the token is there, login has been successful
if (token) {
// store username and jwt token
this.setAuth(res);
// successful login
return true;
}

// failed login
return Observable.throw('Unauthorized');
})
.catch(error => {
return new Observable<any>(error);
});
}

[...]

As we can see, the new refreshToken() method features a strong resemblance with the login() method we implemented back in Chapter 8, Authentication and Authorization, except for some minor differences; it asks for a different grant_type, which also requires sending the refresh_token instead of username and password, and it invokes a new getAuthFromServer() method to actually retrieve the auth info from the server.

By taking a closer look at the getAuthFromServer() implementation, we can see how we can easily call it from the login() method as well and get rid of a fair amount of repeating code:

[...]

login(username: string, password: string): Observable<boolean> {
var url = "api/token/auth";
var data = {
username: username,
password: password,
client_id: this.clientId,
// required when signing up with username/password
grant_type: "password",
// space-separated list of scopes for which the token is issued
scope: "offline_access profile email"
};

return this.getAuthFromServer(url, data);
}

[...]

Our improved AuthService is now ready to refresh tokens; we just need to find a way to use the new feature.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.216.254