1/* Part of SWI-Prolog 2 3 Author: Jan Wielemaker 4 E-mail: jan@swi-prolog.org 5 WWW: https://www.swi-prolog.org 6 Copyright (C): 2015-2025, VU University Amsterdam 7 SWI-Prolog Solutions b.v. 8 9 This program is free software; you can redistribute it and/or 10 modify it under the terms of the GNU General Public License 11 as published by the Free Software Foundation; either version 2 12 of the License, or (at your option) any later version. 13 14 This program is distributed in the hope that it will be useful, 15 but WITHOUT ANY WARRANTY; without even the implied warranty of 16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 GNU General Public License for more details. 18 19 You should have received a copy of the GNU General Public 20 License along with this library; if not, write to the Free Software 21 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 22 23 As a special exception, if you link this library with other files, 24 compiled with a Free Software compiler, to produce an executable, this 25 library does not by itself cause the resulting executable to be covered 26 by the GNU General Public License. This exception does not however 27 invalidate any other reasons why the executable file might be covered by 28 the GNU General Public License. 29*/ 30 31:- module(jwt, 32 [ jwt/2 % +String, -Data 33 ]). 34:- use_module(library(codesio)). 35:- use_module(library(base64)). 36:- use_module(library(utf8)). 37:- use_module(library(json)). 38 39/** <module> JSON Web Token library 40 41This library is a very early start to deal with JOSE: JSON Object 42Signing and Encryption. This is needed for OpenID Connect. The current 43library only extracts the claimed object from a non-encrypted JWT (JSON 44Web Token). This is enough to deal with Google's OpenID Connect, which 45guarantees that the token comes from Google in other ways. 46 47@see https://tools.ietf.org/html/draft-jones-json-web-token 48*/ 49 50%% jwt(+String, -Object) is det. 51% 52% True if Object is claimed in the JWT represented in String. 53% 54% @tbd Currently does not validate the claim using the signature. 55 56jwt(String, Object) :- 57 nonvar(String), 58 split_string(String, ".", "", [Header64,Object64|_Parts]), 59 base64url_json(Header64, _Header), 60 base64url_json(Object64, Object). 61 62%% base64url_json(+String, -JSONDict) is semidet. 63% 64% True when JSONDict is represented in the Base64URL and UTF-8 65% encoded String. 66 67base64url_json(String, JSON) :- 68 string_codes(String, Codes), 69 phrase(base64url(Bytes), Codes), 70 phrase(utf8_codes(Text), Bytes), 71 setup_call_cleanup( 72 open_codes_stream(Text, Stream), 73 json_read_dict(Stream, JSON), 74 close(Stream))