投稿時間:2021-04-13 22:40:10 RSSフィード2021-04-13 22:00 分まとめ(51件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
IT 気になる、記になる… 「Surface Laptop 4」には「Surface Earbuds」がバンドルされるかも https://taisy0.com/2021/04/13/138903.html surfaceearbuds 2021-04-13 12:38:56
IT 気になる、記になる… 「iPhone 12/12 Pro」用純正シリコーンケースの新色の実物写真が流出 − アメジストなど4色に https://taisy0.com/2021/04/13/138900.html apple 2021-04-13 12:20:44
IT 気になる、記になる… 「iPhone 13」とされる3Dレンダリング画像が登場 − リアカメラの配置が変わる模様 https://taisy0.com/2021/04/13/138888.html iphone 2021-04-13 12:06:52
TECH Engadget Japanese ディスプレイがくるっと回る「Echo Show 10」ショートインプレ https://japanese.engadget.com/echo-show-10-amazon-121915855.html amazon 2021-04-13 12:19:15
python Pythonタグが付けられた新着投稿 - Qiita Python+SeleniumでNEOBANK(住信SBIネット銀行)の明細取得(CSVダウンロード) https://qiita.com/yoshi2045/items/46965646afc473c61a83 明細表示browserfindelementbylinktext表示clickここではリンクテキストを元に指定してみました。 2021-04-13 21:26:44
js JavaScriptタグが付けられた新着投稿 - Qiita Apps ScriptとQRコードで、あれ、どこにしまったっけ?解消 https://qiita.com/quantum_cpa/items/2b50b0167f73252a7233 AppsScriptとQRコードで、あれ、どこにしまったっけ解消作ったもの家にあるモノを、どこにしまったか記録・管理する仕組みAppsScriptの練習兼ねて作ったamp作りながら考えたものであり、リファクタリングはしてませんorz使い方初回登録時モノに貼ったQRコードをスマホで撮影、モノの名前を登録初回登録以降モノのQRコードを撮影⇒収納場所のQRコードもスマホで撮影して収納場所を更新元からバーコードがついている商品は、そのバーコードを読み取って名前登録でもOK収納場所には、収納場所の名を埋め込んだQRコードが必要本については、honnoinfoからタイトルを取ってくるので、商品名の入力は不要使ったツールGoogleAppsScriptGoogleスプレッドシートiOSショートカットラベルプリンターBrotherPtouchRQRコードのラベルが作れる普通のプリンターを使う場合honnoinfo参考にしたampコードを拝借したサイト続・Webの技術だけで作るQRコードリーダーGoogleスプレッドシートでISBNから書籍のタイトル・出版社名・著者名・発売日・本体価格・判型・表紙画像・バーコード上段のみを表示するための関数とURL追記あり仕組みの大枠Googleスプレッドシートに、モノと収納場所の一覧を作成iOSの場合ショートカットアプリを利用して、QRコードまたはバーコードを読み取りAndroidの場合JavaScriptベースのQRコードリーダーで読み取り作成したWebアプリのURLに「scany」を付ける読み取った結果をAppsScriptで作成したWebアプリに投げてスプレッドシートを更新作り方Googleスプレッドシート「main」というシートを作成以下の列を作成No列は結局使わなかったが。 2021-04-13 21:41:27
js JavaScriptタグが付けられた新着投稿 - Qiita ReactJSプロジェクトindex.jsとindex.htmlの役割 https://qiita.com/blackdot/items/1ba43906caec303c8c82 IndexhtmlファイルWikiにspaを検索すると以下のように説明しています。 2021-04-13 21:36:12
js JavaScriptタグが付けられた新着投稿 - Qiita (備忘用)React Refの関数がいつからか変わってた https://qiita.com/miguel344/items/12fc06b957407ce68ff3 他にもあるかもしれませんが、備忘用に。 2021-04-13 21:01:54
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) 検索で、半角英数字では問題ないが全角(かな、カナ、漢字)でエラー発生 https://teratail.com/questions/333071?rss=all 検索で、半角英数字では問題ないが全角かな、カナ、漢字でエラー発生前提・実現したいこと学習開始ヶ月の初心者です。 2021-04-13 21:50:56
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) Atcoder Beginner Contest-151-C がACできない(C++) https://teratail.com/questions/333070?rss=all AtcoderBeginnerContestCがACできないCABCC問題でなぜ想定した答えが出ないのか分からないのでご教授ねがいます。 2021-04-13 21:49:15
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) WikiExtractor.pyのエラーについて https://teratail.com/questions/333069?rss=all WikiExtractorpyのエラーについて前提・実現したいことpython初学者です。 2021-04-13 21:41:18
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) サイドバーと横並びにメイン画面を表示させたい https://teratail.com/questions/333068?rss=all サイドバーと横並びにメイン画面を表示させたい前提・実現したいことrailsにて、ヘッダーとサイドバーは共通のビューを表示し、メイン画面は機能によって表示を変える様にしたいです。 2021-04-13 21:36:07
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) rails sでサーバを立ち上げたい。 https://teratail.com/questions/333067?rss=all railssでサーバを立ち上げたい。 2021-04-13 21:25:27
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) RかTableauで収益マネジメントの分析をしたい https://teratail.com/questions/333066?rss=all RかTableauで収益マネジメントの分析をしたい前提・実現したいこと現在、約万件の会社のデータ過去年分で収益管理について調べています。 2021-04-13 21:17:44
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) std:vectorの要素をdeleteしたい https://teratail.com/questions/333065?rss=all class 2021-04-13 21:10:15
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) ポインタが指す値の参照方法 https://teratail.com/questions/333064?rss=all ポインタが指す値の参照方法発生している問題・エラーメッセージ現在ポインタについて学習中なのですが、入力した数字に対応する月の名前を返す関数GetOldMonthを作成するという問題で下記のようなソースコードを作成しました。 2021-04-13 21:06:00
Ruby Rubyタグが付けられた新着投稿 - Qiita 複数の配列を比較し、共通項の数を算出する https://qiita.com/tetsuya_kanamaru/items/9bbe2b43564b37c3bce0 親配列と子配列を比較し、共通の数字の数を出力します。 2021-04-13 21:24:30
AWS AWSタグが付けられた新着投稿 - Qiita Fargate タスクを定期実行したいときに EventBridge 以外の選択肢も検討してみる https://qiita.com/tsubasaogawa/items/762edac32ffbfec1d5d4 EventBridgeはタスクのRunTaskの実行を保証するただしRunTaskによってタスクが起動したかどうかは保証しない筆者も経験があるが、稀にAWS側の不具合でFargateが起動に失敗することがあった。 2021-04-13 21:54:33
Docker dockerタグが付けられた新着投稿 - Qiita 【Docker】MySQLに接続できないエラー(php_network_getaddresses: getaddrinfo failed: Name or service not known) https://qiita.com/mineaki27th/items/2fec99060f1c97ec2892 【Docker】MySQLに接続できないエラーphpnetworkgetaddressesgetaddrinfofailedNameorservicenotknownDockerを用いてlaravelの環境構築を試みている時に起こったエラーです。 2021-04-13 21:20:46
海外TECH Ars Technica The era of reusability in space has begun https://arstechnica.com/?p=1756408 Detail Nothing 2021-04-13 12:36:25
海外TECH DEV Community What is lean canvas https://dev.to/olgagalikua/what-is-lean-canvas-1ggl What is lean canvasYou need a plan That s what start up entrepreneurs are told when they take the first step in turning their ideas into a profitable venture The entrepreneurial journey is so fast paced that you stand to veer off target if you re not armed with a plan Yet if you turn to conventional planning tools like the business model canvas you ll end up spending too much time researching matters that are not relevant at the startup stage This is where the lean canvas proves to be handy a quicker way to provide an accurate idea of the key variables relevant to your startup In this article we ll take a look at what lean canvas is all about and why it s best suited for startups What Is Lean Canvas The lean canvasis a business modeling template based on the conventional business model canvas It was created by Ash Maurya where he made changes to the business model canvas to suit a startup s needs The lean canvas consists of nine blocks each indicating key elements vital for a startup s success A startup s success is determined by how it s able to move quickly against the market forces Its priority is the customers their problems and offering solutions that work The founder cannot afford to spend precious time making lengthy business plans at that stage The lean canvas is built with efficiency in mind It removes original blocks from the business model canvas that are not relevant for a startup and replaces them with important blocks for startups Here are the different blocks in a lean canvasCustomer segmentsProblemsRevenue streamsSolutionUnique value proposition ChannelsKey metricsCost structureUnfair advantage The Problems Solutions Metrics and Unfair Advantage are blocks introduced in the lean canvas They are relevant to the startup s circumstances and allow founders to be more solution focused when crafting their business plans The lean canvas is meant as a page template for founders to quickly put their plans onto paper for an overall picture It serves as the basis to create solutions and test them early onーall that without sitting down and drafting a pages business plan Why Lean Canvas Is The Best Option For Startups Startup founders whose most precious commodity is time have found the lean canvas to be the perfect tool in charting their business plan If you re just stepping into the entrepreneurial world you ll want to use lean canvas too Here s why Quick creation and update You can build your own lean canvas template or download them from the internet It only takes a single piece of paper to print it out and start drafting on it Or you could stick with the digital version If you already have a solid plan in your mind it doesn t take much time to organize them on the template A startup has to deal with changes almost every day It is susceptible to many elements and the path may change to adapt to market circumstances The lean canvas is meant as a template that you could update as your business grows For example you may have discovered an untapped marketing channel to reach your customer and you can add it to the Channel block The Unfair Advantage is an interesting block on the lean canvas Do you offer the best technical expertise in the industry Or delivery speed way faster than competitors Jot them down and leverage them to give your startup a competitive edge in the market Easily shareableWhen you re running a startup you will eventually need a team Onboarding is a tricky process for a budding startup and you ll need each team member to understand how the company works quickly Sharing the lean canvas is an easy way to get all members on the same page in understanding the company Being a single page document it doesn t take much effort to print a copy for your team or to drop one in their inbox ConciseThere are times when you ll need to write lengthy business plans but that s when you re pitching to investors At the early stage you ll want to form a plan and validate its viability in little time That s where you ll find lean canvas helpful Each of the blocks is well defined with the type of ideas or points to fill in It s a norm to fill in those blocks with key points which are short and concise SummaryAs far as business planning is concerned the lean canvas is the ideal tool for startup founders Its straight to the point template allows founders to bring clarity to their business ideas quickly 2021-04-13 12:20:54
海外TECH DEV Community Introducing to you - Polyglot https://dev.to/pranavbaburaj/introducing-to-you-polyglot-22g1 Introducing to you PolyglotI ve recently been working on a side project called polyglot Polyglot is a python module that finds the percentage of different programming languages used in your project pranavbaburaj polyglot Find the percentage of programming languages used in your project You can check it out on Github and also drop a star Get StartedIn order to get started you will need to have python and pip installed on your system Check the versions of python and pippython vpip vInstall python polyglot using pipTo install python polyglot in your system usepip install python polyglot How to use itOnce Polyglot is all set up and good to go implementing is easy as pie from polyglot core import Polyglot dot represents the current working directorydirname or path to dir poly Polyglot poly show This prints out something similar Language files Ignore List GCC Machine Description Unknown Text Python JSON Language lines Ignore List GCC Machine Description Unknown Text Python JSON IgnoresThe ignore option is used to ignore specific files in the directory tree For instance if you don t want the JSON files to appear in the table you can add the json extension to a polyglot ignore file and pass it as a parameter while creating the polyglot instance Polyglot IgnoresPolyglot ignores are used to ignore specific files in the directory tree They should have a polyglot file extension Polyglot Ignores as similar to gitignores and are easy to write with almost the same syntax Writing a Polyglot ignore Create a test polyglot file and add the files to ignore for a specific file extension json for a specific folderdist for a specific filedub sdlLICENSE for specific folders in the directory toxOnce you have an ignore file use it with polyglot like thispoly Polyglot dirname ignore test polyglot Argumentsfrom polyglot arugments import ArgumentsThe Polyglot Arguments is used to parse a list of arguments sys argv by default and perform actions related to Polyglot You can either pass in arguments manuallyargs Arguments arguments show True dir o out json ignore test polyglot return value False or leave it blank to parse the command line arguments passed in along with the fileargs Arguments Start the argument parserargs parse The command line parser has four main options dir default current directory The directory path show default True Whether to display the table or not o default None Outputs the data as JSON in the file ignore default None The ignore fileAn example usagepython B lt filename gt py dir show FalsePlease star the project on GitHub if you like it And thank you for scrolling 2021-04-13 12:19:27
海外TECH DEV Community JWT and Go. How to integrate them with security requirements https://dev.to/abrichak/jwt-and-go-how-to-integrate-them-with-security-requirements-eh5 JWT and Go How to integrate them with security requirementsHey there I am Alexander Brichak Golang developer at NIX Using commonly accepted solutions and technologies developers rarely think about the risks of a particular solution if used incorrectly and whether it is suitable for the tasks to which they are trying to apply This fully applies to such a popular technology as JWT In this article I want to discuss the problems that arise when using JWT tokens in client applications and also consider some interesting solutions for a backend server implemented in Golang Why Golang The high performance of this language makes it easier to work with high load software and microservice architecture Its scope is wide and the syntax is easy to learn The Golang community is growing all over the world Therefore NIX has developed a free learning platform for beginners For those who already deal with Go the article will be useful when creating Web applications in Golang and for those who are looking for ready made solutions for implementing such non standard JWT functions as logging and automatic logging of users How to make sure that the data received by the web application server backend or API was actually sent by this or that user This helps identify the JSON Web Token technology When using web tokens to access APIs for client applications always remember that the token can fall into the hands of attackers Therefore usually after authentication the user receives not just one token but two short lived access token It can be reused to get resources from the server The life cycle of a token is displayed in the payload part and is often limited to hours or even minutes depending on the application The standard JWT libraries when validating a token by default check to see if it has expired The attacker who received the access token will have a very limited time to act on behalf of the user refresh token with a long term of use It allows you to renew a pair of tokens after the access token expires A similar mechanism is adopted in particular in the OAuth protocol In frontend applications when using JWT the scheme of work will be as soon as the server returned access and refresh tokens in response to the username and password the system remembers this pair of tokenson each call to the API the frontend application adds a header with an access token to the HTTP request If the token is not expired the server returns a responseif the access token is expired the server responds with an HTTP Unauthorized error status To get a new pair of tokens the application first needs to access a special API endpoint on the server and pass a refresh token Then repeat the HTTP request to get the data with the already generated access token In JavaScript for example it is convenient to implement such a mechanic in the axios library using interceptors How to make a token invalid and why you need itJSON Web token was originally created as a stateless mechanism for authorization in order not to store information on the server The validity period of the token is recorded automatically After the expiration of time it simply becomes invalid and is not accepted by the server This scheme is excellent because it does not require additional server resources to remember the state Let s imagine that we need to implement a logout the user exits the application On the frontend this is easily accomplished by forgetting a pair of tokens To continue working with the application the user must again enter his username and password and receive a new set of tokens But what if the token fell into the hands of an attacker In the event of theft if the hacker got the refresh token he will have enough time to do something on behalf of the user While a real user has no way to revoke tokens and stop the attacker The only thing that will save you is blocking the user on the server or replacing the secret string with which tokens are signed After this operation all issued tokens will become invalid Therefore RFC which describes the OAuth protocol requires additional measures to identify the illegal use of the refresh token Here you can use the authentication of the user who sent this token Another way is to rotate the refresh token after which it is invalidated and stored on the server If in the future someone tries to use it it will signal a possible hack All these considerations most of the time lead to the need to transform stateless tokens into stateful i e storing some information on the server that allows you to declare the tokens of a certain user invalid Then with each user request the server first checks the validity of the token based on the information in the token itself in particular the expiration date and then based on the information on the server There are many ways to organize this process for example store blacklist tokens on the server The list is formed after logging out or updating a pair of tokens When accessing the server with a token from the blacklist the user will receive an authorization error store the blacklist of users on the server It can contain user ID and logout time Any tokens issued to the user earlier than the moment of logout will be invalid store information on the issued tokens on the server linked to the user ID The token passed by the user application in the request to the server will be valid if its information matches the data about the token issued for this user Exotic methods create secret lines for signing tokens for each user This will allow you to change the line to invalidate the tokens of a specific user change user ID if his tokens are compromised After that the old tokens will not match any user To validate the token many of these methods require an additional query to the database each time the user accesses the server To reduce the load on the database and speed up the processing of the request other options for storing information about tokens are used For example in memory database A lot of other ideas you can find here and here Automatic log out and JWTIn many user applications it is required to implement automatic logout disconnecting the user in case of inactivity for some time The function especially concerns applications that provide access to personal data and other sensitive information bank accounts or records in the medical history In particular the American HIPAA standards apply such a requirement to applications that provide access to users secure electronic health information ePHI Of course it is important that the user frontend application somehow tracks the user s inactivity period and makes a request to logout when the inactivity period is exceeded But given the notion that the backend server should not rely on the validation routines of the frontend application it becomes clear that the backend needs its own way of detecting user inactivity The main flow of interaction between the frontend application and the outside world occurs through the API on the backend server Therefore the user s activity on his part can be considered the execution of requests to the API and inactivity the period between two requests of the same user The backend server s job is to track this time interval between requests and force logout if the maximum inactivity period is exceeded NIX team s solution using stateful tokensOur approach goes beyond stateless tokens and involves storing information about issued tokens on the server in Redis In addition to the user ID we add another ID to the tokens to match the token with the information recorded on the server This article describes in detail such a scheme for working with tokens The main benefit of a Redis database is its automatic logout Thanks to the mechanism of automatic expiration expiration of data in the Redis database it was possible to establish such a method of storing and updating information about issued tokens in which after the expiration of the maximum allowed period between user requests information about his tokens is automatically deleted from the Redis database Tokens become invalid For example take a boilerplate application written in the Golang Echo web framework It has already implemented registration and user login updating a pair of tokens using a refresh token and there is a set of tests Next we will consistently change it to get the desired result There is also Swagger documentation here which is handy to use to test our changes Updates made to the boilerplate application code are available in the repository under the feature JWT logout branch Improving the template applicationThe boilerplate application uses the dgrijalva jwt go library to work with JWTs Besides the standard set of claims fields this library allows you to describe additional fields In the application this makes it possible to write to the token the ID of the user to whom it was issued The library supports the NewWithClaims and Parse functions used in the AuthHandler application to create and validate tokens Also the Echo framework has a JWT middleware that uses the specified library to validate tokens This middleware is hooked up in the ConfigureRoutes function of the template application that declares the routing The current implementation of the boilerplate application uses exclusively stateless tokens In this case there is no way to declare the tokens invalid before their expiration date In addition to the impossibility of a full fledged logout this leads to the following scenario with one refresh token you can contact the API endpoint refresh several times Our further changes should solve this problem as well Let s move on to the implementation of our ideas In the Redis database we will store certain information about the issued tokens for each user We need to add the following components to the application code connecting to the Redis databaserecording information about issued tokens in Redis when generating a pair of tokenschecking the existence of a token in Redis for routes protected by authorizationdeleting records from Redis when the user accesses API endpoint logout Redis connectionSince our templated application uses docker compose we can easily add a container with a Redis database by declaring it in docker compose yml echo redis image redis container name REDIS HOST restart unless stopped ports REDIS EXPOSE PORT REDIS PORT networks echo demo stackTo create a container we need to enter the values ​​REDIS HOST REDIS PORT REDIS EXPOSE PORT into the env file To connect to the Redis server you need to add the RedisConfig structure to the config package package configimport os type RedisConfig struct Host string Port string func LoadRedisConfig RedisConfig return RedisConfig Host os Getenv REDIS HOST Port os Getenv REDIS PORT Then the InitRedis function into the db package To connect it uses the library github com go redis redis github com go redis redis func InitRedis cfg config Config redis Client addr fmt Sprintf s s cfg Redis Host cfg Redis Port return redis NewClient amp redis Options Addr addr We call the InitRedis function in the NewServer method of the server package when starting the application func NewServer cfg config Config Server return amp Server Echo echo New DB db Init cfg Redis db InitRedis cfg Config cfg Storing information about tokensNow that we have a connection to Redis we can start saving information about issued tokens To do this we only need to change the service code in the token package We will save not the token itself but some unique UID This identifier will also appear in the claims of the corresponding token After parsing the token that came in the user s request and checking the UID with what is stored on the server we will always know if this token is active Add the UID field to JwtCustomClaims and to the createToken method type JwtCustomClaims struct ID uint json id UID string json uid jwtGo StandardClaims We will create the UID using the github com google uuid library Let s also add the generated UID to the list of output parameters of the createToken method func tokenService Service createToken userID uint expireMinutes int secret string token string uid string exp int err error exp time Now Add time Minute time Duration expireMinutes Unix uid uuid New String claims amp JwtCustomClaims ID userID UID uid StandardClaims jwtGo StandardClaims ExpiresAt exp Now let s declare a structure that will be saved on the server every time a pair of tokens is generated type CachedTokens struct AccessUID string json access RefreshUID string json refresh Since our service in the token package will need a connection to Redis let s change the service declaration and the NewTokenService method as follows type Service struct server s Server func NewTokenService server s Server Service return amp Service server server The last change concerns the GenerateTokenPair method After receiving the UID of each created token and writing these UIDs into the CachedTokens structure save the JSON of this structure in Redis with the key token ID where the ID of the user who logged in will be substituted for the ID func tokenService Service GenerateTokenPair user models User accessToken string refreshToken string exp int err error var accessUID refreshUID string if accessToken accessUID exp err tokenService createToken user ID ExpireAccessMinutes tokenService server Config Auth AccessSecret err nil return if refreshToken refreshUID err tokenService createToken user ID ExpireRefreshMinutes tokenService server Config Auth RefreshSecret err nil return cacheJSON err json Marshal CachedTokens AccessUID accessUID RefreshUID refreshUID tokenService server Redis Set fmt Sprintf token d user ID string cacheJSON return Now we are truly protected from an attacker If someone steals our tokens each time a user logs into the system with a username and password new tokens will erase information about old tokens making them invalid Note that in this implementation the user will be able to simultaneously use the system on only one device When logging in from another device the tokens issued for the first one will become invalid The task remains to add the code to check the existence of the token sent by the user Checking for the existence of tokens in RedisAdd the ValidateToken method to the service in the token package This method retrieves the token data from Redis which is stored with the key token ID The ID will be replaced by the user ID from the claims token sent in the request Next the UID of the token from the request is compared with the UID from Redis If they match then the user has sent a valid token func tokenService Service ValidateToken claims JwtCustomClaims isRefresh bool error cacheJSON tokenService server Redis Get fmt Sprintf token d claims ID Result cachedTokens new CachedTokens err json Unmarshal byte cacheJSON cachedTokens var tokenUID string if isRefresh tokenUID cachedTokens RefreshUID else tokenUID cachedTokens AccessUID if err nil tokenUID claims UID return errors New token not found return nil We will call it in the RefreshToken method in AuthHandler func authHandler AuthHandler RefreshToken c echo Context error refreshRequest new requests RefreshRequest if err c Bind refreshRequest err nil return err claims err authHandler tokenService ParseToken refreshRequest Token authHandler server Config Auth RefreshSecret if err nil return responses ErrorResponse c http StatusUnauthorized Not authorized if authHandler tokenService ValidateToken claims true nil return responses MessageResponse c http StatusUnauthorized Not authorized user new models User To do this the ParseToken method will need to be slightly redone so that it does not return the standard set of JWT claims but a link to JwtCustomClaims from which we can extract the token identifier func tokenService Service ParseToken tokenString secret string claims JwtCustomClaims err error token err jwtGo ParseWithClaims tokenString amp JwtCustomClaims func token jwtGo Token interface error if ok token Method jwtGo SigningMethodHMAC ok return nil fmt Errorf unexpected signing method v token Header alg return byte secret nil if err nil return if claims ok token Claims JwtCustomClaims ok amp amp token Valid return claims nilAnd of course the ValidateToken method must be called for validation on all token protected routes To do this we ll add one more middleware in the auth go file func ValidateJWT server s Server echo MiddlewareFunc return func next echo HandlerFunc echo HandlerFunc return func c echo Context error token c Get user jwtGo Token claims token Claims tokenService JwtCustomClaims if tokenService NewTokenService server ValidateToken claims false nil return responses MessageResponse c http StatusUnauthorized Not authorized return next c Then we use it after the embedded JWT middleware when declaring routes in the ConfigureRoutes function authMW middleware JWT server Config Auth AccessSecret validateTokenMW middleware ValidateJWT server apiProtected server Echo Group apiProtected Use authMW validateTokenMW Since the built in JWT middleware after validating the token adds it to the request context with the key user our additional middleware for token validation can extract the token from the context and work with it run the ValidateToken method of the service in the token package to validate its data in Redis Removing information about tokens when logging outTo implement the logout it remains to add the code to remove the user token entry from Redis Let s add the Logout method to AuthHandler func authHandler AuthHandler Logout c echo Context error user c Get user jwtGo Token claims user Claims tokenservice JwtCustomClaims authHandler server Redis Del fmt Sprintf token d claims ID return responses MessageResponse c http StatusOK User logged out We use simplified token validation no additional validation in Redis Let s add the “ logout route to the ConfigureRoutes function authMW middleware JWT server Config Auth AccessSecret server Echo POST logout authHandler Logout authMW validateTokenMW middleware ValidateJWT server Automatic logoutSuppose we are faced with automatically logging out a user in case of minutes of inactivity Setting the validity period of the access token does not solve the problem If the user received a couple of tokens and next time accessed the API after minutes we will return the Unauthorized status However the user can then apply to the endpoint refresh and thanks to the longer validity period of the refresh token he will receive a new pair of tokens We cannot allow this to happen On the other hand setting a period of minutes for a refresh token is also not an option When the user contacts the API minutes after receiving a pair of tokens from this moment we must start a new countdown for automatic logout and allow the user to access the API with an access token or with a refresh token for refresh no later than minutes after receiving the first pair of tokens As I noted earlier Redis s TTL mechanism is very handy for solving this problem Let me remind you that when in the GenerateTokenPair method we write data to Redis after creating tokens the third parameter in the Redis Set method specifies the record expiration date When this time expires Redis automatically deletes the entry If we pass as this parameter then the record will have an unlimited TTL tokenService server Redis Set fmt Sprintf token d user ID string cacheJSON By controlling the TTL of the record in Redis we will achieve automatic invalidation of tokens after a specified time In this case the period of automatic logout can be set to any regardless of the validity period of the tokens What should be done set TTL to write to Redis in GenerateTokenPair method at minutes This step will work on the initial user login and on the subsequent refresh of the pair of tokens by refresh extend the TTL of this entry for another minutes each time the user makes a successful API request Let s create a constant const AutoLogoffMinutes and change the “expiration parameter in GenerateTokenPair tokenService server Redis Set fmt Sprintf token d user ID string cacheJSON time Minute AutoLogoffMinutes Using the Redis Expire command add the TTL extension of the record with tokens after successfully checking its existence in the ValidateJWT middleware in the auth go file func ValidateJWT server s Server echo MiddlewareFunc return func next echo HandlerFunc echo HandlerFunc return func c echo Context error token c Get user jwtGo Token claims token Claims tokenService JwtCustomClaims if tokenService NewTokenService server ValidateToken claims false nil return responses MessageResponse c http StatusUnauthorized Not authorized server Redis Expire fmt Sprintf token d claims ID time Minute tokenService AutoLogoffMinutes return next c Let s say we set the automatic logout period when the user is inactive for minutes The access token is valid for minutes the refresh token is valid for minutes The automatic logout mechanism can be perfectly understood from the diagram At the first stage the frontend application sends the username and password and receives a response from the API with access and refresh tokens The token UID entry is placed in Redis with a TTL of minutes In the second and third stages the application sends various API requests Each of them lags behind the previous one by no more than minutes Each time the TTL of a record in Redis with token UIDs is moved by minutes At the same time the token validity period itself remains unchanged At the fourth stage the frontend application sends a request to the API after minutes have passed since the generation of tokens and receives a Not Authorized response since The access token has expired By contacting the endpoint refresh with a refresh token the frontend receives a new set of tokens Redis writes information about new tokens with a fresh TTL of minutes Old tokens are no longer valid At the fifth stage the application sends a request to the API minutes after the previous stage Even though the tokens did not expire the Redis entry was deleted after a TTL of minutes The frontend will not be able to receive new tokens until the user logs in again Thus the automatic logout is completed User informationThere is one problem with our token validation code Suppose a user is logged in and their token information is stored in Redis Immediately after that it was inactivated for example the system administrator deleted a user record from the database or assigned it the “inactive status We need to make sure that the user s application can no longer work with the API using the issued set of tokens At the moment when the administrator inactivates a user information about that user s tokens should be automatically removed from Redis But what if you forgot to do it To avoid such problems when validating a token we can check not only the existence of an entry in Redis but also the presence activity of a user entry in the database This requires an additional query to the database On the other hand in the process of processing a request it is often the case that the user record is searched in the database the server needs information about the current user It will help determine the rights to perform certain actions when making queries that change data in the database the backend application code must check that the user record exists in the database and the user is not inactivated To implement this idea add code to the ValidateToken method of the token service to find a user record in the database We will also add the found user record to the list of returned parameters of the specified method func tokenService Service ValidateToken claims JwtCustomClaims isRefresh bool user models User err error cacheJSON tokenService server Redis Get fmt Sprintf token d claims ID Result cachedTokens new CachedTokens err json Unmarshal byte cacheJSON cachedTokens var tokenUID string if isRefresh tokenUID cachedTokens RefreshUID else tokenUID cachedTokens AccessUID if err nil tokenUID claims UID return nil errors New token not found user new models User userRepository repositories NewUserRepository tokenService server DB userRepository GetUser user int claims ID if user ID return nil errors New user not found return user nil The GetUser method of the repository can retrieve not only a user record from the users table but also in one JOIN request get personal data and user roles from the user details user roles and others tables if such tables are in the database and this information is useful for processing the request These changes will allow us to remove the code for checking the user s record from the RefreshToken method func authHandler AuthHandler RefreshToken c echo Context error refreshRequest new requests RefreshRequest if err c Bind refreshRequest err nil return err claims err authHandler tokenService ParseToken refreshRequest Token authHandler server Config Auth RefreshSecret if err nil return responses ErrorResponse c http StatusUnauthorized Not authorized user err authHandler tokenService ValidateToken claims true if err nil return responses MessageResponse c http StatusUnauthorized Not authorized accessToken refreshToken exp err authHandler tokenService GenerateTokenPair user if err nil return err res responses NewLoginResponse accessToken refreshToken exp return responses Response c http StatusOK res There will be a more significant change in the middleware ValidateJWT code Let s add the found user record to the request context with the currentUser key making it possible to access this information at all subsequent stages of request processing Middleware for additional steps Check the user exists in DB Check the token info exists in Redis Add the user DB data to Context Prolong the Redis TTL of the current token pairfunc ValidateJWT server s Server echo MiddlewareFunc return func next echo HandlerFunc echo HandlerFunc return func c echo Context error token c Get user jwtGo Token claims token Claims tokenService JwtCustomClaims user err tokenService NewTokenService server ValidateToken claims false if err nil return responses MessageResponse c http StatusUnauthorized Not authorized c Set currentUser user server Redis Expire fmt Sprintf token d claims ID time Minute tokenService AutoLogoffMinutes return next c Optimizing ValidateToken CodeNote that two sequential actions take place in the ValidateToken method of the token package retrieving a record with information about tokens from Redis retrieving information about the user from the database Golang allows us to execute these requests in parallel We will save a little processing time for the request in fact only the time required to retrieve and parse the Redis record into the Golang structure But when you can optimize your code why not We use the golang org x sync errgroup package It will allow you to run multiple goroutines and wait for them to complete successfully However in case of an error in at least one of them the execution of the entire group will be canceled The ValidateToken method code will look like this func tokenService Service ValidateToken claims JwtCustomClaims isRefresh bool user models User err error var g errgroup Group g Go func error cacheJSON tokenService server Redis Get fmt Sprintf token d claims ID Result cachedTokens new CachedTokens err json Unmarshal byte cacheJSON cachedTokens var tokenUID string if isRefresh tokenUID cachedTokens RefreshUID else tokenUID cachedTokens AccessUID if err nil tokenUID claims UID return errors New token not found return nil g Go func error user new models User userRepository repositories NewUserRepository tokenService server DB userRepository GetUser user int claims ID if user ID return errors New user not found return nil err g Wait return user err Another small optimization awaits in the middleware ValidateJWT Extending TTL records with information from tokens in Redis can also be done in a goroutine So further processing of the request will not be blocked while we are waiting for the end of this operation c Set currentUser user go func server Redis Expire fmt Sprintf token d claims ID time Minute tokenService AutoLogoffMinutes return next c Have we done everything correctly If you look at the resulting code you can see that we still make a query to the main database when checking the existence of a user This means that we could store information about the user s tokens and the date of their last use in this database and also implement logout and automatic logout without using the Redis database Why exactly Redis this allows you to unload the main database from storing unusual data and unnecessary requests information about tokens and the moment the user last accessed the API is rather short term a mechanism for automatic deletion of records with expired TTL allows you to more elegantly implement automatic logout and not take up space on the database server for storing expired information other data from the database can be stored in Redis For example information about user roles and permissions Where to store information about issued tokens on the server should be decided based on the specifics of each specific application How to store tokens on the clientThe inclusion of tokens in the response body during the login procedure often leads to the fact that front end developers decide to store the received tokens in the local storage of the browser This avoids the need to re login when a user forces a page to refresh or opens a new tab The solution is very vulnerable to XSS attacks during which the attacker s code can gain access to the local storage An alternative option is often used in which the access token is passed in the response body and stored further in the memory of the frontend application and the refresh token is placed in the HttpOnly cookie This approach helps to better defend against XSS attacks but at the same time is vulnerable to CSRF attacks The approach of placing a refresh token in a cookie ideally also implies a change in the architecture of the backend application in which the authorization service is in a separate domain Thus cookies with a refresh token will be transmitted only when interacting with the authorization service But what about the session It is believed that the use of tokens in any other way except for confirming the identity of the user is no longer included in the JWT functions and should be implemented differently The session mechanism is one of the approaches to solving the problem of logout and automatic logout The simplest way to do this is to add a cookie with a specific string to the server s response The string can be the server response time signed with a secret key The next time the frontend application makes a request the server will compare the time of the previous request contained in the cookie with the current time If more than the specified number of minutes have passed since the previous request the user will receive an HTTP Unauthorized error status Thus the access token will only be valid when paired with a cookie which contains information about the user s session But this does not remove the security issue in the event of attacks Therefore to improve the session mechanism you should use other methods of storing session information in the main database in an additional in memory database in the server file system etc Our approach to user authentication using JWT while not without its drawbacks actually works The approach of using sessions to store refresh tokens or other information about user status is also promising Maintaining application security is always a complex process that requires complex solutions There is no ideal option because each specific application dictates its own needs 2021-04-13 12:11:23
海外TECH DEV Community 10 GitHub repos you need to know as a web developer https://dev.to/pascavld/10-github-repos-you-need-to-know-as-a-web-developer-e7a GitHub repos you need to know as a web developerIf you found value in this thread you will most likely enjoy my tweets too so make sure you follow me on Twitter for more information about web development and how to improve as a developer This article was first published on my Blog Frontend Dev Bookmarks This is a manually curated collection of resources for frontend web developers Free Programming Books This is a repo with all free programming books that are available JavaScript Algorithms This is a list with algorithms and data structures implemented in JavaScript with explanations and links to further readings Front End Checklist The perfect Front End Checklist for modern websites and meticulous developers HTML Boilerplate A professional front end template for building fast robust and adaptable web apps or sites CSS Pro Tips A collection of tips to help take your CSS skills pro Web Fundamentals Best practices for modern web development Learn Git Branching An interactive git visualization and tutorial Aspiring students of git can use this app to educate and challenge themselves towards mastery of git Web Gems A curated list of resources for devs and designers Awesome learning resources This is a list full of resources you can use to learn Bootstrap Git JavaScript HTML CSS and more The endI hope found this useful and if you did please let me know If you have any question feel free to DM me on Twitter 2021-04-13 12:07:43
海外TECH DEV Community Python3 Programming - Exercise 25 https://dev.to/otumianempire/python3-programming-exercise-25-12l2 Python Programming Exercise Python SQLiteIn the previous exercise Exercise SQL we discussed SQL and used it to write to and read from the database In this exercise we shall make use of a built in database know as sqlite Read more about sqlite Create database and table withWe do believe SQLite Browser has been installed We shall create a database sample db and save it into a folder we shall use Sample as the folder name Create a table using this script CREATE TABLE profile id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT name TEXT job TEXT skill TEXT salary INTEGER Connect to the databaseBefore we use the sqlite database we must first import it then connect to it import sqliteDATABASE NAME sample db create connectionconnection sqlite connect DATABASE NAME Cursor ObjectAfter we create the connection to the database we then make use of its cursor object to read and write to the database cursor objectcursor connection cursor ExecuteWe pass an SQL query and some parameters to the execute method after we have created the cursor object SQL queryFor the SQL query it is recommended to use placeholders instead of passing the actual values directly into the query consider some arbitrary query don t do thissql query SELECT some tb WHERE some field do this insteadsql query SELECT some tb WHERE some field the is a placeholder Execute method profile gt id int name str job str skill str salary int id is a primary key and auto increments so we shall ignore itname John Doe job Software Engineer skill Python Developer salary writing and updating has the same effect of affectting some rows else rowcount is reading rather returns an iterable a row tuple sql query INSERT INTO profile name job skill salary VALUES the second argument is of the form parameters remember arg there would be a change in the database thus get the number of affected rows with rowcount attributenum affected row cursor execute sql query name job skill salary rowcount do something if num affected row gt consider select query for more than one row return we can use fetchone to get one row and fetchall to return allsql query SELECT FROM profile row profiles cursor execute sql query fetchall do something with row profiles CommitSure commit here sound familiar from exercise Git Commit mean save write changes made to the database permanently Thus after an insert update or delete you have to commit connetion commit Close cursor and connectionAfter everything we must close the cursor and close the database This is done so that the database isn t blocked cursor close connection close Full codeimport sqliteDATABASE NAME sample db create connectionconnection sqlite connect DATABASE NAME cursor objectcursor connection cursor profile gt id int name str job str skill str salary int id is a primary key and auto increments so we shall ignore itname John Doe job Software Engineer skill Python Developer salary insert write to databasesql query INSERT INTO profile name job skill salary VALUES check if there is a change in the databasenum affected row cursor execute sql query name job skill salary rowcountif num affected row print profile written to database successful else print profile writing to database unsuccessful save the changesconnetion commit close cursor and connectioncursor close connection close Readingimport sqliteDATABASE NAME sample db create connectionconnection sqlite connect DATABASE NAME cursor objectcursor connection cursor read datasql query SELECT FROM profile check if there is a change in the databaserows cursor execute sql query fetchall every row is like a tuple integer indexedif rows gt for row in rows id row name row job row skill row salary row print f ID id name is a n job specialized in skill and earns salary else print profile writing to database unsuccessful there is no need to commit here because no changes are made to the database close cursor and connectioncursor close connection close PracticalsUse a class if possibleWrite a script that returns the number of characters in the entire file and the number of characters on each line Save these two into a database with the name of the file Write a script that returns the document statistics of a given file The document statistics are the number of lines number of words number of characters with space and without space file name Lines Words Char ws Char wos Write these into a databaseWrite a script that backs the content of a file up Save the back up in the database SummaryThe concept or steps behind the use of sqlite is quite simple sqlite is a built in lightweight databaseconnect to the databasecreate a cursor objectexecute some queriescommit the changesclose cursor and connection 2021-04-13 12:03:23
Apple AppleInsider - Frontpage News Adobe Premiere Rush now available on Apple's M1 Silicon Macs https://appleinsider.com/articles/21/04/13/adobe-premiere-rush-now-available-on-apples-m1-silicon-macs Adobe Premiere Rush now available on Apple x s M Silicon MacsAdobe has added more features to their popular video editing software including macOS specific updates and more support for Apple s line of M Macs On April Adobe pushed out an update to its Creative Cloud Video suite Among the updates which include several geared toward performance and stability improvements were updates specifically for macOS and iOS devices For the first time Premiere Rush ーAdobe s lightweight version of Premiere designed for mobile devices ーis now available on M Macs Users can quickly and easily create and edit videos intended for social media Read more 2021-04-13 13:00:04
Apple AppleInsider - Frontpage News Renders of 'iPhone 13' double down on smaller notch rumors https://appleinsider.com/articles/21/04/13/renders-of-iphone-13-double-down-on-smaller-notch-rumors Renders of x iPhone x double down on smaller notch rumorsRenders claimed to depict the iPhone give another chance to see what the iPhone could look like complete with the rumored smaller notch A number of supposed leaks in March and April all claim to show the physical design of the iPhone complete with the often rumored smaller notch Renders published on Tuesday offer another look at the upcoming mobile device as well as doubling down on the notch speculation The renders hosted by MySmartPrice show a design that s fairly similar to the iPhone one that is said to be a cross between the iPhone and the iPhone X The size of mm by mm by mm is also in the same ballpark as the current generation counterpart Read more 2021-04-13 12:36:09
Apple AppleInsider - Frontpage News Apple's next event will be on April 20, Siri says https://appleinsider.com/articles/21/04/13/siri-reveals-apples-next-event-will-be-on-april-20 Apple x s next event will be on April Siri saysMultiple users are reporting that when asked about Apple events Siri sometimes says the next one is on April at Apple Park Apple s current inch and inch iPad Pro modelsSay Hey Siri Apple event into iPhone and most of the time it will tell you that you can get all the details about Apple events on Apple com That s true even now but a number of users are being told of a specific as yet unannounced event instead Read more 2021-04-13 12:29:26
ラズパイ Raspberry Pi Go down a Raspberry Pi YouTube rabbit hole https://www.raspberrypi.org/blog/go-down-a-raspberry-pi-youtube-rabbit-hole/ Go down a Raspberry Pi YouTube rabbit holeWe here at Virtual Raspberry Pi Towers are looking forward to our weekends getting warmer now that we are officially in British Summer Time But we wanted to make the most of these last Saturdays and Sundays in which we have no choice but to cosy up against the typically British spring weather with a The post Go down a Raspberry Pi YouTube rabbit hole appeared first on Raspberry Pi 2021-04-13 12:24:13
海外科学 NYT > Science Darius, ‘World’s Longest Rabbit,’ Goes Missing https://www.nytimes.com/2021/04/13/world/europe/darius-worlds-longest-rabbit-stolen.html Darius World s Longest Rabbit Goes MissingMeasuring more than four feet the furry giant should be easy to spot But he vanished from an English garden last weekend and the police are treating his disappearance as an abduction 2021-04-13 12:51:39
海外科学 NYT > Science Johnson & Johnson Vaccine: Blood Clotting Cases Cause Calls for Pause in US https://www.nytimes.com/2021/04/13/us/politics/johnson-johnson-vaccine-blood-clots-fda-cdc.html Johnson amp Johnson Vaccine Blood Clotting Cases Cause Calls for Pause in USThe Food and Drug Administration and the Centers for Disease Control will stop using the vaccine at federal sites and urge states to do so as well while they examine the safety issues 2021-04-13 12:26:13
海外科学 NYT > Science NFTs Are Shaking Up the Art World. Are They Also Fueling Climate Change? https://www.nytimes.com/2021/04/13/climate/nft-climate-change.html gases 2021-04-13 12:40:56
医療系 医療介護 CBnews 能力に応じた給付と負担へ、マイナンバー活用を提言-資産情報とのひも付けも、諮問会議・民間議員 https://www.cbnews.jp/news/entry/20210413213600 社会保障 2021-04-13 21:42:00
海外ニュース Japan Times latest articles Biden calls for $50 billion investment in semiconductors amid global shortage https://www.japantimes.co.jp/news/2021/04/13/business/biden-chipmaker-investment/ Biden calls for billion investment in semiconductors amid global shortageAbout of global semiconductor manufacturing capacity is concentrated in mainland China and elsewhere in East Asia a report by an industry group and a 2021-04-13 22:18:19
海外ニュース Japan Times latest articles U.K. COVID-19 variant not linked to more serious infections, study finds https://www.japantimes.co.jp/news/2021/04/13/world/uk-coronavirus-variant/ U K COVID variant not linked to more serious infections study findsThe variant is now the dominant viral strain across much of Europe and previous studies had shown it was linked to a higher likelihood of 2021-04-13 22:03:11
海外ニュース Japan Times latest articles Countering China’s threat to the Senkakus requires a full rethink of operations https://www.japantimes.co.jp/opinion/2021/04/13/commentary/japan-commentary/china-japan-senkakus/ Countering China s threat to the Senkakus requires a full rethink of operationsAs the China Coast Guard ramps up its provocations Japan needs to respond in kind and increase the possibilities available for maritime protection 2021-04-13 21:25:23
ニュース BBC News - Home Covid: People 45 or over in England invited to book vaccine https://www.bbc.co.uk/news/uk-56729897 covid 2021-04-13 12:43:51
ニュース BBC News - Home Covid-19: US agencies call for pause in Johnson & Johnson vaccine https://www.bbc.co.uk/news/world-us-canada-56733715 cases 2021-04-13 12:07:31
ニュース BBC News - Home Greensill: Labour urges 'full' probe into Cameron lobbying https://www.bbc.co.uk/news/uk-politics-56730447 labour 2021-04-13 12:22:00
ニュース BBC News - Home Government's LGBT advisory panel disbanded https://www.bbc.co.uk/news/uk-politics-56731460 advisors 2021-04-13 12:54:20
ニュース BBC News - Home Tottenham & Man City each get 2,000 EFL Cup final tickets - but no under-18s allowed https://www.bbc.co.uk/sport/football/56732740 april 2021-04-13 12:18:50
ニュース BBC News - Home Lockdown rules: What are the restrictions in your area? https://www.bbc.co.uk/news/uk-54373904 coronavirus 2021-04-13 12:57:01
ニュース BBC News - Home Covid: Which areas are being mass tested for variants? https://www.bbc.co.uk/news/explainers-54872039 covid 2021-04-13 12:24:15
ニュース BBC News - Home What's the roadmap for lifting lockdown? https://www.bbc.co.uk/news/explainers-52530518 lockdown 2021-04-13 12:20:07
ニュース BBC News - Home Covid: When can I go on holiday abroad or in the UK? https://www.bbc.co.uk/news/explainers-52646738 reason 2021-04-13 12:35:08
北海道 北海道新聞 本紙夕刊帯広・十勝面連載「おうちレシピ」 CFで自費出版 筆者の福島さん40万円目標 15年分から60品紹介 https://www.hokkaido-np.co.jp/article/532772/ 北海道新聞 2021-04-13 21:15:00
北海道 北海道新聞 ひらふ地区の宿泊施設、15日工事開始 韓国財閥側が説明会 https://www.hokkaido-np.co.jp/article/532771/ 宿泊施設 2021-04-13 21:13:00
北海道 北海道新聞 テレワークにどうぞ 清水町など駅直結の貸事務所開設 https://www.hokkaido-np.co.jp/article/532770/ 十勝清水駅 2021-04-13 21:12:00
北海道 北海道新聞 高校野球 神奈川の公立高で長年指導 加賀谷さんが紋別高監督就任 https://www.hokkaido-np.co.jp/article/532581/ 監督就任 2021-04-13 21:04:01
北海道 北海道新聞 日本郵便は争う姿勢 かんぽ不正販売解雇訴訟 札幌地裁で口頭弁論 https://www.hokkaido-np.co.jp/article/532768/ 口頭弁論 2021-04-13 21:03:00
北海道 北海道新聞 衆院道2区補選 6氏舌戦、春の陣 コロナ下、オンラインも活用 https://www.hokkaido-np.co.jp/article/532767/ 札幌市北区 2021-04-13 21:03:00

コメント

このブログの人気の投稿

投稿時間:2021-06-17 22:08:45 RSSフィード2021-06-17 22:00 分まとめ(2089件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)