#JWTToken
Explore tagged Tumblr posts
asadmukhtarr · 2 months ago
Text
In modern web applications, user authentication is a critical feature. One of the most secure ways to implement authentication is by using JSON Web Tokens (JWT). JWT allows for secure communication between a client and server, ensuring that only authorized users can access protected resources.
In this tutorial, we'll walk through the process of integrating JWT authentication in a MERN stack application. We'll use Node.js and Express for the backend and React for the frontend. This guide will cover the complete setup, from creating a JWT authentication system in Node.js to connecting it with a React application.
By the end of this tutorial, you'll have a secure authentication system in place that uses JWT for token-based authentication.
0 notes
codeonedigest · 2 years ago
Video
youtube
(via JWT Access Token Design Pattern Tutorial for API Developers | JWT OAuth3 Explained for Microservices) Full Video Link                https://youtu.be/TEx6LCu8TK0Hello friends, new #video on #accesstoken #jwt #jsonwebtoken #jwttoken #designpattern for #microservices #tutorial for #api #developer #programmers with #examples is published on #codeonedigest #youtube channel.  @java #java #aws #awscloud @awscloud @AWSCloudIndia #salesforce #Cloud #CloudComputing @YouTube #youtube #azure #msazure  #aws #accesstoken #microservices #microservicestutorial #microservicearchitecture #instagramaccesstoken #howtouseanaccesstoken #accesstokens #accesstokenandrefreshtoken #accesstokenandrefreshtokenjwtnodejs #accesstokenandrefreshtokenoauth2 #accesstokenandrefreshtokenspringboot #jwtauthentication #jwttoken #jwtauthenticationnodejs #jwttokenauthenticationwebapispringboot #jwttokenauthenticationwebapi #jwttokeninnodejs #designpattern
0 notes
devstoc · 2 years ago
Text
Does jwt tokens are really secure? what is jwt tokens and what for? know more about jwt tokens: https://thescribitionists.medium.com/what-is-json-web-token-jwt-a0361360530f
Tumblr media
0 notes
katyslemon · 3 years ago
Text
𝐇𝐨𝐰 𝐭𝐨 𝐁𝐮𝐢𝐥𝐝 𝐑𝐚𝐢𝐥𝐬 𝐀𝐏𝐈 𝐀𝐮𝐭𝐡𝐞𝐧𝐭𝐢𝐜𝐚𝐭𝐢𝐨𝐧 𝐮𝐬𝐢𝐧𝐠 𝐉𝐖𝐓?
🔶 Prerequisites to Build Rails API Authentication Using JWT 🔶 Create Rails Application 🔶 Add Gems 🔶 Create User Model 🔶 Create User Controller 🔶 Add CRUD Operations 🔶 Create JwtToken Concern 🔶 Creating Authentication Controller 🔶 Implementing the Login Function 🔶 Update routes.rb 🔶 Test the API using Postman
#rails #API #jwt #100DaysOfCode
0 notes
awsexchage · 5 years ago
Photo
Tumblr media
LINE WORKSボットをAmazon Lexで作る https://ift.tt/377Tuym
LINEWORKS Advent Calendar 2019 11日目の記事です。
チャットボットを簡単に作れるサービスは数多く存在してますが、今回は前から気になってた「Amazon Lex」を使ったLINE WORKSボット開発をしてみました。
Amazon Lex とは
「Amazon Lex」は、会話型インターフェイスを提供するAWSサービスです。LexにはAlexaで使われている技術と同じものが使われているそう。 自然言語処理だけでなく音声認識も内包されてます。
https://aws.amazon.com/jp/lex/
似たようなサービスにDialogFlowとかAzure Bot ServiceとかIBM Watson Assistant
今回はAmazon Lexで対話フローを作成し、LINE WORKSのトーク上で会話できるボットを作りました。
!!!注意!!!
2019/12/11現在、Amazon Lexは米国英語のみ対応しており、日本語および東京リージョンでの利用は対応してません。 今回についても英語で対話するチャットボットとなります。(日本語対応いつになるか…) また、使用するリージョンはオレゴンとしました。
構成
Tumblr media
AWS Lambdaを使ったサーバーレス構成とする。
LINE WORKSからのコールバックをAPI Gateway経由で受け取る。そこからAmazon Lexと連携して対話処理をする。
LINE WORKSのパラメータはSystems Managerパラメータストアで管理する。
LINE WORKSのアクセストークンは定期的に実行されるLambdaにより更新される。
開発環境
言語: Python 3.7.1
デプロイ: LambdaのデプロイにはServerless Frameworkを使う
実装
1. Amazon LexでBotを作成
今回は、以下の公式のチュートリアルに沿ってサンプルを使ったBotを作成しました。
ボットの例: BookTrip – Amazon Lex https://docs.aws.amazon.com/ja_jp/lex/latest/dg/ex-book-trip.html
簡単に説明すると、車やホテルを予約するチャットボットです。 サンプル���ら「BookTrip」を選んで、作成しました。
Tumblr media
このような画面で、インテントの設定や、対話フローについて設定をします。
Tumblr media
他のチャットボット作成サービスを使ったことがある人ならすぐ使える印象。初心者はなかなか一から設定するのは大変そうだなと感じました。
2. LINE WORKS Developer Consoleから各種キー作成 & ボット作成
LINE WORKS Developer Consoleへログインし、キーの作成や今回のボットを作成します。
詳しくはこちらの過去記事を参照ください。
LINE WORKS トークBot をPythonで実装してみる 〜前編: API認証〜 https://qiita.com/mmclsntr/items/1d0f520f1df5dffea24b
3. LINE WORKSボットアプリサーバー作成
Lambdaで構成し、ランタイムをPython3.7で実装しました。
Lambda関数は以下の2つ
1.LINE WORKS アクセストークン定期更新
CloudWatch Event スケジュールイベントで定期実行 (半日に一回)
2.LINE WORKS チャットボット
API Gateway経由でLINE WORKSからのメッセージを取得し、Amazon Lex Botと連携。
以下、サンプルコード
lambda_function.py
import json import jwt import requests import urllib import boto3 import os from datetime import datetime from base64 import b64encode, b64decode import hashlib import hmac from requests.structures import CaseInsensitiveDict ssm = boto3.client('ssm') lex = boto3.client('lex-runtime') #################################### # Systems Manager パラメータストア # #################################### def get_parameter(key): """ SSMパラメータストアからパラメータ取得 """ response = ssm.get_parameters( Names=[ key ], WithDecryption=True ) parameters = response["Parameters"] if len(parameters) > 0: return response['Parameters'][0]["Value"] else: return "" def put_parameter(key, value): """ SSMパラメータストアへパラメータを格納 """ response = ssm.put_parameter( Name=key, Value=value, Type='SecureString', Overwrite=True ) ############## # Amazon Lex # ############## def post_text_to_lex(text, user_id, bot_name, bot_alias): """ Amazon Lexへテキストを送信 & 返答取得 """ response = lex.post_text( botName=bot_name, botAlias=bot_alias, userId=user_id, inputText=text ) return response["message"] ################## # LINE WORKS API # ################## def get_jwt(server_list_id, server_list_privatekey): """ LINE WORKS アクセストークンのためのJWT取得 """ current_time = datetime.now().timestamp() iss = server_list_id iat = current_time exp = current_time + (60 * 60) # 1時間 secret = server_list_privatekey jwstoken = jwt.encode( { "iss": iss, "iat": iat, "exp": exp }, secret, algorithm="RS256") return jwstoken.decode('utf-8') def get_server_token(api_id, jwttoken): """ LINE WORKS アクセストークン取得 """ url = 'https://authapi.worksmobile.com/b/{}/server/token'.format(api_id) headers = { 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8' } params = { "grant_type" : urllib.parse.quote("urn:ietf:params:oauth:grant-type:jwt-bearer"), "assertion" : jwttoken } form_data = params r = requests.post(url=url, data=form_data, headers=headers) body = json.loads(r.text) access_token = body["access_token"] return access_token def validate_request(body, signature, api_id): """ LINE WORKS リクエスト検証 """ # API IDを秘密鍵に利用 secretKey = api_id.encode() payload = body.encode() # HMAC-SHA256 アルゴリズムでエンコード encoded_body = hmac.new(secretKey, payload, hashlib.sha256).digest() # BASE64 エンコード encoded_b64_body = b64encode(encoded_body).decode() # 比較 return encoded_b64_body == signature def send_message(content, api_id, botno, consumer_key, access_token, account_id): """ LINE WORKS メッセージ送信 """ url = 'https://apis.worksmobile.com/{}/message/sendMessage/v2'.format(api_id) headers = { 'Content-Type' : 'application/json;charset=UTF-8', 'consumerKey' : consumer_key, 'Authorization' : "Bearer " + access_token } params = { "botNo" : int(botno), "accountId" : account_id, "content" : content } form_data = json.dumps(params) r = requests.post(url=url, data=form_data, headers=headers) if r.status_code == 200: return True return False ###################### # Lambda関数ハンドラ # ###################### def update_token_handler(event, context): """ LINE WORKS アクセストークン定期更新 Lambdaハンドラー関数 """ # SSMパラメータストアからLINE WORKSのパラメータを取得 api_id = get_parameter("lw_api_id") server_list_id = get_parameter("lw_server_list_id") server_list_privatekey = get_parameter("lw_server_list_private_key").replace("\\n", "\n") # JWT取得 jwttoken = get_jwt(server_list_id, server_list_privatekey) # Server token取得 access_token = get_server_token(api_id, jwttoken) # Access Tokenをパラメータストアに設定 put_parameter("lw_access_token", access_token) return def chat_with_lex_handler(event, content): """ LINE WORKS チャットボット Lambdaハンドラー関数 """ botno = os.environ.get("BOTNO") lex_bot_name = os.environ.get("LEX_BOT_NAME") lex_bot_alias = os.environ.get("LEX_BOT_ALIAS") # SSMパラメータストアからLINE WORKSのパラメータを取得 api_id = get_parameter("lw_api_id") consumer_key = get_parameter("lw_server_api_consumer_key") access_token = get_parameter("lw_access_token") event = CaseInsensitiveDict(event) headers = event["headers"] body = event["body"] # リクエスト検証 if not validate_request(body, headers.get("x-works-signature"), api_id): # 不正なリクエスト return # Jsonへパース request = json.loads(body) # 送信ユーザー取得 account_id = request["source"]["accountId"] res_content = { "type" : "text", "text" : "Only text" } # 受信したメッセージの中身を確認 request_type = request["type"] ## Message if request_type == "message": content = request["content"] content_type = content["type"] ## Text if content_type == "text": text = content["text"] # Amazon Lexと連携 reply_txt = post_text_to_lex(text, account_id.replace("@", "a"), lex_bot_name, lex_bot_alias) res_content = { "type" : "text", "text" : reply_txt } # 送信 rst = send_message(res_content, api_id, botno, consumer_key, access_token, account_id) res_body = { "code": 200, "message": "OK" } response = { "statusCode": 200, "headers": { "Content-Type": "application/json" }, "body": json.dumps(res_body) } return response
こちらの過去記事もご参照ください。 LINE WORKS トークBot をPythonで実装してみる 〜後編: チャットボット実装〜 https://qiita.com/mmclsntr/items/28ba6baaf23124a53663
ソースコード
https://github.com/mmclsntr/lineworks-bot-with-amazon-lex
動かしてみる
以下の感じで、LINE WORKSのトーク上で、Lexで作成したチャットボットと (英語で) 会話できます。
Tumblr media
まとめ
Amazon Lexで作成したチャットボットもLINE WORKSで問題なく動かせることができました。 簡単な問い合わせであれば楽に実現できるかなと思います。ぜひ日本語対応していただけると。。
あとはLexで対話の設定をいろいろチューニングして遊んでみようと思います。
元記事はこちら
「LINE WORKSボットをAmazon Lexで作る」
December 24, 2019 at 02:00PM
0 notes
codeonedigest · 2 years ago
Video
youtube
JWT Access Token Design Pattern Tutorial for API Developers | JWT OAuth3... Full Video Link                https://youtu.be/TEx6LCu8TK0Hello friends, new #video on #accesstoken #jwt #jsonwebtoken #jwttoken #designpattern for #microservices #tutorial for #api #developer #programmers with #examples is published on #codeonedigest #youtube channel.  @java #java #aws #awscloud @awscloud @AWSCloudIndia #salesforce #Cloud #CloudComputing @YouTube #youtube #azure #msazure  #aws #accesstoken #microservices #microservicestutorial #microservicearchitecture #instagramaccesstoken #howtouseanaccesstoken #accesstokens #accesstokenandrefreshtoken #accesstokenandrefreshtokenjwtnodejs #accesstokenandrefreshtokenoauth2 #accesstokenandrefreshtokenspringboot #jwtauthentication #jwttoken #jwtauthenticationnodejs #jwttokenauthenticationwebapispringboot #jwttokenauthenticationwebapi #jwttokeninnodejs #designpattern
1 note · View note
codeonedigest · 2 years ago
Text
JWT Access Token Design Pattern Tutorial for API Developers | JWT OAuth3 Explained for Microservices
Full Video Link https://youtu.be/TEx6LCu8TK0 Hello friends, new #video on #accesstoken #jwt #jsonwebtoken #jwttoken #designpattern for #microservices #tutorial for #api #developer #programmers with #examples is published on #codeonedigest #
In this video we will learn about Access Token design pattern for microservices.   Access Token pattern is to validate the identity of the caller.  Caller service or app sends the access token in request header to callee services. Api Gateway of the Callee service validates the token & check the identity of caller. Api gateway will allow request only with valid access token. OAuth 2.0 has…
Tumblr media
View On WordPress
0 notes
codeonedigest · 2 years ago
Text
What is JWT | Learn Json Web Token in 1 Minute
Hi, a short #video on #jwt #jsonwebtoken is published on #codeonedigest #youtube channel. Learn the jwt in 1 minute. #jwtauthentication #jwttoken #jwtauthentication #jwt #jwtvsoauth2 #jwtauthenticationspringboot #jwttokenvssession
What is JWT? JWT is stands for Json web token. JWT is an open standard RFC 7519 that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret with the HMAC algorithm or a public/private key pair using RSA or ECDSA algorithms. When…
Tumblr media
View On WordPress
0 notes
codeonedigest · 2 years ago
Video
youtube
What is JWT | Learn Json Web Token in 1 Minute | JWT tutorial for beginners
Hi, a short #video on #jwt #jsonwebtoken is published on #codeonedigest #youtube channel. Learn the jwt in 1 minute.
#jwtauthentication #jwttoken #jwtauthentication #jwt #jwtvsoauth2 #jwtauthenticationspringboot #jwttokenvssession #jwttokenauthenticationwebapi #jwtspringboot #jwtauthenticationreact #jwttutorial #jwtauthorization #jwtauthorizationspringboot #jwtauthorizationnodejsjwtauthorizationreact #jwtauthorizationangular #jwtauthorizationandauthentication #jwtauthorizationvslambdaauthorizer #jwtauthorizationserver #jwtauthorizationspring #jwtauthorizationheader #jwtauthorizationtoken #jwttoken #jwttokenauthenticationwebapi #jwttokenspringbootexample #jwttokenvsoauth2 #jwttokenauthentication #jwttokeninspringboot #jwttokeninnodejs
1 note · View note
awsexchage · 6 years ago
Photo
Tumblr media
LINE WORKS トークBot をPythonで実装してみる 〜前編: API認証〜 https://ift.tt/2OfXuZ2
はじめに
 ビジネス版LINEという位置付けのLINE WORKSにチャットボットを実装できます。  最近、LINE WORKSのチャットボットを開発することになったので、その実装方法についてまとめようと思います。
LINEボットと同じ?
 LINEのチャットボットのAPIは Messaging APIと言いますが、LINE WORKSのAPIは LINE WORKS Bot Platform APIと言うそうです。  私自身、これまでLINEのチャットボット開発をいくつか経験してきましたのでLINE WORKSの方もすぐ使えると思いましたが、やはりAPI仕様としてはほぼ別物という印象です。返答の仕方やメッセージの種類も異なります。  ただ、UIは似たものですので使う側は馴染みやすいと思います。
LINE WORKS Developersドキュメント: https://developers.worksmobile.com/jp/document/300130001?lang=ja
サービスAPIとサーバーAPI
LINE WORKSのAPIには「サービスAPI」と「サーバーAPI」の2種類があります。
サービスAPI
ユーザーのログインが必要なAPIです。本人のデータへのみアクセスできます。
サーバーAPI
ユーザーのログインが不要な APIです。
API共通ガイド:https://developers.worksmobile.com/jp/document/3002001?lang=ja
APIそれぞれの説明にどちらの種類なのか記載されてます。 LINE WORKS トークBotで利用するAPIは「サーバーAPI」になります。なので、Token発行などはサーバーAPIの利用手順に沿って行います。
検証環境
言語: Python 3.7
0. 前準備
0.1. アカウント権限
対象のLINE WORKSのテナントへBotを設定するために、開発用のアカウントが必要です。
管理画面の「メンバー > 管理者権限」で開発用の権限の作成 (権限は “サービス>Bot” および “developers”)
作っ��管理者権限にメンバーを紐付け
0.2. LINE WORKS Developer Consoleで各種キーの発行
LINE WORKSのAPIを利用するために必要なキーをLINE WORKS Developer Consoleで発行します。
LINE WORKS Developer Console: https://developers.worksmobile.com/jp/console/openapi/main
項目 説明 API ID API認証用のAPI ID Server API Consumer Key サーバー APIのConsumer Key Server List ID Server List(ID登録タイプ) のID Server List 認証キー 上のServer List IDに対応する認証キー (秘密鍵)
0.3. Botの登録
BotをLINE WORKS Developer Consoleで登録します。
Bot – LINE WORKS Developer Console: https://developers.worksmobile.com/jp/console/bot/view
1.「登録」をクリックし登録画面を開く 2. 必須となっている情報を入力 ※ 「Callback URL」はボットのサーバーを構築後に「修正」から登録。 3. 「保存」をクリックし、Botリストへ戻る 4. 登録したBotを選択し、情報表示。記載されている Bot Noを控える。
0.4. 環境変数��設定
上記で発行した各種キーを環境変数へ設定する。
0.5. Token 発行
トークBotのAPIを利用するにあたって、Tokenを発行する必要があります。
API認証の準備: https://developers.worksmobile.com/jp/document/1002002?lang=ja
JWT生成
使うもの
Server List ID
Server List 認証キー
import os import jwt import datetime SERVER_LIST_ID = os.environ.get("SERVER_LIST_ID") # Server List ID SERVER_LIST_PRIVATEKEY = os.environ.get("SERVER_LIST_PRIVATEKEY") # Server List 認証キー def get_jwt(): """ JWTの生成 """ current_time = datetime.datetime.now().timestamp() iss = SERVER_LIST_ID iat = current_time exp = current_time + 3600 # 1時間有効 secret = SERVER_LIST_PRIVATEKEY jwstoken = jwt.encode( { "iss": iss, "iat": iat, "exp": exp }, secret, algorithm="RS256") return jwstoken.decode('utf-8')
Token 発行
使うもの
生成したJWT
API ID
import os import json import requests import urllib API_ID = os.environ.get("API_ID") # API ID def get_server_token(jwttoken): """ Token発行 """ url = 'https://authapi.worksmobile.com/b/' + API_ID + '/server/token' headers = { 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8' } params = { "grant_type" : urllib.parse.quote("urn:ietf:params:oauth:grant-type:jwt-bearer"), "assertion" : jwttoken } form_data = params r = requests.post(url=url, data=form_data, headers=headers) body = json.loads(r.text) access_token = body["access_token"] return access_token
生成されたTokenを控えておく。
※ 注意
発行された access_token が 24 時間以内利用されない場合には自動的に失効しますので、ID 登録タイプの場合は必ず一日に一回 Token を発行してください。 access_token の発行時間を token 情報と共に保存し、 Server API の利用時には token の有効期限を確認することを推奨します。 access_token の有効期限内であっても、token の再発行を行うと以前の token は無効になります。
https://developers.worksmobile.com/jp/document/1002002?lang=ja
まとめ
上記のToken発行をまとめると、こんな感じです。
publish_token.py
import os import json import jwt import requests import urllib import datetime SERVER_LIST_ID = os.environ.get("SERVER_LIST_ID") # Server List ID SERVER_LIST_PRIVATEKEY = os.environ.get("SERVER_LIST_PRIVATEKEY") # Server List 認証キー API_ID = os.environ.get("API_ID") # API ID def get_jwt(): """ JWTの生成 """ current_time = datetime.datetime.now().timestamp() iss = SERVER_LIST_ID iat = current_time exp = current_time + 3600 # 1時間有効 secret = SERVER_LIST_PRIVATEKEY jwstoken = jwt.encode( { "iss": iss, "iat": iat, "exp": exp }, secret, algorithm="RS256") return jwstoken.decode('utf-8') def get_server_token(jwttoken): """ Token発行 """ url = 'https://authapi.worksmobile.com/b/' + API_ID + '/server/token' headers = { 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8' } params = { "grant_type" : urllib.parse.quote("urn:ietf:params:oauth:grant-type:jwt-bearer"), "assertion" : jwttoken } form_data = params r = requests.post(url=url, data=form_data, headers=headers) body = json.loads(r.text) access_token = body["access_token"] return access_token if __name__ == "__main__": jwttoken = get_jwt() access_token = get_server_token(jwttoken) print(access_token)
後編へ続く
次は実際のチャットボットの部分をまとめます。
後編:https://cloudpack.media/48211
参考
https://qiita.com/leo1109/items/2e82c899891f8e771315 https://qiita.com/tokotan/items/f615f4a62219d655436f
元記事はこちら
「LINE WORKS トークBot をPythonで実装してみる 〜前編: API認証〜」
July 24, 2019 at 12:00PM
0 notes