- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我在这里好像在兜圈子,也许是因为使用了如此多的订阅并且不得不将它们链接在一起。
如果 token 已过期,我希望能够使用刷新 token 刷新 token 。这就是我所拥有的,如果可能的话,我真的很感激一个简单的工作示例。
总而言之,我如何确保 AudienceService 首先检查 token 是否有效,如果无效,它会尝试使用刷新 token 刷新它,然后使用适当的 token 调用端点?
app.module.ts:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule } from '@angular/router';
import { Http, RequestOptions } from '@angular/http';
import { ConfirmDialogModule, ListboxModule, PickListModule } from 'primeng/primeng';
import { AppComponent } from './app.component';
import { HeaderComponent } from './components/header/header.component';
import { HomeComponent } from './components/home/home.component';
import { ListAudiencesComponent } from './components/audiences/list-audiences/list-audiences.component';
import { AudienceService } from './services/audience.service';
import { LoggingService } from './services/logging.service';
import { RoleService } from './services/role.service';
import { AuthService } from './services/auth.service';
import { UserService } from './services/user.service';
import { AuthGuard } from './services/auth-guard.service'
import { AuthHttp, AuthConfig, provideAuth } from 'angular2-jwt';
import { ListRolesComponent } from './components/roles/list-roles/list-roles.component';
import { EditRoleAudiencesComponent } from './components/roles/edit-role-audiences/edit-role-audiences.component';
import { ModifyRoleComponent } from './components/roles/modify-role/modify-role.component';
import { LoginComponent } from './components/login/login.component';
import { UnauthorizedComponent } from './components/unauthorized/unauthorized.component';
export function authHttpServiceFactory(http: Http, options: RequestOptions) {
return new AuthHttp(new AuthConfig({
tokenName: 'token',
tokenGetter: (() => sessionStorage.getItem('id_token')),
globalHeaders: [{'Content-Type':'application/json'}],
}), http, options);
}
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
HomeComponent,
ListAudiencesComponent,
ListRolesComponent,
EditRoleAudiencesComponent,
ModifyRoleComponent,
LoginComponent,
UnauthorizedComponent
],
imports: [
BrowserModule,
ConfirmDialogModule,
FormsModule,
HttpModule,
ListboxModule,
PickListModule,
ReactiveFormsModule,
RouterModule.forRoot([
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'unauthorized', component: UnauthorizedComponent },
{ path: 'audiences', component: ListAudiencesComponent, canActivate: [AuthGuard] },
{ path: 'roles', component: ListRolesComponent, canActivate: [AuthGuard] },
{ path: 'roles/modify/:name', component: ModifyRoleComponent, canActivate: [AuthGuard] },
{ path: '**', redirectTo: 'home' }
]),
],
providers: [
{
provide: AuthHttp,
useFactory: authHttpServiceFactory,
deps: [Http, RequestOptions]
},
AudienceService, AuthGuard, AuthService, LoggingService, RoleService, UserService
],
bootstrap: [AppComponent]
})
export class AppModule { }
auth.service.ts:
import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, URLSearchParams } from '@angular/http';
import { environment } from '../../environments/environment';
import { tokenNotExpired } from 'angular2-jwt';
@Injectable()
export class AuthService {
tokenEndpoint = environment.token_endpoint;
constructor(private http: Http ) { }
login(username: string, password: string) {
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers });
let body = new URLSearchParams();
body.set('username', username);
body.set('password', password);
body.set('client_id', '099153c2625149bc8ecb3e85e03f0022');
body.set('grant_type', 'password');
console.log("Got here");
return this.http.post(this.tokenEndpoint, body, options)
.map(res => res.json())
.subscribe(
data => {
localStorage.setItem('id_token', data.access_token);
localStorage.setItem('refresh_token', data.refresh_token);
},
error => console.log(error)
);
}
loggedIn() {
if (tokenNotExpired()) {
return true;
} else {
this.refreshToken()
.subscribe(
data => {
if (data.error) {
this.logout();
} else {
localStorage.setItem('id_token', data.access_token);
localStorage.setItem('refresh_token', data.refresh_token);
console.log("Token was refreshed.");
}
},
error => this.logout(),
() => {
return tokenNotExpired();
}
);
}
}
refreshToken() {
let refToken = localStorage.getItem('refresh_token');
if (refToken) {
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers });
let body = new URLSearchParams();
body.set('client_id', '099153c2625149bc8ecb3e85e03f0022');
body.set('grant_type', 'refresh_token');
body.set('refresh_token', refToken);
return this.http.post(this.tokenEndpoint, body, options)
.map(res => res.json());
} else {
this.logout();
}
}
tokenRequiresRefresh(): boolean {
if (!this.loggedIn()) {
console.log("Token refresh is required");
}
return !this.loggedIn();
}
logout() {
localStorage.removeItem('id_token');
localStorage.removeItem('refresh_token');
}
}
audience.service.ts:
import 'rxjs/Rx';
import { Observable } from 'rxjs/Observable';
import { environment } from '../../environments/environment';
import { AuthHttp } from 'angular2-jwt';
import { AuthService } from './auth.service';
import { AddDeleteAudienceModel } from './AddAudienceModel';
@Injectable()
export class AudienceService {
baseApiUrl = environment.api_endpoint;
constructor(private http: Http, private authHttp: AuthHttp, private authService: AuthService) { }
getAllAudiences()
{
if (this.authService.tokenRequiresRefresh()) {
this.authService.refreshToken();
}
if (this.authService.loggedIn()) {
return this.authHttp.get(this.baseApiUrl + 'audience/all').map(res => res.json());
}
}
}
最佳答案
auth.service.ts
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Http, Headers, RequestOptions, URLSearchParams } from '@angular/http';
import { environment } from '../../environments/environment';
import { tokenNotExpired, JwtHelper } from 'angular2-jwt';
import { Subject, Observable } from 'rxjs';
@Injectable()
export class AuthService {
tokenEndpoint = environment.token_endpoint;
requireLoginSubject: Subject<boolean>;
tokenIsBeingRefreshed: Subject<boolean>;
lastUrl: string;
jwtHelper: JwtHelper = new JwtHelper();
constructor(private http: Http, private router: Router) {
this.requireLoginSubject = new Subject<boolean>();
this.tokenIsBeingRefreshed = new Subject<boolean>();
this.tokenIsBeingRefreshed.next(false);
this.lastUrl = "/home";
}
isUserAuthenticated() {
if(this.loggedIn()) {
this.requireLoginSubject.next(false);
return true;
} else {
return false;
}
}
login(username: string, password: string) {
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers });
let body = new URLSearchParams();
body.set('username', username);
body.set('password', password);
body.set('client_id', '099153c2625149bc8ecb3e85e03f0022');
body.set('grant_type', 'password');
return this.http.post(this.tokenEndpoint, body, options).map(res => res.json());
}
loggedIn() {
return tokenNotExpired();
}
addTokens(accessToken: string, refreshToken: string) {
localStorage.setItem('id_token', accessToken);
localStorage.setItem('refresh_token', refreshToken);
}
getRefreshTokenExpirationDate() {
var token = localStorage.getItem('id_token');
if (token) {
let tokenExpDate = this.jwtHelper.getTokenExpirationDate(token);
let sessionExpDate = new Date(tokenExpDate.getTime() + 4*60000);
if (new Date() > sessionExpDate) {
this.logout();
}
return sessionExpDate;
}
return null;
}
hasRefreshToken() {
let refToken = localStorage.getItem('refresh_token');
if (refToken == null) {
this.logout();
}
return refToken != null;
}
refreshTokenSuccessHandler(data) {
if (data.error) {
console.log("Removing tokens.");
this.logout();
this.requireLoginSubject.next(true);
this.tokenIsBeingRefreshed.next(false);
this.router.navigateByUrl('/unauthorized');
return false;
} else {
this.addTokens(data.access_token, data.refresh_token);
this.requireLoginSubject.next(false);
this.tokenIsBeingRefreshed.next(false);
console.log("Refreshed user token");
}
}
refreshTokenErrorHandler(error) {
this.requireLoginSubject.next(true);
this.logout();
this.tokenIsBeingRefreshed.next(false);
this.router.navigate(['/sessiontimeout']);
console.log(error);
}
refreshToken() {
let refToken = localStorage.getItem('refresh_token');
//let refTokenId = this.jwtHelper.decodeToken(refToken).refreshTokenId;
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers });
let body = new URLSearchParams();
body.set('client_id', '099153c2625149bc8ecb3e85e03f0022');
body.set('grant_type', 'refresh_token');
body.set('refresh_token', refToken);
return this.http.post(this.tokenEndpoint, body, options)
.map(res => res.json());
}
tokenRequiresRefresh(): boolean {
if (!this.loggedIn()) {
console.log("Token refresh is required");
}
return !this.loggedIn();
}
logout() {
localStorage.removeItem('id_token');
localStorage.removeItem('refresh_token');
this.requireLoginSubject.next(true);
}
}
auth-http.service.ts
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import 'rxjs/Rx';
import { Observable } from 'rxjs/Observable';
import { environment } from '../../environments/environment';
import { AuthHttp } from 'angular2-jwt';
import { AuthService } from './auth.service';
@Injectable()
export class AuthHttpService {
constructor(private authHttp: AuthHttp, private authService: AuthService, private router: Router) { }
get(endpoint: string) {
if (this.authService.tokenRequiresRefresh()) {
this.authService.tokenIsBeingRefreshed.next(true);
return this.authService.refreshToken().switchMap(
(data) => {
this.authService.refreshTokenSuccessHandler(data);
if (this.authService.loggedIn()) {
this.authService.tokenIsBeingRefreshed.next(false);
return this.getInternal(endpoint);
} else {
this.authService.tokenIsBeingRefreshed.next(false);
this.router.navigate(['/sessiontimeout']);
return Observable.throw(data);
}
}
).catch((e) => {
this.authService.refreshTokenErrorHandler(e);
return Observable.throw(e);
});
}
else {
return this.getInternal(endpoint);
}
}
post(endpoint: string, body: string) : Observable<any> {
if (this.authService.tokenRequiresRefresh()) {
this.authService.tokenIsBeingRefreshed.next(true);
return this.authService.refreshToken().switchMap(
(data) => {
this.authService.refreshTokenSuccessHandler(data);
if (this.authService.loggedIn()) {
this.authService.tokenIsBeingRefreshed.next(false);
return this.postInternal(endpoint, body);
} else {
this.authService.tokenIsBeingRefreshed.next(false);
this.router.navigate(['/sessiontimeout']);
return Observable.throw(data);
}
}
).catch((e) => {
this.authService.refreshTokenErrorHandler(e);
return Observable.throw(e);
});
}
else {
return this.postInternal(endpoint, body);
}
}
private getInternal(endpoint: string) {
return this.authHttp.get(endpoint);
}
private postInternal(endpoint: string, body: string) {
return this.authHttp.post(endpoint, body);
}
}
audience.service.ts
import { Injectable } from '@angular/core';
import 'rxjs/Rx';
import { Observable } from 'rxjs/Observable';
import { environment } from '../../environments/environment';
import { AuthHttpService } from './auth-http.service';
import { AddDeleteAudienceModel } from './AddAudienceModel';
@Injectable()
export class AudienceService {
baseApiUrl = environment.api_endpoint;
constructor(private authHttpService: AuthHttpService) { }
getAllAudiences()
{
return this.authHttpService.get(this.baseApiUrl + 'audience/all').map(res => res.json());
}
addAudience(model: AddDeleteAudienceModel) {
return this.authHttpService.post(this.baseApiUrl + 'audience', JSON.stringify(model)).map(res => res.json());
}
deleteAudience(model: AddDeleteAudienceModel) {
return this.authHttpService.post(this.baseApiUrl + 'audience/delete', JSON.stringify(model)).map(res => res.json());
}
}
关于Angular2-jwt - AuthHttp,刷新 token ,将它们放在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41705618/
我当前项目中的许多类都有几个只能从类本身内部调用的属性和方法。此外,根据类(class)的当前状态,它们可能会扰乱类(class)的工作。 目前,所有这些接口(interface)都在 .h 文件的主
我想使用ngbTabSet将nav-pills in card-header 和tab-content in card-body。但我不知道该怎么做。 这是我尝试实现的示例(使用 bootstrap.
我正在浏览文档以查找如何允许放置在停靠栏图标上。据我所知,建议您使用 LSItemContentTypes,因为 CFBundleTypeOSTypes 已弃用。但是,我无法让 LSItemConte
我正在尝试在书签中使用 jquery UI 作为 slider 。并且 jquery ui 要求在普通 jquery 文件之后包含该文件。 所以到目前为止我所尝试的只是将脚本附加到 header ,同
您好,我尝试了广泛的谷歌搜索,但似乎没有任何帮助。 这是我的场景: 公司 Logo 存储在外部域/网址(矩形)中。 带有谷歌地图的 Ionic 应用程序,将这些 Logo 作为标记放置在 map 上。
我今天在阅读我的一些 C# 代码时发现了这一行: if (ProgenyList.ItemContainerGenerator.Status != System.Windows.Controls.Pr
我刚遇到this question在 Go FAQ 中,它让我想起了困扰我一段时间的事情。不幸的是,我真的不明白答案是什么。 似乎几乎所有非 C 类语言都将类型放在变量名之后,如下所示: var :
这是有效的 HTML 吗? 最佳答案 作为元素可以包含 phrasing content ,以及属于该组,则有效。 从语义上(并且具有一些常识),如果唯一的内容是 , 不;如果它同时包含文本和图像
这是有效的 HTML 吗? 最佳答案 作为元素可以包含 phrasing content ,以及属于该组,则有效。 从语义上(并且具有一些常识),如果唯一的内容是 , 不;如果它同时包含文本和图像
我有两本 T.Parr 写的关于 ANTLR 的书,我到处都看到美元符号和符号的引用。它也对我有用: term : IDENT -> { new TokenNode($IDENT) }; 或更复杂的东
我在实现段控制时遇到了一些问题。因为我希望它是一个固定的标题,所以当我滚动时我总是可以看到它,我已经在 - (UIView *)tableView:(UITableView *)tableView v
我有一个 20x36px (10x18pt) 的箭头图像,当我选择一个 UIImageView 时,将它拖到我的 View Controller 上然后设置图像,它总是模糊的。我只在我的项目中包含 @
How can I put background image when I hover a link Insert Bg in this a when hov
我需要在我的 .container 中添加(最新的第一个)新分区,但在 .controls (按钮)之后。可能吗? 注意:添加新的分区来保存按钮下方的前置控件对我来说不是一个选择。 HTML 需要保持
我是一名优秀的程序员,十分优秀!