如何使用jwt在Angular 6和Web API中刷新令牌?

时间:2019-03-26 10:42:39

标签: api jwt owin

我已经在Web API的angular 6项目中使用了jwt令牌。 我可以通过生成令牌登录到会话,但是当令牌到期时,可以说10分钟后。我想显示一个弹出窗口,提示您的会话已过期,请单击下面的刷新会话。这将生成一个新令牌,可用于访问我的门户。

我尝试了下面的代码,并使用下面的一些链接

https://steemit.com/utopian-io/@babelek/how-to-manage-with-refresh-token-in-asp-net-core-2-0-web-api

http://bitoftech.net/2014/07/16/enable-oauth-refresh-tokens-angularjs-app-using-asp-net-web-api-2-owin/

Refresh token (JWT) in interceptor Angular 6

在我的Angular 6的auth Interceptor文件中,我添加了以下代码

intercept(req: HttpRequest<any>, next: HttpHandler) {
    const token = sessionStorage.getItem('token');
    const authReq = req.clone({ setHeaders: { Authorization: 'bearer ' + 
token } });

    return next.handle(authReq).do((event: HttpEvent<any>) => {
        if (event instanceof HttpResponse) {
            // if the token is valid
        }
    }, (err: any) => {
        if (err instanceof HttpErrorResponse) {
            if (err.status === 401) { 
                 const refreshToken =                         
sessionStorage.getItem('refreshToken');

this.loginService.refreshToken([refreshToken]).subscribe((res: any) => {
              const tokenInfo = 
this.loginService.getDecodedAccessToken(res.access_token);
               const loggedUser = tokenInfo.userName;
                    this.loginService.setToken(res.access_token, 
loggedUser, res.refresh_token);
                sessionStorage.setItem('userName', loggedUser);
                 }, error => {


                });
                 this.router.navigateByUrl('/login');
                this.authService.collectFailedRequest(authReq);
            }
        }
    });
  }

在我的登录服务文件中,我添加了以下代码

public getToken(parameter: string[]): Observable<any> {
    const data = new HttpParams()
        .set('username', parameter[0])
        .set('password', parameter[1])
        .set('grant_type', 'password');
    const url = this.API_URL + '/api/confirm_login';
    return this._httpClient.post(url, data.toString()).pipe(
        map(x => x),
        catchError((error: any) => {
            let errorMessage: any;
            if (error.error && error.error.error_description) {
                errorMessage = error.error.error_description;
            }
            throw errorMessage;
        })
    );
}

public refreshToken(parameter: string[]): Observable<any> {

    const data = new HttpParams()
        .set('refresh_token', parameter[0])
        .set('grant_type', 'refresh_token');
    const url = this.API_URL + '/api/refresh_token';
    return this._httpClient.post(url, data.toString()).pipe(map(x => x),
        catchError((error: any) => {
            let errorMessage: any;
            if (error.error && error.error.error_description) {
                errorMessage = error.error.error_description;
            }
            throw errorMessage;
        })
    );
}


public setToken(token: any, getLoggedUser: any, refresh_token: any) {
    sessionStorage.setItem('token', token);
    sessionStorage.setItem('userName', getLoggedUser);
    sessionStorage.setItem('refreshToken', refresh_token);
}


getDecodedAccessToken(token: string): any {
    try {
        return jwt_decode(token);
    } catch (Error) {
        return null;
    }
}

我已在authservice文件中添加

authenticated(): boolean {
const token = sessionStorage.getItem('token');
if (!token) {
  return null;
}
return !this.jwtHelper.isTokenExpired(token);
  }

在我的startup.cs文件中添加

public void ConfigureOAuth(IAppBuilder app)
    {
        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
        OAuthAuthorizationServerOptions OAuthServerOptions = new 
OAuthAuthorizationServerOptions()
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/api/confirm_login"),
            AccessTokenExpireTimeSpan = TimeSpan.FromMilliseconds(30000),
            Provider = new ldAuthorizationServerProvider(),
            AccessTokenFormat = new 
 ldTokenFormat(ConfigurationManager.AppSettings["as:AngularHostURL"]),
            RefreshTokenProvider = new RefreshTokenProvider(),
            AuthorizeEndpointPath = new PathString("/api/refresh_token"),
        };

        app.UseOAuthAuthorizationServer(OAuthServerOptions);
    }

这是我的refreshtokenprovider

public class RefreshTokenProvider : IAuthenticationTokenProvider
    {
    private static ConcurrentDictionary<string, AuthenticationTicket> 
_refreshTokens = new ConcurrentDictionary<string, AuthenticationTicket>();
    public async Task CreateAsync(AuthenticationTokenCreateContext 
  context)
    {
        var guid = Guid.NewGuid().ToString();

        // copy all properties and set the desired lifetime of refresh 
 token  
        var refreshTokenProperties = new 
 AuthenticationProperties(context.Ticket.Properties.Dictionary)
        {
            IssuedUtc = context.Ticket.Properties.IssuedUtc,
            ExpiresUtc = 
  DateTime.UtcNow.AddMilliseconds(30000)//DateTime.UtcNow.AddYears(1)  
        };
        var refreshTokenTicket = new 
   AuthenticationTicket(context.Ticket.Identity, refreshTokenProperties);

        _refreshTokens.TryAdd(guid, refreshTokenTicket);

        // consider storing only the hash of the handle  
        context.SetToken(guid);
    }

    public void Create(AuthenticationTokenCreateContext context)
    {
        throw new NotImplementedException();
    }

    public void Receive(AuthenticationTokenReceiveContext context)
    {
        throw new NotImplementedException();
    }

    public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
    {
        Guid token;

        if (Guid.TryParse(context.Token, out token))
        {
            AuthenticationTicket ticket;

            if (_refreshTokens.TryRemove(token, out ticket))
            {
                context.SetTicket(ticket);
            }
        }
    }

在这里,我的代码未到达GrantRefreshToken方法。我不确定我想念什么。

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

在该示例中,我具有用于登录和刷新令牌的共享令牌端点为/ Token。除令牌端点外,我的代码与您完全相同。当我向邮递员发出请求时,我点击了GrantRefreshToken代码。

enter image description here

或者,为此的角度代码是

refreshToken(): Observable<any> {

let headers = new Headers({ 'Content-type': 'application/x-www-form-urlencoded' });
headers.append('Content-Type', 'application/json');
headers.append('No-Auth', 'True');
var refreshToken = <the guid in the refresh_token local storage>
let body = 'grant_type=refresh_token&refresh_token=' + refreshToken;

return this._http.post(<some url> + '/Token', body, {headers:headers});

}