TECH |
Techable(テッカブル) |
転売・レンタル収益を作者とユーザーに還元。漫画NFTマーケットプレイス「コマワリ」が誕生 |
https://techable.jp/archives/185593
|
日本の漫画 |
2022-09-18 02:00:22 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
[python] youtubedl |
https://qiita.com/hakoritenshi/items/cd78cb4bcd2074d8e8b4
|
config |
2022-09-18 11:33:31 |
Docker |
dockerタグが付けられた新着投稿 - Qiita |
コンテナ上でコマンドを叩いてMySQL8.0の認証をする方法 |
https://qiita.com/shuhei_m/items/441849d4dbf253b4ead7
|
docker |
2022-09-18 11:57:59 |
Docker |
dockerタグが付けられた新着投稿 - Qiita |
Docker+DNS入門 その2:Unboundを用いたキャッシュDNSサーバ構築 |
https://qiita.com/miwamoto/items/7981c390ac876a7fac5e
|
coredns |
2022-09-18 11:55:03 |
Git |
Gitタグが付けられた新着投稿 - Qiita |
Windows+SourceTreeで.github\workflowsがPush出来なくなったときの対処法 |
https://qiita.com/kkkkan/items/5445870c490a223c342e
|
tocreateorupdateworkflow |
2022-09-18 11:00:21 |
海外TECH |
DEV Community |
Angular - Logout when Token is expired |
https://dev.to/tienbku/angular-logout-when-token-is-expired-4151
|
Angular Logout when Token is expiredIn this Angular tutorial I will show you how to logout when JWT Token is expired You also know two approaches to checking if JWT token is expired or not in Angular This tutorial is from BezKoder Check if JWT token is expired or not in AngularThere are two ways to check if Token is expired or not Proactive strategy get expiry time in JWT and compare with current time Reactive strategy read response status from the serverI will show you the implementations of both approaches For we check the token expiration and call logout method dispatch logout event For we dispatch logout event to App component when response status tells us the token is expired We re gonna use the code base for next steps So you may need to read following tutorial first Angular JWT Authentication amp Authorization exampleThe Github source code is at the end of the tutorial Check the token expiration in AngularWith this approach we get expiry time from JWT token stored in Browser Local Storage or Session Storage and compare with the current time private isTokenExpired token string const expiry JSON parse atob token split exp return expiry gt Date now ngOnInit if this isTokenExpired token call logout method dispatch logout event else token is valid send requests For more details about structure of a JWT kindly visit In depth Introduction to JWT JSON Web TokenHow about the Token is stored in HttpOnly Cookie that can t be accessed by JavaScript On client side we don t check the JWT as cookie on server side so we will use Interceptor to catch the HTTP request response from token expiring then send token refresh call and replay the HTTP request Token Refresh endpoint is implemented on the server side and it is a little bit complicated For instructions Spring Boot Refresh Token with JWTNode js Refresh Token with JWTNode js Refresh Token with JWT and MongoDBIn this post we just logout when Token is expired I will write Angular tutorial for Refresh Token soon Logout when Token is expired in AngularTypically you don t check token validity on the client side Angular but catch the response in the Interceptor We will handle JWT token expiration using an HTTP INTERCEPTOR provider With the Interceptor we can add the Bearer token to HTTP requests or handle errors We will dispatch logout event to App component when response status tells us the access token is expired First we need to set up a global event driven system or a PubSub system which allows us to listen and dispatch emit events from independent components so that they don t have direct dependencies between each other We re gonna create EventBusService with three methods on and emit shared event bus service tsimport Injectable from angular core import Subject Subscription from rxjs import filter map from rxjs operators import EventData from event class Injectable providedIn root export class EventBusService private subject new Subject amp lt EventData gt constructor emit event EventData this subject next event on eventName string action any Subscription return this subject pipe filter e EventData gt e name eventName map e EventData gt e value subscribe action shared event class tsexport class EventData name string value any constructor name string value any this name name this value value Now you can emit event to the bus and if any listener was registered with the eventName it will execute the callback function action Next we import EventBusService in App component and listen to logout event src app component tsimport Component from angular core import Subscription from rxjs import StorageService from services storage service import AuthService from services auth service import EventBusService from shared event bus service Component selector app root templateUrl app component html styleUrls app component css export class AppComponent private roles string isLoggedIn false showAdminBoard false showModeratorBoard false username string eventBusSub Subscription constructor private storageService StorageService private authService AuthService private eventBusService EventBusService ngOnInit void this isLoggedIn this storageService isLoggedIn if this isLoggedIn const user this storageService getUser this roles user roles this showAdminBoard this roles includes ROLE ADMIN this showModeratorBoard this roles includes ROLE MODERATOR this username user username this eventBusSub this eventBusService on logout gt this logout logout void this authService logout subscribe next res gt console log res this storageService clean window location reload error err gt console log err Finally we only need to emit logout event in the Angular Http Interceptor import Injectable from angular core import HttpEvent HttpInterceptor HttpHandler HttpRequest HTTP INTERCEPTORS HttpErrorResponse from angular common http import Observable throwError from rxjs import catchError from rxjs operators import StorageService from services storage service import EventBusService from shared event bus service import EventData from shared event class Injectable export class HttpRequestInterceptor implements HttpInterceptor private isRefreshing false constructor private storageService StorageService private eventBusService EventBusService intercept req HttpRequest amp lt any gt next HttpHandler Observable amp lt HttpEvent amp lt any gt gt req req clone withCredentials true return next handle req pipe catchError error gt if error instanceof HttpErrorResponse amp amp req url includes auth signin amp amp error status return this handleError req next return throwError gt error private handleError request HttpRequest amp lt any gt next HttpHandler if this isRefreshing this isRefreshing true if this storageService isLoggedIn this eventBusService emit new EventData logout null return next handle request export const httpInterceptorProviders provide HTTP INTERCEPTORS useClass HttpRequestInterceptor multi true In the code above we intercept requests or responses before they are handled by intercept method handle error status on interceptor response except response of signin request emit logout event if user is logged in Logout when JWT Token is expired without InterceptorThis is another way to logout the user when Token is expired This approach is not recommended because we have to catch error status in every Http Request that accesses protected resources import Component OnInit from angular core import UserService from services user service import StorageService from services storage service import EventBusService from shared event bus service import EventData from shared event class Component selector app board user templateUrl board user component html styleUrls board user component css export class BoardUserComponent implements OnInit content string constructor private userService UserService private storageService StorageService private eventBusService EventBusService ngOnInit void this userService getUserBoard subscribe next data gt this content data error err gt if err error try const res JSON parse err error this content res message catch this content Error with status err status err statusText else this content Error with status err status if err status amp amp this storageService isLoggedIn this eventBusService emit new EventData logout null ConclusionProactive token strategy and the Reactive token strategy have their own pros and cons will always be handled correctly in Reactive strategy but before knowing the token is expired or not it requires response from HTTP Request If we provide a minute or more expiration period the API calls aren t likely to really impose a burden on user Proactive strategy reduces the HTTP Request because the token could expire before the request but it adds overhead to each request Some people could validate the token before sending some HTTP requests but also include replay logic Source CodeYou can find the complete source code for this tutorial on Github Further Reading In depth Introduction to JWT JSON Web Token Angular JWT Authentication amp Authorization example Angular Form Validation example Angular CRUD example with Web API Angular File upload example Angular Pagination example server side Fullstack Angular Spring Boot JWT Authentication amp Authorization example Angular Node js Express JWT Authentication amp Authorization example |
2022-09-18 02:01:41 |
海外ニュース |
Japan Times latest articles |
Ryan McBroom powers Carp past BayStars |
https://www.japantimes.co.jp/sports/2022/09/18/baseball/japanese-baseball/mcbroom-carp-baystars/
|
climax |
2022-09-18 11:13:30 |
海外ニュース |
Japan Times latest articles |
Phil Mickelson: LIV series is ‘here to stay’ |
https://www.japantimes.co.jp/sports/2022/09/18/more-sports/golf/mickelson-liv-here-to-stay/
|
champions |
2022-09-18 11:07:57 |
海外ニュース |
Japan Times latest articles |
Kawasaki’s J1 title hope hit by draw at Kashiwa |
https://www.japantimes.co.jp/sports/2022/09/18/soccer/j-league/frontale-reysol/
|
marinos |
2022-09-18 11:03:14 |
ニュース |
BBC News - Home |
Queen's lying-in-state: How long is the queue? |
https://www.bbc.co.uk/news/uk-62872323?at_medium=RSS&at_campaign=KARANGA
|
thames |
2022-09-18 02:40:53 |
ニュース |
BBC News - Home |
How the Queen's Christian faith went beyond duty |
https://www.bbc.co.uk/news/uk-62942772?at_medium=RSS&at_campaign=KARANGA
|
chaplain |
2022-09-18 02:12:29 |
北海道 |
北海道新聞 |
野田元首相、参列は「人生観」 安倍元首相の国葬巡り |
https://www.hokkaido-np.co.jp/article/732911/
|
安倍元首相 |
2022-09-18 11:26:00 |
北海道 |
北海道新聞 |
台風14号 北海道内19日から21日かけ大雨警戒 |
https://www.hokkaido-np.co.jp/article/732885/
|
北海道内 |
2022-09-18 11:06:40 |
北海道 |
北海道新聞 |
<市場発!>輸入頼みのパプリカ高騰 北海道内産地、市場拡大へ虎視眈々 |
https://www.hokkaido-np.co.jp/article/732218/
|
北海道内 |
2022-09-18 11:23:22 |
北海道 |
北海道新聞 |
山陽新幹線で19日計画運休 広島―博多、始発から |
https://www.hokkaido-np.co.jp/article/732910/
|
山陽新幹線 |
2022-09-18 11:17:00 |
北海道 |
北海道新聞 |
<中国残留邦人のいま 日中国交正常化50年>下 多様性育む 3世の希望 |
https://www.hokkaido-np.co.jp/article/732908/
|
札幌市中央区 |
2022-09-18 11:12:00 |
北海道 |
北海道新聞 |
<拉致問題解決の道>2 拉致被害者・蓮池薫さん(64) 「被害者死亡」はうそ |
https://www.hokkaido-np.co.jp/article/732901/
|
拉致被害者 |
2022-09-18 11:07:00 |
海外TECH |
reddit |
What are the best things about being a gaijin in Japan |
https://www.reddit.com/r/japanlife/comments/xh4cfk/what_are_the_best_things_about_being_a_gaijin_in/
|
What are the best things about being a gaijin in JapanAs the title says submitted by u to r japanlife link comments |
2022-09-18 02:12:05 |
コメント
コメントを投稿