Repository: Aralink/ssojwt Branch: master Commit: e47856e5594f Files: 35 Total size: 181.2 KB Directory structure: gitextract_2ha_n88x/ ├── LICENSE ├── README.md ├── backend/ │ ├── build-lib/ │ │ └── geronimo-servlet_3.0_spec-1.0.jar │ └── src/ │ ├── java/ │ │ └── com/ │ │ └── aralink/ │ │ └── sslsignature/ │ │ └── sso/ │ │ └── jwt/ │ │ ├── AuthenticationOperation.java │ │ ├── HMACKeyContainer.java │ │ ├── JWTManager.java │ │ └── JWTServlet.java │ └── web/ │ └── WEB-INF/ │ └── web.xml ├── build/ │ ├── build.xml │ ├── gruntfile.js │ ├── ivy.xml │ └── package.json ├── client/ │ └── resources/ │ ├── html/ │ │ ├── sso.html │ │ ├── sso.js │ │ ├── sso_common.js │ │ └── sso_rest.js │ └── js/ │ └── sslssso.js ├── dist/ │ └── sso.war └── test/ ├── java/ │ └── com/ │ └── aralink/ │ └── sslsignature/ │ └── sso/ │ └── jwt/ │ └── test/ │ ├── JWTTest.java │ ├── RestClient.java │ └── SimpleConsoleLogger.java └── web/ ├── hosted/ │ ├── index.html │ ├── js/ │ │ ├── config.js │ │ ├── index.js │ │ ├── jwtcreator.js │ │ ├── keystore.js │ │ ├── login.js │ │ └── register.js │ ├── jwtcreator.html │ ├── keystore.html │ ├── login.html │ ├── register.html │ └── sso.html └── standalone/ ├── index.html └── sso.html ================================================ FILE CONTENTS ================================================ ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. {one line to give the program's name and a brief idea of what it does.} Copyright (C) {year} {name of author} This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: {project} Copyright (C) {year} {fullname} This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: README.md ================================================ # Cross domain Single sign-on with Json Web Tokens (JWT) > Federate your websites using only javascript Access to several web sites with a unique identification. Uses JSON Web Tokens (RFC7519) to represent the information exchanged between the identification provider (IDP) and service provider (SP). The JWT is shared and synchronized among all your websites through the browser local storage without need of server session ![alt tag](https://produccion.sslsignature.com/web/images/ssoiframe.png) ## How does it work You have an excellent introduction to JWT in (https://jwt.io/introduction/) and single sign-on (SSO) on our website (spanish) (https://produccion.sslsignature.com/web/sso.html) ## Getting started > With hosted version (it is free) Define on page a `` field to indicate the sslsignature accountId ``` ``` Include javascript ``` ``` Create a function to receive the authenticated user ``` function onIdentification(operation){ console.log("eidentifier: "+ operation.eIdentifier); console.log("name: "+ operation.name); console.log("jwt: "+ operation.jwt); } ``` Now, we are going to see it in action (download the demo for the third step) 1. Create a JWT [here](https://produccion.sslsignature.com/sso/hosted/jwtcreator.html). This would be done in your login form 2. Open a new tab in your browser with [this URL](https://produccion.sslsignature.com/sso/hosted/sso.html). You will see that you are logged in and the content of the JWT token 3. Now, here is the magic, download [sso.html](/test/web/hosted/sso.html) and open from your computer, and you will see that you are registered with the same user. Try to logout and see the opened page in second step (do not use IE11 at this moment, please...) ##Install ### Content of the repository * /backend -->The sample server * /build -->Build scripts * /client -->Javascript library for your pages * /dist -->Precompiled sso.war to deploy javascript, sample server and demos on a container like tomcat * /test -->Demo pages (hosted and standalone) and a java sample client to issue/validate tokens ### Javascript library Simply copy the library 'sslssso.js' and its dependencies on a web server. {yourserver.com}/{ssopath}/js/sslssso.js {yourserver.com}/{ssopath}/html/sso.html sslssso will access sso.html and related .js, therefore expect to find this structure Include a javascript reference in your page to sslssso.js ``` ``` or use hosted ``` ``` ### Backend server The signature key to issue tokens (and validate) must be well protected, usually on the server. You can use a hosted account from SSLSignature (free of charges) or issue tokens from your own server. The project includes a sample server with autogenerated HMAC keys ####Use your own server Yo need to provide a REST service to validate the JWT from the client side. If you plan to do it only on server side, move on to the next section ``` POST /{ssoValidationUri} HTTPS Content-Type=application/x-www-form-urlencoded Host: yourserver.com jwt={jwt} ``` The answer must have code 200, status = FAILED / SUCCESS, and the JWT parsed fields in JSON format ``` { "status": "SUCCESS", //SUCCESS, FAIL. Mandatory "sub": "123456", //User unique identifier. Recommended "eidentifier":"john.smith" //username,Recommended "name": "John Smith", //User Full Name. Recommended "other": "value", //More fields (email, phone, etc). Optional "jwt": "eyJhbGciOiJIUzI..." //JWT new token if necessary. Optional } ``` ####Use the sample server Take care that it is only an example and it is not intended for a production system Deploy sso.war in a J2EE container like tomcat. The first time you run the HMAC signing key will be created in a file called jwt.hmac (configure location in WEB-INF/web.xml) The JWT validation service will be available on {yourserver.com}/sso/jwt The sample server also allow you to issue JWT. Invoke the service providing the fields to be included in JWT ``` POST /sso/jwt HTTPS Content-Type=application/x-www-form-urlencoded Host: yourserver.com sub=123456&eidentifier=john.smith&name=John+Smith&phone=34+661661661&email=john.smith%40mycompany.com&other=... ``` The response will be the JWT string ``` eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTYiLCJpc3MiOiJKV1QgU0FNUExFIElTU1VFUiIsImlhdCI6MTQ2MzU4MTg4MSwiZXhwIjoxNDYzNjY4MjgxLCJwaG9uZSI6IjM0IDY2MTY2MTY2MSIsIm90aGVyIjoiLi4uIiwiZWlkZW50aWZpZXIiOiJqb2huLnNtaXRoIiwiZW1haWwiOiJqb2huLnNtaXRoQG15Y29tcGFueS5jb20iLCJuYW1lIjoiSm9obiBTbWl0aCJ9.eaihxfyO8zWJJm0o97T6p-Cql9oe6n_3SLj0MphGbBA ``` Configure expiration or issuer in JWTServlet class. ####Use the hosted server The SSLSignature could issue and validate the JWT for your system. You need an account. After that, the configuration is simple as shown in 'Getting started'. After a successful authentication in your system, invoke this service to issue a new token . Provide a JSON with your required fields. ``` POST /sslsignature/account/jwt HTTPS Authorization=Basic YWNjb3VudElkOmFwaUtleQ== Content-Type=application/json Host: produccion.sslsignature.com { sub: "yourInternalId", eidentifier: "yourUserIdentifier", name: "user name", other: "other..." } ``` Also is needed an authorization header (basic http auth) in the way `Basic Base64(accountId:apiKey)`. The string 'Basic' followed by the base64 encoding of the provided accountId, ':' and apiKey ##Usage ### Page configuration Configure the accountId and custom validation URL in the tags of the page or using javascript. The accountId will reference the identifier that will take the token in the local storage. ``` //Optional javascript config var ssls_accountId=myTokenId; var ssls_validationUrl={yourserver.com}/{ssoValidationUri}; ``` ### SSO Events The sso generates events for onload, onIdentification and onLogout. Simply create a function on the page with these names. ``` // Invoked after page load if you have a valid token or after new JWT correct identification (if page is still loaded) // If you do not have identification token, this function is not executed function onIdentification(operation){ console.log(operation.sub); //Your User internal ID console.log(operation.eidentifier); //Your user unique identifier (for example the username) console.log(operation.name); //User full name console.log("operation.jwt); //The token itself } //Invoked when the script finish loading the SSO. It is always after onIdentification function onLoad(){ } //Invoked when user logs out function onLogout(){ } ``` In you need several event listeners use ``` sslssso.listen ("sso.onload", function (observable, eventType, data) {}); ``` ### JWT Validation The token is validated during script execution to check that has been issued by the server and has not been altered. The electronic signature is verified cryptographically on the server. If the token is correct will occur a call to onIdentification. If the validation is unsuccessful, the token is deleted and acts as if there had been token. Validation URL is configured with `` (see server instalation). If you do not want the tokens are validated on the client side, set `validate = false` (default is true). Then no server configuration is needed, and `sslssso.js` only will decode jwt token and check expiration on the client side. On hosted version, use the provided accountId and do not set the validationUrl ### Login In a standard authentication flow, when an identification is required, the website redirects the user to the IDP (identification provider). The IDP authenticates user with the organization defined method, for example, and username/password form. After successful authentication, the IDP server returns a valid JWT that includes the identification information and the electronic signature. The JWT is stored locally on the browser ![alt tag](https://produccion.sslsignature.com/web/images/ssoflow.png) Calls SSO to store the jwt issued token on localStorage of browser. An `onIdentification` event will be fired on all tabs ``` sslssso.login(jwt); ``` ### Logout ``` sslssso.logout(); ``` The token will be cleaned and an `onLogout` event will be fired on all tabs ##Known issues ###IE11 & Edge JWT update events do not syncronize tabs. See [Microsoft doc](https://connect.microsoft.com/IE/feedback/details/812563/ie-11-local-storage-synchronization-issues) ## Support https://soporte.aralink.com https://github.com/Aralink/ssojwt/issues ================================================ FILE: backend/src/java/com/aralink/sslsignature/sso/jwt/AuthenticationOperation.java ================================================ package com.aralink.sslsignature.sso.jwt; import java.io.StringReader; import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import io.jsonwebtoken.Claims; public class AuthenticationOperation { private Map params = new HashMap(); /** * FAIL operation * @param e error produced parsing or validating JWT */ public AuthenticationOperation(Exception e){ params.put("status", "FAIL"); params.put("error", e.getMessage()); } /** * Success operation. * Return all fields parsed * @param the body of JWT */ public AuthenticationOperation(Claims body){ params.put("status", "SUCCESS"); for (String key: body.keySet()){ Object value = body.get(key); if (value instanceof String){ params.put(key, (String)value); } } } /** * JSON Coder. * Use jackson or your preferred dependendy * @return */ public String toJSON(){ StringBuffer buf = new StringBuffer(); buf.append("{"); String prefix = ""; for (String key:params.keySet()){ buf.append(prefix).append("\"").append(key).append("\":\"").append(params.get(key)).append("\""); prefix=","; } buf.append("}"); return buf.toString(); } } ================================================ FILE: backend/src/java/com/aralink/sslsignature/sso/jwt/HMACKeyContainer.java ================================================ package com.aralink.sslsignature.sso.jwt; import io.jsonwebtoken.impl.crypto.MacProvider; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.Key; import javax.crypto.spec.SecretKeySpec; public class HMACKeyContainer { private Key key; public HMACKeyContainer()throws IOException{ this(null); } public HMACKeyContainer(String keyFile) throws IOException{ if (keyFile == null || keyFile.length()==0){ keyFile = "jwthmac.key"; } Path path = Paths.get(keyFile); if (!path.toFile().exists()){ //File not exists. Create new File generateKey(path); } else { //Reads the HMAC key from file byte[] data = Files.readAllBytes(path); key = hmacKeyFromEncoded(data); System.out.println("init HMAC key from file: "+path.toAbsolutePath()); } } public Key getHmacKey(){ return key; } private Key generateKey(Path path) throws IOException{ //path..createNewFile(); key = MacProvider.generateKey(JWTManager.DEFAULT_HMAC_KEY_ALGORITHM); byte data[] = key.getEncoded(); Files.write(path, data); System.out.println("created new HMAC key in file: "+path.toAbsolutePath()); return key; } public static Key hmacKeyFromEncoded(byte encodedHmacKey[]){ if (encodedHmacKey != null && encodedHmacKey.length>0){ Key key = new SecretKeySpec(encodedHmacKey,JWTManager.DEFAULT_HMAC_KEY_ALGORITHM.getJcaName()); return key; } return null; } } ================================================ FILE: backend/src/java/com/aralink/sslsignature/sso/jwt/JWTManager.java ================================================ package com.aralink.sslsignature.sso.jwt; import io.jsonwebtoken.Claims; import io.jsonwebtoken.ExpiredJwtException; import io.jsonwebtoken.JwtBuilder; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.MalformedJwtException; import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.SignatureException; import io.jsonwebtoken.UnsupportedJwtException; import java.security.Key; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Map; public class JWTManager { public final static SignatureAlgorithm DEFAULT_HMAC_SIGNATURE_ALGORITHM = SignatureAlgorithm.HS256; public final static SignatureAlgorithm DEFAULT_HMAC_KEY_ALGORITHM = SignatureAlgorithm.HS512; private HMACKeyContainer hmacKeyContainer; private String issuer = "JWT SAMPLE ISSUER"; private int expirationTimeInHours = 24; public JWTManager(HMACKeyContainer hmacKeyContainer){ this.hmacKeyContainer = hmacKeyContainer; } public String getIssuer() { return issuer; } public void setIssuer(String issuer) { this.issuer = issuer; } public int getExpirationTimeInHours() { return expirationTimeInHours; } public void setExpirationTimeInHours(int expirationTimeInHours) { this.expirationTimeInHours = expirationTimeInHours; } private Date exp (int calendar,int len){ GregorianCalendar gc = new GregorianCalendar(); gc.add(calendar,len); Date expires = gc.getTime(); return expires; } private boolean isExpired(Claims body, Date actual){ return body.getExpiration().before(actual); } private boolean isExpired(Claims body){ return isExpired(body,new Date()); } public String issueJWT(@SuppressWarnings("rawtypes") Map extra){ //get hmac signature key Key key = hmacKeyContainer.getHmacKey(); String subject = "none"; //Get required subject ID if (extra.get("sub") != null) subject = ((String[])extra.get("sub"))[0]; //Build token JwtBuilder builder = Jwts.builder() .setSubject(subject) .setIssuer(getIssuer()) .setIssuedAt(new java.util.Date()) .setExpiration(exp (Calendar.HOUR,getExpirationTimeInHours())); //Body with extra fields for (Object extKey: extra.keySet()){ if (!extKey.equals("sub")) builder.claim((String)extKey,((String[])extra.get(extKey))[0]); } String token = builder.signWith(JWTManager.DEFAULT_HMAC_SIGNATURE_ALGORITHM, key).compact(); return token; } public Claims validateJWT ( String jwtToken)throws Exception{ //Get signature key Key key = hmacKeyContainer.getHmacKey(); try{ //Check signature and parse body Claims body = Jwts.parser().setSigningKey(key).parseClaimsJws(jwtToken).getBody(); //Check expiration if (isExpired(body)) throw new Exception ( "key expired"); return body; }catch (UnsupportedJwtException e){ System.err.println("Bad JWT token: "+e.getMessage()); throw new Exception ( " Bad JWT token"); }catch (MalformedJwtException e){ System.err.println("Bad JWT token: "+e.getMessage()); throw new Exception ( " Bad JWT token"); }catch (IllegalArgumentException e){ System.err.println("Bad JWT token: "+e.getMessage()); throw new Exception ( " Bad JWT token"); }catch (SignatureException e){ System.err.println(" BAD PUBLIC KEY"); throw new Exception ( "Bad signature in JWT token"); } catch (ExpiredJwtException e){ System.err.println("Expired JWT token: "+e.getMessage()); throw new Exception ( "Expired JWT token: "+e.getMessage()); } } } ================================================ FILE: backend/src/java/com/aralink/sslsignature/sso/jwt/JWTServlet.java ================================================ package com.aralink.sslsignature.sso.jwt; import io.jsonwebtoken.Claims; import java.io.IOException; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @SuppressWarnings("serial") public class JWTServlet extends HttpServlet { private HMACKeyContainer hmacKeyContainer; private JWTManager jwtManager; public void init(ServletConfig config) throws ServletException { super.init(config); String keyFile = config.getInitParameter("keyFile"); // String issuer = config.getInitParameter("issuer"); try{ //Init HMAC key from file. If it not exists, creates a new one hmacKeyContainer = new HMACKeyContainer(keyFile); jwtManager = new JWTManager (hmacKeyContainer); }catch (IOException e){ throw new ServletException(e); } System.out.println("servlet init: "+keyFile); } public void doOptions(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("OPTIONS REQUESTS "); response.addHeader("Access-Control-Allow-Origin", "*"); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String jwt = request.getParameter("jwt"); if (jwt != null){ AuthenticationOperation result = null; //validateToken try{ Claims body = jwtManager.validateJWT(jwt); //Validation successful result = new AuthenticationOperation(body); System.out.println("JWT validation SUCCESS for SUB: "+body.getSubject()); }catch (Exception e){ //Validation fail result = new AuthenticationOperation(e); System.err.println("JWT validation failed: "+e.getMessage()); } //Response JSON & enable CORS response.setContentType("application/json"); response.addHeader("Access-Control-Allow-Origin", "*"); System.out.println(result.toJSON()); response.getWriter().print(result.toJSON()); } else { //Issue new token jwt = jwtManager.issueJWT(request.getParameterMap()); System.out.println("Issued new JWT "+jwt); //Response TEXT & enable CORS response.setContentType("text/html"); response.addHeader("Access-Control-Allow-Origin", "*"); response.getWriter().print(jwt); } } public void destroy() { // do nothing. } } ================================================ FILE: backend/src/web/WEB-INF/web.xml ================================================ SSLSIGNATURE {env.SVN_REVISION} 300 jwt com.aralink.sslsignature.sso.jwt.JWTServlet keyFile jwt.hmac jwt /jwt ================================================ FILE: build/build.xml ================================================ ================================================ FILE: build/gruntfile.js ================================================ module.exports = function(grunt) { // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), uglify: { options: { banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n' }, build: { src: '../client/resources/js/<%= pkg.name %>*.js', dest: '<%= pkg.name %>.min.js' } }, uglify: { build: { src: '../client/resources/html/*.js', dest: 'sso.min.js' } } }); // Load the plugin that provides the "uglify" task. grunt.loadNpmTasks('grunt-contrib-uglify'); // Default task(s). grunt.registerTask('default', ['uglify']); }; ================================================ FILE: build/ivy.xml ================================================ ================================================ FILE: build/package.json ================================================ { "name": "sslssso", "version": "1.0.0", "devDependencies": { "grunt": "~0.4.5", "grunt-contrib-jshint": "~0.10.0", "grunt-contrib-nodeunit": "~0.4.1", "grunt-contrib-uglify": "~0.5.0" } } ================================================ FILE: client/resources/html/sso.html ================================================ SSLSignature SSO IFRAME ================================================ FILE: client/resources/html/sso.js ================================================ var validationUrl; var validate; var accountId; var tokenId; var apiKey; function onIdentification(operation){ log(LogLevels.INFO ,"[SSO IFRAME] fire event onidentification jwt: "+ operation.jwt); //var domain = getGetParam2("domain"); //if (!domain || domain=="") domain = "*"; postMessageToListeners (operation,domain); } function onLogout(){ log(LogLevels.INFO ,"[SSO IFRAME] fire event onlogout "); //var domain = getGetParam2("domain"); //if (!domain || domain=="") domain = "*"; log(LogLevels.DEBUG,"[SSO IFRAME] postMessage to: "+ domain); var operation = {action:"sso.onlogout"}; postMessageToListeners (operation,domain); } function onLoad(){ log(LogLevels.INFO ,"[SSO IFRAME] fire event onload "); //var domain = getGetParam2("domain"); //if (!domain || domain=="") domain = "*"; log(LogLevels.DEBUG,"[SSO IFRAME] postMessage to: "+ domain); var operation = {action:"sso.onload"}; postMessageToListeners (operation,domain); } function postMessageToListeners (operation, domain){ log(LogLevels.DEBUG,"[SSO IFRAME] postMessage "+operation.action+" to: "+ domain); if (window.attachEvent) { // IE before version 9 window.parent.postMessage(JSON.stringify(operation), domain); } else { window.parent.postMessage(operation, domain); } } function doLogout(){ log(LogLevels.INFO,"[SSO IFRAME] logout "); localStorage.removeItem(tokenId); onLogout(); } function doLogin(jwt){ log(LogLevels.INFO,"[SSO IFRAME] login :"+jwt); localStorage.setItem(tokenId,jwt); /*if (isIE()){ //Mas mierda de IE. En el caso de IE11 no sincroniza entre pestaas si no haces esta guarrera. Y tampoco va localStorage.setItem('dummy', 'dummyvalue'); localStorage.removeItem('dummy'); } */ } function localStorageHandler(e) { log(LogLevels.DEBUG,'[SSO IFRAME] Successfully communicate with other tab'); log(LogLevels.DEBUG,'[SSO IFRAME] Received data: ' + localStorage.getItem(tokenId)); var jwtsso = localStorage.getItem(tokenId); if (jwtsso){ validateJWT (jwtsso); } else { onLogout(); } } function localStorageHandlerIE8(e) { log(LogLevels.DEBUG,'[SSO IFRAME] Successfully communicate with other tab IE8'); // var jwtsso = localStorage.getItem(tokenId); -> old value in IE // timeout waiting IE8 browser to update the new value setTimeout(function(){ var jwtsso = localStorage.getItem(tokenId); // new value if (jwtsso){ validateJWT (jwtsso); } else { onLogout(); } }, 1); // delay } function listener(event){ //if ( event.origin !== "https://pfb.sslsignature.com" ){ // return; //} log(LogLevels.DEBUG,"[SSO IFRAME] received event "); var data = event.data; //Chrome, firefox, IE11 , etc if (event.data && !event.data.action){ //<=IE8 & IE9 porque no soporta JSON en objetos de mensaje data = eval('(' + event.data+ ')'); } if(data.hasOwnProperty('action')) { log(LogLevels.DEBUG,"[SSO IFRAME] received event "+data.action); var action = data.action; if (action == 'logout'){ doLogout(); } else if (action == 'login'){ if (data.hasOwnProperty('jwt')){ doLogin(data.jwt); } } } else { log(LogLevels.WARN,"[SSO IFRAME] received unknown event "); } } function validateJWT(jwtsso){ if (validate && validationUrl){ //Invoke server to get remote validation of token signature, parse and return extra data if necessary validateJWTRemote(jwtsso); } else { //Do not validate. Expected token validation on first usage of jwt parseJWTLocal(jwtsso); } } function validateJWTRemote(jwtsso){ log(LogLevels.DEBUG,"[SSO IFRAME] Remote validation of JWT with url: "+validationUrl+ " accountId:"+ accountId+ " apiKey:"+apiKey); jwt = new JWT(jwtsso); log(LogLevels.DEBUG,jwt.payload()); var rest = new RestClient(validationUrl,accountId,apiKey); /* POST validationUrl jwt={jwtsso} Expected JSON response {status:SUCCESS,sub:yourUserId, jwt:newTokenIfNeeded, eidentifier:username, name:fullname, email:useremail, ... } or {AuthenticationOperation: {status:SUCCESS,sub:...} } */ rest.validateJWT(jwtsso, function (obj){ var operation = obj; if (obj.AuthenticationOperation){ operation = obj.AuthenticationOperation; } log(LogLevels.DEBUG,"[SSO IFRAME] Validating token "+operation.status); if (operation.status == 'SUCCESS') { log(LogLevels.INFO,"[SSO IFRAME] token is valid "); if (operation.jwt && operation.jwt != jwtsso){ log(LogLevels.INFO,"[SSO IFRAME] Backend issued a new JWT. Replace current token"); doLogin(operation.jwt); } else { operation.jwt = jwtsso; } operation.action = "sso.onidentification"; //Identification successful. Fire onIdentification event onIdentification(operation); } else { localStorage.removeItem(tokenId); log(LogLevels.ERROR,"[SSO IFRAME] invalid token: "+operation.error); } //Authentication process finish. //fire onload event onLoad(); }, function(err) { log(LogLevels.DEBUG,err); }); } function parseJWTLocal(jwtsso){ log(LogLevels.INFO,"[SSO IFRAME] Local parse of JWT (no signature validation)"); try{ var jwt = new JWT(jwtsso); var payload = jwt.payload(); log(LogLevels.DEBUG,payload); if (jwt.isExpired()) throw ("JWT expired"); //We have not validated. So UNKNOWN payload.status = 'UNKNOWN'; payload.action = "sso.onidentification"; payload.jwt = jwtsso; //Identification finished. Fire onIdentification event onIdentification(payload); } catch (err){ //Bad token. remove it localStorage.removeItem(tokenId); log(LogLevels.ERROR,"[SSO IFRAME] invalid token: "+err); } //Authentication process finish. //fire onload event onLoad(); } function ready(){ var jwtsso = localStorage.getItem(tokenId); log(LogLevels.INFO,"[SSO IFRAME] ready"); log(LogLevels.DEBUG,"[SSO IFRAME] " + tokenId + " = "+jwtsso); if (jwtsso){ validateJWT (jwtsso); } else { //OnLoad must be the last method invocation. Invoked head or from validateJWT after token validation onLoad(); } } function init(config){ //Listener for localStorage changes of ssls.sso.jwt.[accountId] tokens if (window.addEventListener) { // Normal browsers window.addEventListener("storage", localStorageHandler, false); } else { // for IE (why make your life more difficult) //Adems hay que suscribierse al documento y no al windows //Y para acabar de tocar los huevos, localStorage.getItem devuelve el valor viejo y no el nuevo. Por supuesto el evento no lleva la informacion //window.attachEvent("onstorage", localStorageHandlerIE8); document.attachEvent("onstorage", localStorageHandlerIE8); }; //Iframe message listener from SSO clients if (window.addEventListener){ addEventListener("message", listener, false); } else { attachEvent("onmessage", listener); } //onLoad document listener if (window.addEventListener) { // W3C standard window.addEventListener('load', ready, false); // NB **not** 'onload' } else if (window.attachEvent){ // Microsoft window.attachEvent('onload', ready); } validationUrl = config.validationUrl; validate = config.validate; accountId = config.accountId; tokenId = config.tokenId; apiKey = config.apiKey; log(LogLevels.INFO,"[SSO IFRAME] inited"); } //init(); ================================================ FILE: client/resources/html/sso_common.js ================================================ var LogLevels = {DEBUG:0, INFO:1, WARN:2, ERROR:3}; var logLevel = LogLevels.DEBUG; var console = window.console || { log: function() {} }; var Base64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(e){var t="";var n,r,i,s,o,u,a;var f=0;e=Base64._utf8_encode(e);while(f>2;o=(n&3)<<4|r>>4;u=(r&15)<<2|i>>6;a=i&63;if(isNaN(r)){u=a=64}else if(isNaN(i)){a=64}t=t+this._keyStr.charAt(s)+this._keyStr.charAt(o)+this._keyStr.charAt(u)+this._keyStr.charAt(a)}return t},decode:function(e){var t="";var n,r,i;var s,o,u,a;var f=0;e=e.replace(/[^A-Za-z0-9+/=]/g,"");while(f>4;r=(o&15)<<4|u>>2;i=(u&3)<<6|a;t=t+String.fromCharCode(n);if(u!=64){t=t+String.fromCharCode(r)}if(a!=64){t=t+String.fromCharCode(i)}}t=Base64._utf8_decode(t);return t},_utf8_encode:function(e){e=e.replace(/rn/g,"n");var t="";for(var n=0;n127&&r<2048){t+=String.fromCharCode(r>>6|192);t+=String.fromCharCode(r&63|128)}else{t+=String.fromCharCode(r>>12|224);t+=String.fromCharCode(r>>6&63|128);t+=String.fromCharCode(r&63|128)}}return t},_utf8_decode:function(e){var t="";var n=0;var r=c1=c2=0;while(n191&&r<224){c2=e.charCodeAt(n+1);t+=String.fromCharCode((r&31)<<6|c2&63);n+=2}else{c2=e.charCodeAt(n+1);c3=e.charCodeAt(n+2);t+=String.fromCharCode((r&15)<<12|(c2&63)<<6|c3&63);n+=3}}return t}} function log(level, object){ if (level >= logLevel){ console.log (object); } } function getOrigin(){ if (!window.location.origin) { window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: ''); } return window.location.origin; } function getGetParam (vr){ var src = String( window.location.href ).split('?')[1]; if (src != null) { var vrs = src.split('&'); for (var x = 0, c = vrs.length; x < c; x++) { if (vrs[x].indexOf(vr) == 0){ return decodeURI( vrs[x].split('=')[1] ); break; }; }; } else { return ""; } }; function JWT (jwt){ "use strict"; this.header = function() { var headerB64u = jwt.substring(0,jwt.indexOf('.')); var headerB64 = _b64utob64(headerB64u); var headerJSON = Base64.decode(headerB64); var header = JSON.parse( headerJSON ); return header; }; this.payload = function() { var payloadB64u = jwt.substring(jwt.indexOf('.') + 1, jwt.lastIndexOf('.')); var payloadB64 = _b64utob64(payloadB64u); var payloadJSON = Base64.decode(payloadB64); var payload = JSON.parse( payloadJSON ); return payload; }; this.isExpired = function(){ var body = this.payload(); if (body.exp){ return body.exp <= Date.now()/1000; } else { return true; } }; function _b64tob64u(a){ a=a.replace(/\=/g,""); a=a.replace(/\+/g,"-"); a=a.replace(/\//g,"_"); return a; }; function _b64utob64(a){ if(a.length%4==2){ a=a+"=="; }else{ if(a.length%4==3){ a=a+"="; } } a=a.replace(/-/g,"+"); a=a.replace(/_/g,"/"); return a; }; }; ================================================ FILE: client/resources/html/sso_rest.js ================================================ function RestClient (host,accountId,apiKey,scheme){ "use strict"; //this.host = host; //this.accountId = accountId; //this.apiKey = apiKey; scheme = _validateScheme(scheme); this.validateJWT = function (jwt,fulfill,reject){ //var uri = host+'/sso/' + accountId + '/jwt'; var uri = host; var request = {'jwt':jwt}; return _postFormNoJQuery(uri,request,fulfill,reject); }; function _validateScheme(scheme){ if (!scheme) scheme = "Basic"; if ( !(scheme == 'Basic' || scheme == 'JWT' || scheme == 'CJWT' )) throw "Scheme " + scheme + "not valid"; return scheme; } function _makeAuth(scheme, user, password) { var tok = user + ':' + password; var hash; if (window.btoa){ hash = btoa(tok); } else { hash = Base64.encode(tok); } return scheme + " " + hash; } function _get(url,fulfill,reject){ var contentType = "application/json; charset=utf-8"; log(LogLevels.INFO, "GET "+url+ " "+contentType); $.support.cors = true; $.ajax({ type: "GET", //GET or POST or PUT or DELETE verb url: url, // Location of the service crossdomain: true, contentType: contentType, accepts: { text: "application/json" }, dataType: "json", beforeSend: function (xhr) { xhr.setRequestHeader("Authorization", _makeAuth(scheme, accountId,apiKey)); } }).done(function (response) { response = _decodeJson(response); fulfill(response); }).fail(function (err) { reject(err); }); } function _post(url, request,fulfill,reject){ var contentType = "application/json; charset=utf-8"; var jsondata = null; if (request) jsondata = JSON.stringify(request, null, 4); log(LogLevels.INFO, "POST "+url+ " "+contentType); log(LogLevels.DEBUG, " Request: "+jsondata); $.support.cors = true; $.ajax({ type: "POST", //GET or POST or PUT or DELETE verb url: url, // Location of the service data: jsondata, //Data sent to server contentType: contentType, crossdomain: true, beforeSend: function (xhr) { xhr.setRequestHeader("Authorization", _makeAuth(scheme, accountId,apiKey)); } }).done(function (response) { response = _decodeJson(response); fulfill(response); }).fail(function (err) { reject(err); }); } function _postForm(url, request,fulfill,reject){ //return new Promise(function(fulfill, reject) { //var contentType = "application/json; charset=utf-8"; var contentType = "application/x-www-form-urlencoded"; var jsondata = null; if (request) jsondata = JSON.stringify(request, null, 4); log(LogLevels.INFO, "POST "+url+ " "+contentType); log(LogLevels.DEBUG, " Request: "+jsondata); $.support.cors = true; $.ajax({ type: "POST", //GET or POST or PUT or DELETE verb url: url, // Location of the service data: request, //Data sent to server contentType: contentType, crossdomain: true, beforeSend: function (xhr) { xhr.setRequestHeader("Authorization", _makeAuth(scheme, accountId,apiKey)); } }).done(function (response) { response = _decodeJson(response); fulfill(response); }).fail(function (err) { reject(err); }); //}); } function _postFormNoJQuery(url, request,fulfill,reject){ var contentType = "application/x-www-form-urlencoded"; var jsondata = null; if (request) jsondata = JSON.stringify(request, null, 4); log(LogLevels.INFO, "POST "+url+ " "+contentType); log(LogLevels.DEBUG, " Request: "+jsondata); _ajax.post( url, request, function (response) { response = _decodeJson(response); fulfill(response); }); } function _delete(url,fulfill,reject){ var contentType = "application/json; charset=utf-8"; var jsondata = null; log(LogLevels.INFO, "DELETE "+url+ " "+contentType); $.support.cors = true; $.ajax({ type: "DELETE", //GET or POST or PUT or DELETE verb url: url, // Location of the service data: jsondata, //Data sent to server contentType: contentType, crossdomain: true, beforeSend: function (xhr) { xhr.setRequestHeader("Authorization", _makeAuth(scheme, accountId,apiKey)); } }).done(function (response) { response = _decodeJson(response); fulfill(response); }).fail(function (err) { reject(err); }); } function _isAbv(value) { var ArrayBufferView = Object.getPrototypeOf(Object.getPrototypeOf(new Uint8Array)).constructor; return value instanceof ArrayBufferView; } function _isAb(value) { return value && value instanceof ArrayBuffer && value.byteLength; } function _postStream(url, data,fulfill,reject){ var contentType = "application/octet-stream"; log(LogLevels.INFO, "POST "+url+ " "+contentType); log(LogLevels.DEBUG, data); if (!_isAbv(data) && !_isAb(data)) throw "data is not an ArrayBuffer"; $.support.cors = true; $.ajax({ type: "POST", //GET or POST or PUT or DELETE verb url: url, // Location of the service data: data, //Data sent to server contentType: contentType, processData: false, crossdomain: true, beforeSend: function (xhr) { xhr.setRequestHeader("Authorization", _makeAuth(scheme, accountId,apiKey)); } }).done(function (response) { response = _decodeJson(response); fulfill(response); }).fail(function (err) { reject(err); }); } function _decodeJson(response) { if (response){ var jsonresponse = response; if (typeof response === 'object') jsonresponse = JSON.stringify(response, null, 4); log(LogLevels.DEBUG, " Response: "+jsonresponse); var obj = JSON.parse( jsonresponse ); return obj; }else { log(LogLevels.DEBUG, " Response: NULL"); return; } } function _convertMimetype(mimetype){ if (mimetype == 'gallery/manual') return 'application/pdf'; else if (mimetype == 'application/binary') return 'application/pdf'; return mimetype; } var _ajax = {}; _ajax.x = function () { if (typeof XMLHttpRequest !== 'undefined') { return new XMLHttpRequest(); } var versions = [ "MSXML2.XmlHttp.6.0", "MSXML2.XmlHttp.5.0", "MSXML2.XmlHttp.4.0", "MSXML2.XmlHttp.3.0", "MSXML2.XmlHttp.2.0", "Microsoft.XmlHttp" ]; var xhr; for (var i = 0; i < versions.length; i++) { try { xhr = new ActiveXObject(versions[i]); break; } catch (e) { } } return xhr; }; _ajax.send = function (url, callback, method, data, async) { if (async === undefined) { async = true; } var x = _ajax.x(); x.open(method, url, async); x.onreadystatechange = function () { if (x.readyState == 4) { callback(x.responseText); } }; if (method == 'POST') { x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); } x.send(data); }; _ajax.get = function (url, data, callback, async) { var query = []; for (var key in data) { query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key])); } _ajax.send(url + (query.length ? '?' + query.join('&') : ''), callback, 'GET', null, async); }; _ajax.post = function (url, data, callback, async) { var query = []; for (var key in data) { query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key])); } _ajax.send(url, callback, 'POST', query.join('&'), async); }; }; ================================================ FILE: client/resources/js/sslssso.js ================================================ sslssso = new sslssso(); var console = window.console || { log: function() {} }; function Observable(){ this.listen = function(type, method, scope, context) { var listeners, handlers; if (!(listeners = this.listeners)) { listeners = this.listeners = {}; } if (!(handlers = listeners[type])){ handlers = listeners[type] = []; } scope = (scope ? scope : window); handlers.push({ method: method, scope: scope, context: (context ? context : scope) }); } this.fireEvent = function(type, data, context) { var listeners, handlers, i, n, handler, scope; if (!(listeners = this.listeners)) { return; } if (!(handlers = listeners[type])){ return; } for (i = 0, n = handlers.length; i < n; i++){ handler = handlers[i]; if (typeof(context)!=="undefined" && context !== handler.context) continue; if (handler.method.call( handler.scope, this, type, data )===false) { return false; } } return true; } }; function sslssso (){ //"use strict"; var DEFAULT_IFRAME_URI = "../html/sso.html"; var obs = new Observable(); var config = {}; /* obs.listen("sso.onload", function(observable, eventType, data){ console.log("----------------"); console.log("sso.onload"); console.log("----------------"); }); */ this.listen = function(type, method, scope, context){ obs.listen(type,method,scope,context); } this.logout = function (){ var message = {action: "logout"}; postSSOMessage(message, _getUrl()); } this.login = function (jwt){ var message = {action: "login",jwt:jwt}; postSSOMessage(message, _getUrl()); } function _getMeta(name){ var metas = document.getElementsByTagName('meta'); for (var i=0; i jwtInfo = new HashMap(); jwtInfo.put("sub", "theSub"); jwtInfo.put("eidentifier", "theEidentifier"); jwtInfo.put("name", "theName"); jwtInfo.put("phone", "thePhone"); jwtInfo.put("other", "theOther"); //REquest a new JWT to server String jwt = client.postForm("/sso/jwt", jwtInfo); SimpleConsoleLogger.info(jwt); Assert.assertNotNull(jwt); //Validate the token signature Map jwtValidationInfo = new HashMap(); jwtValidationInfo.put("jwt", jwt); String authenticationResponseJson = client.postForm("/sso/jwt", jwtValidationInfo); SimpleConsoleLogger.info(authenticationResponseJson); //JWT token validated on server to Java Object Map map = new HashMap(); ObjectMapper mapper = new ObjectMapper(); map = mapper.readValue(authenticationResponseJson, new TypeReference>(){}); SimpleConsoleLogger.info("STATUS: "+map.get("status")+ " eidentifier"+ map.get("eidentifier")); Assert.assertEquals("SUCCESS", map.get("status")); } @Test public void alteredJWT() throws Exception { Map jwtInfo = new HashMap(); jwtInfo.put("sub", "theSub"); jwtInfo.put("eidentifier", "theEidentifier"); jwtInfo.put("name", "theName"); jwtInfo.put("phone", "thePhone"); jwtInfo.put("other", "theOther"); //REquest a new JWT to server String jwt = client.postForm("/sso/jwt", jwtInfo); SimpleConsoleLogger.info(jwt); Assert.assertNotNull(jwt); //Signature modified jwt = jwt + "XXX"; //Validate the token signature Map jwtValidationInfo = new HashMap(); jwtValidationInfo.put("jwt", jwt); String authenticationResponseJson = client.postForm("/sso/jwt", jwtValidationInfo); SimpleConsoleLogger.info(authenticationResponseJson); //JWT token validated on server to Java Object Map map = new HashMap(); ObjectMapper mapper = new ObjectMapper(); map = mapper.readValue(authenticationResponseJson, new TypeReference>(){}); SimpleConsoleLogger.info("STATUS: "+map.get("status")+ " eidentifier"+ map.get("eidentifier")); Assert.assertEquals("FAIL", map.get("status")); } @Test public void fakeJWT() throws Exception { //Create a token with a key autogenerated (not server key) Key key = MacProvider.generateKey(JWTManager.DEFAULT_HMAC_KEY_ALGORITHM); String jwt = Jwts.builder() .setSubject("fake") .signWith(JWTManager.DEFAULT_HMAC_SIGNATURE_ALGORITHM, key).compact(); //Validate token Map jwtValidationInfo = new HashMap(); jwtValidationInfo.put("jwt", jwt); String authenticationResponseJson = client.postForm("/sso/jwt", jwtValidationInfo); SimpleConsoleLogger.info(authenticationResponseJson); //JWT token validated on server to Java Object Map map = new HashMap(); ObjectMapper mapper = new ObjectMapper(); map = mapper.readValue(authenticationResponseJson, new TypeReference>(){}); SimpleConsoleLogger.info("STATUS: "+map.get("status")+ " eidentifier"+ map.get("eidentifier")); Assert.assertEquals("FAIL", map.get("status")); } } ================================================ FILE: test/java/com/aralink/sslsignature/sso/jwt/test/RestClient.java ================================================ package com.aralink.sslsignature.sso.jwt.test; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.Map; import javax.xml.bind.DatatypeConverter; public class RestClient { private static final String CONTENT_TYPE_OCTET_STREAM = "application/octet-stream"; private static final String CONTENT_TYPE_JSON = "application/json"; private static final String CONTENT_TYPE_FORM = "application/x-www-form-urlencoded"; private String baseurl; private String user; private String password; public RestClient (String url){ setUrl(url); } public RestClient (String url, String user, String password){ setUrl(url); setUser(user); setPassword(password); } public String getUrl() { return baseurl; } public void setUrl(String url) { this.baseurl = url; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String postJson(String uri, String jsonRequest) throws IOException{ HttpURLConnection conn = getConnection("POST",uri,CONTENT_TYPE_JSON); conn.connect(); SimpleConsoleLogger.debug("request body: "+jsonRequest); upload(conn,jsonRequest.getBytes()); return processJsonResponse(conn); } public String postForm(String uri, Map formParams) throws IOException{ HttpURLConnection conn = getConnection("POST",uri,CONTENT_TYPE_FORM); conn.connect(); String request = serialize(formParams); SimpleConsoleLogger.debug("request body: "+formParams); upload(conn,request.getBytes()); return processJsonResponse(conn); } public String post(String uri) throws IOException{ HttpURLConnection conn = getConnection("POST",uri,CONTENT_TYPE_JSON); conn.connect(); return processJsonResponse(conn); } public String get(String uri) throws IOException{ HttpURLConnection conn = getConnection("GET",uri,CONTENT_TYPE_JSON); conn.setRequestProperty("Accept", CONTENT_TYPE_JSON); conn.connect(); return processJsonResponse(conn); } public InputStream getStream(String uri) throws IOException{ HttpURLConnection conn = getConnection("GET",uri,CONTENT_TYPE_JSON); conn.connect(); return processStreamResponse(conn); } public String delete(String uri) throws IOException{ HttpURLConnection conn = getConnection("DELETE",uri,CONTENT_TYPE_JSON); conn.connect(); return processJsonResponse(conn); } public String postStream(String uri, byte data[])throws IOException{ HttpURLConnection conn = getConnection("POST",uri,CONTENT_TYPE_OCTET_STREAM); conn.connect(); upload(conn,data); return processJsonResponse(conn); } private String processJsonResponse(HttpURLConnection conn)throws IOException{ int statusCode = conn.getResponseCode(); SimpleConsoleLogger.info("response code: "+statusCode); if (statusCode == 200 ||statusCode == 201 ||statusCode == 204) { //OK InputStream is = conn.getInputStream(); String responseString = read(is); SimpleConsoleLogger.debug("response body: "+responseString); return responseString; } else { InputStream is =conn.getErrorStream(); String error = read(is); throw new IOException(error); } } private InputStream processStreamResponse(HttpURLConnection conn)throws IOException{ //Recibe respuesta int statusCode = conn.getResponseCode(); SimpleConsoleLogger.info("response code: "+statusCode); if (statusCode == 200 ||statusCode == 201) { InputStream is = conn.getInputStream(); return is; } else { InputStream is =conn.getErrorStream(); String error = read(is); throw new IOException(error); } } private void upload(HttpURLConnection conn, byte data[]) throws IOException{ OutputStream os = conn.getOutputStream(); os.write(data); os.flush(); os.close(); } private HttpURLConnection getConnection(String method,String uri, String contentType) throws IOException{ String URL = baseurl + uri; SimpleConsoleLogger.info(method+" "+URL); SimpleConsoleLogger.debug("username:"+user+ " PASSWORD:"+password); URL url = new URL(URL); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestMethod(method); if ("POST".equals(method)) conn.setDoOutput(true); if (user != null){ String basicAuth = "Basic " + DatatypeConverter.printBase64Binary((user+":"+password).getBytes()); conn.setRequestProperty ("Authorization", basicAuth); conn.setRequestProperty("Content-Type",contentType); } return conn; } private static String read(InputStream in) throws IOException{ InputStreamReader is = new InputStreamReader(in); StringBuilder sb=new StringBuilder(); BufferedReader br = new BufferedReader(is); String read = br.readLine(); while(read != null) { sb.append(read); read =br.readLine(); } is.close(); return sb.toString(); } private static String serialize(Map params){ StringBuffer buf = new StringBuffer(); String prefix = ""; for (String key:params.keySet()){ buf.append(prefix).append(key).append("=").append(params.get(key)); prefix="&"; } return buf.toString(); } } ================================================ FILE: test/java/com/aralink/sslsignature/sso/jwt/test/SimpleConsoleLogger.java ================================================ package com.aralink.sslsignature.sso.jwt.test; public class SimpleConsoleLogger { public enum Level { ERROR, WARN, INFO, DEBUG,TRACE} /* public enum Level { ERROR(0), WARN(1), INFO(2), DEBUG(3),TRACE(4); private final int id; Level(int id) { this.id = id; } public int getValue() { return id; } }; */ private static Level level = Level.INFO; public static void setLevel (Level l){ level = l; } public static Level getLevel(){ return level; } public static void info(String message){ log(Level.INFO,message); } public static void error(String message){ log(Level.ERROR,message); } public static void warn(String message){ log(Level.WARN,message); } public static void debug(String message){ log(Level.DEBUG,message); } public static void trace(String message){ log(Level.TRACE,message); } public static void log(Level level, String message){ log(level,message,null); } public static void log(Level level, String message, Throwable throwable){ if (level.ordinal() <= getLevel().ordinal()){ System.out.println(level.name()+ " "+message); if (throwable != null) throwable.printStackTrace(); } } } ================================================ FILE: test/web/hosted/index.html ================================================ SSLSignature - CryptoKeys ================================================ FILE: test/web/hosted/js/config.js ================================================ var config = { apiUrl: 'https://produccion.sslsignature.com/sslsignature', accountId: '5995a3c9-678b-4338-a674-362af68b9ef9', apiKey: "Qt89SdnW", tokenType: "Basic", cryptobankingAppImage: "../images/qr_cb_des.jpg", cryptobankingAppKey:"AIzaSyASSQmFExB9NNfNzhlsihdI0TQi5m8G6uY", registerSuccessUrl: 'https://produccion.sslsignature.com/sso/hosted/index.html', signInSuccessUrl: 'https://produccion.sslsignature.com/sso/hosted/index.html', signInOptions: ["CERTIFICATE", "CLAVE","CRYPTOKEYS","WEBCRYPTO", "PASSWORD"], siteTitle: "SSLSignature Sample Login Form", siteDescription: "Select ID method" }; ================================================ FILE: test/web/hosted/js/index.js ================================================ var uAg = navigator.userAgent.toLowerCase(); var isMobile = !!uAg.match(/android|iphone|ipad|ipod|blackberry|symbianos/i); var keyStore = null; var ssls = null; var userId = null; var userConnected = null; var keyRequest =null; var currentKey = null; var jwt = null; var otp = null; var deviceId = null; var deviceDescription = null; var deviceCharacteristics = null; var identified = false; function start(conf){ config = conf; ssls = new SSLSignature(config.apiUrl, config.accountId, config.apiKey,config.tokenType); console.log ("Create sslsignature service agent url:"+config.apiUrl+ " accountId:"+config.accountId+ " "+config.apiKey); } $(document).ready(function(){ //Evita que IE11 cachee peticiones $.ajaxSetup({ cache: false }) //$('.modificable').on('change input',initRequest); //$('#abortButton').hide(); $('#showOnlyActive').change(function() { listDevices(userId); }); otp = getGetParam('otp'); var browserInfo = getBrowserInfo(); deviceDescription = browserInfo.name+ " "+browserInfo.version+ "("+navigator.platform+")"; deviceCharacteristics = navigator.userAgent; /* new Fingerprint2().get(function(result){ console.log("deviceId:"+ result); deviceId = result; }); */ console.log ("deviceDescription: "+deviceDescription); console.log ("deviceCharacteristics: "+deviceCharacteristics); }); ///////////////////// //////// SSO METHODS ///////////////////// function onIdentification(operation){ console.log("SSO PAGE onIdentification"); identificationPerformed({AuthenticationOperation:operation}); identified = true; } function onLoad(){ console.log("SSO PAGE onLoad"); if (!identified){ if (otp){ recoverFailedIdentification (otp); } else { configureForm('notidentified'); } } } function onLogout(){ console.log("SSO PAGE onLogout"); configureForm('notidentified'); } ///////////////////// //////// ///////////////////// function configureForm(mode){ if (mode == 'notidentified'){ $('#notIdentified').show(); $('#identified').hide(); $("#logged").hide(); }else if (mode == 'identificationFailed'){ $('#notIdentified').hide(); $('#identified').show(); $('#idOk').hide(); $('#idFailed').show(); $("#logged").hide(); }else if (mode == 'notregistered'){ $('#notIdentified').hide(); $('#identified').show(); $('#idOk').show(); $('#idFailed').hide(); $("#logged").hide(); } else if (mode =='logged'){ $('#notIdentified').hide(); $('#identified').hide(); $("#logged").show(); $("#newDevice").show(); $("#registeredDevice").hide(); $("#signedTransaction").hide(); } else if (mode =='registeredDevice'){ $('#notIdentified').hide(); $('#identified').hide(); $("#logged").show(); $("#newDevice").hide(); $("#registeredDevice").show(); $("#signedTransaction").show(); } } function recoverFailedIdentification(otp){ console.log("Identification failed. OTP with description = "+otp) ssls.login(otp).then(function (obj){ identificationPerformed(obj); }).catch (function (result){ console.log(result); configureForm('notidentified'); }); } function identificationPerformed(obj){ console.log ("Identification performed with status: "+obj.AuthenticationOperation.status); //Muestra la información de la autenticación, sea correcta o no if (obj.AuthenticationOperation.status == 'SUCCESS') { var userId = obj.AuthenticationOperation.userId; var jwt = obj.AuthenticationOperation.jwt; if (jwt){ console.log ("JWT: "+jwt); } infoSignature(obj); if (userId){ console.log ("User registered with userId "+userId); configureForm('logged'); login(userId, jwt,"JWT"); } else { console.log ("User identified but not registered") configureForm('notregistered') } } else { console.log ("Identification failed: "+obj.AuthenticationOperation.error) infoSignature(obj); configureForm('identificationFailed'); } } function infoSignature(obj) { var status = obj.AuthenticationOperation.status; var error = ""; var infoSection =""; var alertClass = ""; if (status == "SUCCESS" || status=="UNKNOWN"){ image = ""; status = "ID successful"; alertClass = "alert alert-success well-sm"; }else if (status == "FAIL"){ image = ""; status = "ID fail "+obj.AuthenticationOperation.error; alertClass = "alert alert-danger well-sm"; } status = status +" ("+obj.AuthenticationOperation.mode+") perfomed at "+obj.AuthenticationOperation.date; var nameInfo = "Name: "+obj.AuthenticationOperation.name; if (obj.AuthenticationOperation.phone){ nameInfo = nameInfo + " Phone: "+obj.AuthenticationOperation.phone; } if (obj.AuthenticationOperation.email){ nameInfo = nameInfo +" Email: "+obj.AuthenticationOperation.email ; } if (obj.AuthenticationOperation.nif){ idInfo = obj.AuthenticationOperation.nif; } else if (obj.AuthenticationOperation.eIdentifier){ idInfo = obj.AuthenticationOperation.eIdentifier; } else if (obj.AuthenticationOperation.eidentifier){ idInfo = obj.AuthenticationOperation.eidentifier; } else { idInfo = ""; } jwtInfo = "JWT: "+obj.AuthenticationOperation.jwt; infoSection = "
    " +"
  • ID: "+idInfo+"
  • " +"
  • "+nameInfo+"
  • " +"
  • "+jwtInfo+"
  • " +"
"; var section = "
" +"
" +" "+image+"" +"
" +"
" +"

"+status+"

" + infoSection + "
" + "
"; var text = $("
"+section+"
"); $('#identificationInfo').replaceWith(text); } function login (username,password,scheme){ sslsUser = new SSLSignature(config.apiUrl,username,password,scheme); sslsUser.getUser().then (function(us){ userConnected = us.User; userId = us.User.id; $("#pageTitle").html("Welcome to CryptoKeys, "+us.User.name+"!"); console.log ("log user: "+userId); if (scheme != 'JWT'){ //Autenticación basic, procedente de registro. Guardar token en SSO console.log(" Obtain JWT and store in SSO localStorage"); sslsUser.issueJWT(userId).then(function(jwtResponse){ jwt = jwtResponse.JWT.data; console.log("Issued JWT token by server: "+jwt); //Guardar token en SSO sslssso.login(jwt); //Chequear claves openCryptoKeyStore(); }).catch (function (err){ console.log(err); callFailed(err); }); } else { //Chequear claves openCryptoKeyStore(); } return sslsUser.issueJWT(userId); }).then (function (jwtResponse){ jwt = jwtResponse.JWT.data; console.log("Issued JWT token by server: "+jwt); }).catch (function (err){ console.log(err); callFailed(err); }); } function openCryptoKeyStore(){ keyStore = new KeyStore(); keyStore.open("CBKeyStore").then(function() { console.log ("KeyStore opened"); //Buscamos si en el navegador hay una key asociada a la cuenta de usuario return keyStore.getKey("name",userId); }).then (function (pkcs12Entry){ console.log("Key exists. Validate with server signing and example text"); validateCurrentKeyAndRequestIfNotValid(pkcs12Entry); }).catch (function (err){ console.log(err); console.log("Key does not exists. Enable button so user can request one"); configureNewKeyForm(); //requestAKey(); }); } function keyExists(pkcs12Entry){ currentKey = pkcs12Entry; listDevices(userId); configureForm('registeredDevice'); window.location="#userAuthentication"; } function requestAKey(){ configureForm('logged'); ssls.keyRequest(userConnected.id).then (function (kr){ console.log ("key requested"); keyRequest = kr; }).catch (function (err){ console.log(err); var error = "No se ha podido solicitar una nueva clave privada"; if (err && err.responseJSON ){ error = error + ": "+err.responseJSON.error; } else if (err) { error = error + ": "+err.status+ "-"+err.statusText; } error = error + "\nCon este usuario no va a poder realizar operaciones. ¿Desea borrarlo y volver a registrarse?"; if (confirm(error)) { ssls.deleteUser(userConnected.id).then (function (){ console.log("User "+userConnected.id+" deleted"); location.reload(); }).catch (function (err){ console.log("Error deleting user"+userConnected.id); location.reload(); }); } }); } function keyCreated(pkcs12Entry){ currentKey = pkcs12Entry; configureForm('registeredDevice'); listDevices(userId); } function handleLogoutClick(){ sslssso.logout(); } function handleEnrollClick () { console.log("proceed to enroll "); //Genera un par de claves privada y pública var keys = forge.pki.rsa.generateKeyPair(1024); // convierte de Forge public key a formatos PEM y DER para enviar a servidor. Esta parte sobraría con el envío de pkcs10, pero desde aquí es más fácil extraer cosas que en servidor. var publicKeyPem = forge.pki.publicKeyToPem(keys.publicKey); var subjectPublicKeyInfo = forge.pki.publicKeyToAsn1(keys.publicKey); var publicKeyInfoDer = forge.asn1.toDer(subjectPublicKeyInfo).getBytes(); var publicKeyb64 = forge.util.encode64(publicKeyInfoDer); //Crea una solicitud de certificado PKCS10 var csr = createCSR(keys,"ES",userConnected.name,userConnected.id); //Pasa a PEM format var csrPem = forge.pki.certificationRequestToPem(csr); //Resto de datos del registro de clave. Incluye la clave pública y datos del dispositivo keyRequest.KeyRequest.csrPem = csrPem; keyRequest.KeyRequest.deviceId = deviceId; keyRequest.KeyRequest.deviceDescription = deviceDescription; keyRequest.KeyRequest.deviceCharacteristics = deviceCharacteristics; keyRequest.KeyRequest.engine = "WEBCRYPTO"; keyRequest.KeyRequest.otp = $('#otp').val(); keyRequest.KeyRequest.publicKey = publicKeyb64; //Envía petición a servidor, ID de operación, OTP respondido y CSR con la clave pública ssls.keyRegister(keyRequest.KeyRequest.userId,keyRequest.KeyRequest.id,keyRequest).then (function (csrResponse){ console.log("CSR response from server"); console.log(csrResponse); var pkcsEntry = new PKCS12Entry(); pkcsEntry.fromCsrP7b(keys.privateKey,csrResponse.DeviceKey.certificatep7b); pkcsEntry.name = userConnected.id; pkcsEntry.keyId = csrResponse.DeviceKey.id; pkcsEntry.keyName = userConnected.name; return keyStore.importCertificate(pkcsEntry,false); }).then(function(pkcs12Entry) { console.log ("Imported CSR key, generated local, signed on server: "+pkcs12Entry.name); keyCreated(pkcs12Entry); }).catch (function (err){ console.log(err); enrollFailed(err); }); } function enrollFailed(result){ $('#newDeviceSend').hide(); $('#newDeviceErrorMessage').text("La identificación no ha sido correcta: "+result.status+"-"+result.responseText); $('#newDeviceErrorMessage').show(); $('#newDeviceError').show(); } function configureNewKeyForm(){ $('#otp').val(null); $('#newDeviceSend').hide(); $('#newDeviceErrorMessage').text(""); $('#newDeviceErrorMessage').hide(); $('#resendOtp').text(" Habilitar CryptoKeys "); $('#newDeviceError').show(); //requestAKey(); } function configureBadKeyForm(){ $('#otp').val(null); $('#newDeviceSend').hide(); $('#newDeviceErrorMessage').text("La clave existe pero no es válida"); $('#newDeviceErrorMessage').show(); $('#resendOtp').text(" Solicitar nueva clave "); $('#newDeviceError').show(); //requestAKey(); } function handleResendClick(){ $('#otp').val(null); $('#newDeviceError').hide(); $('#newDeviceErrorMessage').text(""); $('#resendOtp').text(" Reintentar "); $('#newDeviceSend').show(); requestAKey(); } function handleExecuteSignedTransactionClick(){ if (!currentKey){ showCheckResultMessage("No dispone de clave de firma. Por favor, validese primero.", "alert-warning"); return; } //La clave privada solo se puede usar con pin? if (currentKey.pin){ password_prompt("La clave de identificación requiere PIN para habilitar el uso. Introdúzcalo a continuación","Aceptar",320,300,executeSignedTransactionImpl); } else { executeSignedTransactionImpl(); } } function executeSignedTransactionImpl(pin){ var textToSign = "Authorization request text to sign"; var message = "1. Signing challenge with a private key
"; var st = new SignatureToken(); st.webcryptosign(textToSign,currentKey,pin).then (function (signature){ message = message + "2. Sending signature to server
"; var signatureB64 = forge.util.encode64(arrayBufferToString(signature)); console.log ("signedData: "+signatureB64); var dataB64 = forge.util.encode64(textToSign); var check ={KeyCheck:{data:dataB64,signature:signatureB64}}; return ssls.userKeyCheck(userId,check); }).then (function(){ message = message +"3. Transaction validated"; showCheckResultMessage(message, "alert-success"); }).catch (function (err){ console.log(err); message = message + "Signature not validated. Transaction can not be performed" var motivo = null; if (err && err.responseJSON) message = message +": " + err.responseJSON.error; else if (err) message = message +": " + err; showCheckResultMessage( message, "alert-danger"); }); } function validateCurrentKeyAndRequestIfNotValid(pkcs12Entry){ //La clave privada solo se puede usar con pin?. En ese caso se da por buena y ya la validaremos con la primera transacción if (pkcs12Entry.pin) return true; var textToSign = "Validating key"; var pin = null; var st = new SignatureToken(); st.webcryptosign(textToSign,pkcs12Entry,pin).then (function (signature){ var signatureB64 = forge.util.encode64(arrayBufferToString(signature)); var dataB64 = forge.util.encode64(textToSign); var check ={KeyCheck:{data:dataB64,signature:signatureB64}}; return ssls.userKeyCheck(userId,check); }).then (function(){ console.log("The key is valid"); keyExists(pkcs12Entry); }).catch (function (err){ console.log(err); console.log("The key is not valid. Deleting key for user: "+userId); keyStore.deleteKey(null,userId).then (function(){ console.log("Invalid key deleted"); currentKey = null; //requestAKey(); configureBadKeyForm(); }); }); } function doDeleteKey(){ keyStore.deleteKey(null,userId).then(function (){ console.log ("key deleted from keystore for user: "+userId); var currentKeyToRevoke = currentKey; if (currentKeyToRevoke && currentKeyToRevoke.keyId && !currentKeyToRevoke.revoked){ ssls.keyRevoke(userId,currentKeyToRevoke.keyId).then(function(){ console.log("Key revoked in server "+currentKeyToRevoke.keyId); listDevices(userId); }).catch (function (err){ console.log (err); console.log("Error revoking key in server "+currentKeyToRevoke.keyId); listDevices(userId); }); } else{ listDevices(userId); } $("#userId").val(null); currentKey = null; }).catch (function (err){ console.log(err); }); return } function showCheckResultMessage(mensaje, alertType){ if (!alertType){ alertType = "alert-info" } var text = ""; $('#checkResultMessage').replaceWith(text); } function callFailed(result) { console.log(result); alert('Service call failed: ' + result.status + ' - ' + result.statusText + ' - ' +result.responseText); //showResponse ('Service call failed: ' + result.status + ' - ' + result.statusText + ' - ' +result.responseText); } function generateCSR(userConnected,keys){ var CN = null; if (userConnected.nif) CN = userConnected.nif; else if (userConnected.email) CN = userConnected.email; var C = "ES"; var SERIALNUMBER = userConnected.id; var extractable = false; //generate PKCS10 request var csr = createCSR(keys,C,CN,SERIALNUMBER); //Pasa a PEM format var csrPem = forge.pki.certificationRequestToPem(csr); return csrPem; } function createCSR(keys, C,CN,SERIALNUMBER){ // create a certification request (CSR) var csr = forge.pki.createCertificationRequest(); csr.publicKey = keys.publicKey; csr.setSubject([{ name: 'commonName', value: CN }, { name: 'countryName', value: C }, { name: 'serialName', value: SERIALNUMBER }]); // set (optional) attributes /* csr.setAttributes([{ name: 'challengePassword', value: 'password' }, { name: 'unstructuredName', value: 'SSL certificate, Inc.' }, { name: 'extensionRequest', extensions: [{ name: 'subjectAltName', altNames: [{ // 2 is DNS type type: 2, value: 'test.domain.com' }, { type: 2, value: 'other.domain.com', }, { type: 2, value: 'www.domain.net' }] }] }]); */ // sign certification request csr.sign(keys.privateKey); // verify certification request var verified = csr.verify(); return csr; } function listDevices(userId){ console.log("listing keys"); ssls.keyList(userId).then(function(list) { console.log(list.DeviceKey); $("#theDeviceList > tbody").empty(); for (var i=0; i" +" " + ""; if (key.revoked){ keyActions = ""; } var tableElement = "" // + "" + ""+name+"" + ""+actual+"" + ""+keyEngine+"" + ""+keyStatus+"" + ""+keyActions+"" +""; if (!showOnlyActive || !key.revoked) $('#theDeviceList').append(tableElement); } function doRevokeKey(selectedKeyId){ //var selectedKeyId =$('input:radio[name=key]:checked').val(); console.log ("Revoking key "+selectedKeyId); if (selectedKeyId){ ssls.keyRevoke(userId,selectedKeyId).then(function(){ listDevices(userId); }).catch(function(err) { alert("Could not delete key : " + err); }); } } function handleRegisterDeviceClick(){ var message = "Click to start mobile linking process"; if (isMobile ){ var link = makeRegisterLink(userId); var section = ""; $('#checkRegisterMessage').replaceWith(section); } else { var qrLink = config.apiUrl+"/account/"+userId+"/qr?userId="+userId+ "&jwt="+jwt; $('#qrdevice').attr("src",qrLink); $('#registerDeviceDialog').modal('show') } } function handleRefreshDevicesClick(){ listDevices(userId); } function handleExecuteSignedTransactionDoubleFactorClick(){ var textToSign = "Double factor transaction"; var request = { Authorization : { userId : userId, appKey: config.cryptobankingAppKey,channel:'PUSH',mode:'DIGITAL_SIGNATURE',message: textToSign }}; ssls.postAuthorization(request).then (function(obj){ authorizationResponse(obj); initTimer(); }).catch (function (err){ callFailed(err); }); } function checkCallStatus(){ ssls.getAuthorization (authorizationId).then (function (obj){ var status = obj.Authorization.status; if (isAuthorizationFinished(status)) finishAuthorization(obj.Authorization); }).catch (function (result){ callFailed(result); }); } function authorizationResponse(obj) { authorizationId = obj.Authorization.id; console.log("authorization Id : "+authorizationId); $('#abortButton').show(); $('#sendTransactionDoubleFactor').hide(); $('#textToSignDoubleFactor').hide(); var message = "Requesting authorization to your linked device..."; if (isMobile ){ var link = makeAuthorizationLink(obj.Authorization); var section = ""; $('#checkResultMessage').replaceWith(section); } else { showCheckResultMessage(message); } } function handleDownloadAppClick(){ if (!isMobile){ $('#qrimage').attr("src",config.cryptobankingAppImage); $('#downloadAndroidDialog').modal('show') } else { window.open(cryptobankingApp) } } function makeAuthorizationLink(authorization){ var protocol = "cb"; var appUrl = "com.aralink.cryptobanking.authorization"; var p1 = "id="+authorization.id; //var p2 = "web="+webHost; var p2 = "web="+config.apiUrl; var p3 = "data="+authorization.dataToSign; var link = protocol + "://" + appUrl+ "?"+p1+"&"+p2+"&"+p3; console.log(link) return link; } function makeRegisterLink(userId){ var protocol = "cb"; var appUrl = "com.aralink.cryptobanking.register"; var p1 = "userId="+userId; var p2 = "web="+config.apiUrl; var p3 = "jwt="+jwt; //p2 = "web=https://10.5.3.9:444/sslsignature"; var link = protocol + "://" + appUrl+ "?"+p1+"&"+p2+"&"+p3; console.log(link) return link; } function isAuthorizationFinished(status) { return (status == "CANCEL" || status=="SUCCESS" || status =="FAIL") } function finishAuthorization(authorization) { cancelTimer(); var mode = authorization.mode; var status = authorization.status; console.log ("Authorization status ="+status); var image; var alertType; if (status == "CANCEL"){ image = ""; alertType = "alert-warning"; }else if (status == "SUCCESS"){ image = ""; alertType = "alert-success"; }else if (status == "FAIL"){ image = ""; alertType = "alert-danger"; }else{ image = ""; alertType = "alert-info"; } var section = ""; return keyElement; } function listCryptoKeyStore(){ cbKeyStore.listKeys().then(function(list) { $( "#cryptoKeyList" ).empty(); for (var i=0; i"+ ""+ name+ ""+ ""; return keyElement; } function escapeHTML(s) { return s.toString().replace(/&/g, "&").replace(//g, ">").replace(/"/g, """).replace(/'/g, "'"); } function handleDeleteClick(){ var selectedKeyId = parseInt($('input:radio[name=key]:checked').val()); console.log ("Deleting key "+selectedKeyId); if (selectedKeyId){ keyStore.deleteKey(selectedKeyId).then(function(){ listKeyStore(); }).catch(function(err) { alert("Could not delete key : " + err); }); } } function handleDeleteCryptoKeyClick(){ var selectedKeyId = parseInt($('input:radio[name=cryptokey]:checked').val()); console.log ("Deleting key "+selectedKeyId); if (selectedKeyId){ cbKeyStore.deleteKey(selectedKeyId).then(function(){ listCryptoKeyStore(); }).catch(function(err) { alert("Could not delete key : " + err); }); } } function handleImportPkcs12Click(){ var file = document.getElementById('pkcs12File').files[0]; var password = $("#password").val(); var extractable = $('#extractable').is(':checked'); importPkcs12(file, password,extractable); } function handleExportClick(){ var selectedKeyId = parseInt($('input:radio[name=key]:checked').val()); var selectedKeyName; console.log ("Exporting key "+selectedKeyId); keyStore.getKey("id",selectedKeyId). then (function (pkcs12Entry){ selectedKeyName = pkcs12Entry.name; console.log("exportKey:"+ selectedKeyName); var password = window.prompt("Insert password for .p12",""); return keyStore.exportKey (selectedKeyId,password); }).then(function(p12b64){ if (isIE()) downloadAsBlob(p12b64,selectedKeyName); else { var downloadLink = 'data:application/x-pkcs12;base64,' + p12b64; window.location = downloadLink; } }).catch (function( err){ alert("Error exporting key: "+err); }); } function downloadAsBlob(p12b64,selectedKeyName){ var blob = b64toBlob(p12b64,'application/x-pkcs12'); var name = selectedKeyName+ ".p12"; if (window.saveAs) { window.saveAs(blob, name); } else { navigator.saveBlob = navigator.saveBlob || navigator.msSaveBlob || navigator.mozSaveBlob || navigator.webkitSaveBlob; navigator.saveBlob(blob, name); } } ================================================ FILE: test/web/hosted/js/login.js ================================================ var uAg = navigator.userAgent.toLowerCase(); var isMobile = !!uAg.match(/android|iphone|ipad|ipod|blackberry|symbianos/i); var config; var webcrypto = true; var webcryptoError; var keyStore; var keyStoreList; var cbKeyStore; var cbKeyStoreList; $(function () { $("[data-toggle='tooltip']").tooltip(); }); function start(conf){ config = conf; ssls = new SSLSignature(config.apiUrl, config.accountId, config.apiKey,config.tokenType); } $(document).ready(function(){ configureForm(); if (isWebCryptoEnabled()){ checkWebCrypto(); openWebCryptoKeyStore(); } if (isCryptoKeysEnabled()){ checkCryptoKeys(); openCryptoKeysKeyStore(); } }); function configureForm(){ $("#webcryptoOff").hide(); $("#cryptokeysOff").hide(); if (!isCertificateEnabled()){ $("#idByCert").hide(); } if (!isClaveEnabled()){ $("#idByClave").hide(); } if (!isWebCryptoEnabled()){ $("#webcryptoListOn").hide(); $("#webcryptoOff").hide(); } if (!isCryptoKeysEnabled()){ $("#cryptokeysListOn").hide(); $("#cryptokeysOff").hide(); } if (!isPasswordEnabled()){ $("#idByPassword").hide(); } if (config.siteTitle){ $("#siteTitle").text(config.siteTitle); } if (config.siteDescription){ $("#siteDescription").text(config.siteDescription); } } function isWebCryptoEnabled(){ return !(config.signInOptions && config.signInOptions.indexOf("WEBCRYPTO") == -1); } function isCryptoKeysEnabled(){ return !(config.signInOptions && config.signInOptions.indexOf("CRYPTOKEYS") == -1); } function isCertificateEnabled(){ return !(config.signInOptions && config.signInOptions.indexOf("CERTIFICATE") == -1); } function isClaveEnabled(){ return !(config.signInOptions && config.signInOptions.indexOf("CLAVE") == -1); } function isPasswordEnabled(){ return !(config.signInOptions && config.signInOptions.indexOf("PASSWORD") == -1); } function checkWebCrypto(){ if (!window.crypto || !window.crypto.subtle) { disableWebCrypto("Web Cryptographi API no soportada!"); } if (!window.indexedDB) { disableWebCrypto("IndexedDB no soportada!"); } } function checkCryptoKeys(){ if (!window.crypto || !window.crypto.subtle) { disableCryptoKeys("Web Cryptographi API no soportada!"); } if (!window.indexedDB) { disableCryptoKeys("IndexedDB no soportada!"); } } function disableWebCrypto(message){ webcrypto = false; webcryptoError = message; $("#webcryptoOff").attr('title', message).tooltip('fixTitle').tooltip('show'); $("#webcryptoOff").show(); $("#webcryptoListOn").hide(); } function disableCryptoKeys(message){ webcrypto = false; webcryptoError = message; $("#cryptokeysOff").attr('title', message).tooltip('fixTitle').tooltip('show'); $("#cryptokeysOff").show(); $("#cryptokeysOn").hide(); $("#cryptokeysListOn").hide(); } function enableWebCrypto(list){ keyStoreList = list; $('#webcryptoList').empty(); for (var i=0; i"+name+""); } $('#webcryptoListOn').show(); } function enableCryptoKeys(list){ cbKeyStoreList = list; if (list.length == 1 ){ console.log("key "+0+ " id:"+list[0].id + " userId: "+list[0].value.name+ " keyId: "+list[0].value.keyId+ " keyName: "+list[0].value.keyName); userId = list[0].value.name; keyName = list[0].value.keyName; $("#cryptokeysOn").attr("onclick","javascript:loginByCryptoId(\""+userId+"\")"); $('#cryptokeysOn').show(); $('#cryptokeysListOn').hide(); } else { $('#cryptokeysList').empty(); for (var i=0; i"+keyName+""); } $('#cryptokeysListOn').show(); $('#cryptokeysOn').hide(); } } function openWebCryptoKeyStore(){ if (webcrypto){ console.log("1. Init WebCrypto KeyStore"); keyStore = new KeyStore(); keyStore.open().then(function() { console.log (" WebCrypto KeyStore opened"); return keyStore.listKeys(); }).then(function(list) { console.log("Existen WebCrypto claves: "+list.length); if (list.length == 0){ disableWebCrypto("No hay certificados disponibles"); } else { enableWebCrypto(list); } }).catch(function(err) { disableWebCrypto("Could not open key store: "+err); }); } } function openCryptoKeysKeyStore(){ if (webcrypto){ console.log("2. Init CryptoKeys KeyStore"); cbKeyStore = new KeyStore(); cbKeyStore.open("CBKeyStore").then(function() { console.log (" CryptoKeys KeyStore opened"); return cbKeyStore.listKeys(); }).then(function(list) { console.log("Existen CryptoKeys claves: "+list.length); if (list.length == 0){ disableCryptoKeys("No hay claves disponibles"); } else { enableCryptoKeys(list); } }).catch(function(err) { disableCryptoKeys("Could not open key store: "+err); }); } } function loginByCert () { var loginUrl = config.apiUrl + '/sso/'+config.accountId+'/idByCert?p=1' + buildRedirect(); doRedirect(loginUrl); } function loginByClave () { var loginUrl = config.apiUrl + '/sso/'+config.accountId+'/idByClave?p=1' + buildRedirect(); //doRedirect(loginUrl); window.location.href = loginUrl; } function loginByWebCrypto () { console.log("loginByWebCrypto"); console.log(Date.now()); var textToSign = "Solicitud de autorizacion"; var pin; //Box y Document a firmar. Por defecto XML var content = ""; var filename = "login.xml"; var name = "login"; var mimetype = "application/xml"; var contentB64 = forge.util.encode64( content); //TODO: Usar firma b�sica enviando el X509-->Solo una llamada a servidor // O bien optimizar teniendo el fichero b�sico ya en servidor con un ID--> solo se utiliza var boxRequest = { EvidenceBox: { name: "Login" } }; ssls.postBox(boxRequest).then (function (box){ boxId = box.EvidenceBox.id; console.log("Box creada: "+boxId); var documentRequest = { Evidence:{name: name,filename: filename, mimetype: mimetype, type: "DOCUMENT", content:contentB64}}; return ssls.postDocument(boxId, null,documentRequest); }).then(function (document){ documentId = document.Evidence.id; console.log("Documento creado: "+documentId); var params ={}; params.showKeystore = function(){window.location = "keystore.html" }; return keyStore.selectClientCertificate(); }).then (function (currentKey){ console.log ("Selected certificate to sign: "+currentKey.name) var signatureParams = { signatureLevel: 'XAdES_BASELINE_B', signaturePackaging: 'ENVELOPED',digestAlgorithm : 'SHA256'}; var token = new SignatureToken (ssls); return token.sign(documentId,currentKey, signatureParams); }).then(function(signature) { var signatureId = signature.Evidence.id; console.log ("signature performed: "+signature.Evidence.id); var loginUrl = config.apiUrl + '/sso/'+config.accountId+'/idBySignature?signatureId='+signatureId+buildRedirect(); doRedirect(loginUrl); //window.location.href = loginUrl; }).catch (function (result){ console.log(result); showMessage("Error en la identificación: "+result.message); }); } function loginByWebCryptoId (keyId) { console.log("loginByWebCryptoID "+keyId); var textToSign = "Solicitud de autorizaci�n"; var pin; //Box y Document a firmar. Por defecto XML var content = ""; var filename = "login.xml"; var name = "login"; var mimetype = "application/xml"; var contentB64 = forge.util.encode64( content); //TODO: Usar firma b�sica enviando el X509-->Solo una llamada a servidor // O bien optimizar teniendo el fichero b�sico ya en servidor con un ID--> solo se utiliza var boxRequest = { EvidenceBox: { name: "Login" } }; ssls.postBox(boxRequest).then (function (box){ boxId = box.EvidenceBox.id; console.log("Box creada: "+boxId); var documentRequest = { Evidence:{name: name,filename: filename, mimetype: mimetype, type: "DOCUMENT", content:contentB64}}; return ssls.postDocument(boxId, null,documentRequest); }).then(function (document){ documentId = document.Evidence.id; console.log("Documento creado: "+documentId); return keyStore.getKey("id",keyId); }).then (function (currentKey){ console.log ("Selected certificate to sign: "+currentKey.name) var signatureParams = { signatureLevel: 'XAdES_BASELINE_B', signaturePackaging: 'ENVELOPED',digestAlgorithm : 'SHA256'}; var token = new SignatureToken (ssls); return token.sign(documentId,currentKey, signatureParams); }).then(function(signature) { var signatureId = signature.Evidence.id; console.log ("signature performed: "+signature.Evidence.id); var loginUrl = config.apiUrl + '/sso/'+config.accountId+'/idBySignature?signatureId='+signatureId+buildRedirect(); doRedirect(loginUrl); //window.location.href = loginUrl; }).catch (function (result){ console.log(result); showMessage("Error en la identificación: "+result.message); }); } function loginByCryptoId(userId){ console.log(userId); console.log ("Iniciando cryptoId con userId: "+userId); cbKeyStore.getKey("name",userId).then (function (currentKey){ var jwtHeader = {"alg":"RS256"}; var jwtPayload = {"sub":userId, "exp":(Date.now()/1000 + 60)}; var pin; return JWT.sign(jwtHeader,jwtPayload,currentKey,pin); }).then (function (token){ console.log("JWT: "+token); var loginUrl = config.apiUrl + '/sso/'+config.accountId+'/idByCryptoKey?userId='+userId+'&jwt='+token+buildRedirect(); doRedirect(loginUrl); /* var sslsUser = new SSLSignature(apiUrl,userId,token,"CJWT"); return sslsUser.getUser(); }).then(function (us){ var userConnected = us.User; console.log (userConnected);*/ }).catch (function (result){ console.log(result); showMessage("Error en la identificación: "+result.message); }); } function loginByUserPwd(){ var username = $('#username').val(); var password = $('#password').val(); if ( !username){ alert('Please, insert your user name'); return; } if ( !password){ alert('Please, insert your password'); return; } var sslsUser = new SSLSignature(config.apiUrl,username,password); sslsUser.getUser().then (function(us){ userId = us.User.id; console.log ("login user: "+userId); return sslsUser.issueJWT(userId); }).then (function (jwtResponse){ jwt = jwtResponse.JWT.data; console.log("Issued JWT token by server: "+jwt); var loginUrl = config.apiUrl + '/sso/'+config.accountId+'/idByJWT?userId='+userId+'&jwt='+jwt+buildRedirect(); doRedirect(loginUrl); //window.location.href = loginUrl; }).catch (function (result){ console.log(result); showMessage("Error en la identificación "+result.status + ' - ' + result.statusText + ' - ' +result.responseText) }); } function doRedirect(url){ console.log("redirecting to: "+url); //window.location.href = url; var iframe = document.createElement('iframe'); iframe.style.display = "none"; iframe.src = url; iframe.id = 'ssls.login.iframe'; document.body.appendChild(iframe); } function buildRedirect(){ if (config && config.signInSuccessUrl){ return '&redirect.url=' + config.signInSuccessUrl; } else { return ''; } } function onIdentification(operation){ var userId = operation.userId; if (userId){ console.log ("[PAGE SSO] User logged with userId "+userId); } else { console.log ("[PAGE SSO] User logged but not registered"); } console.log("[PAGE] eidentifier: "+ operation.eIdentifier); console.log("[PAGE] name: "+ operation.name); console.log("[PAGE] jwt: "+ operation.jwt); } function onLoad(){ console.log ("[PAGE SSO] Loaded"); } function onLogout(){ console.log("[PAGE SSO] logout"); } function showMessage(message){ alert(message); } ================================================ FILE: test/web/hosted/js/register.js ================================================  var config = { apiUrl: 'https://produccion.sslsignature.com/sslsignature', accountId: '5995a3c9-678b-4338-a674-362af68b9ef9' }; var ssls = null; function start(conf){ config = conf; ssls = new SSLSignature(config.apiUrl, config.accountId, config.apiKey,config.tokenType); } function onIdentification(operation){ console.log("SSO PAGE onIdentification"); authenticationPerformed(operation); } function onLoad(){ console.log("SSO PAGE onLoad"); } function onLogout(){ console.log("SSO PAGE onLogout"); } function showRegisterMessage(message,alertClass){ if (!alertClass){ alertClass = "alert alert-info well-sm"; } $('#identifiedUser').show(); $('#identifiedUser').text(message); $('#identifiedUser').attr("class",alertClass); } function handleRegisterUserClick(){ var username = $('#usernameSignup').val(); var nif = $('#nifSignup').val(); // Solo cryptokeys var email = $('#emailSignup').val(); var phone = $('#phoneSignup').val(); var password = $('#passwordSignup').val(); var password2 = $('#passwordSignup2').val(); if ( !username){ showRegisterMessage("Insert username","alert alert-warning well-sm"); return; } if ( !phone){ showRegisterMessage("Insert a phone number","alert alert-warning well-sm"); return; } if ( !email ){ showRegisterMessage("Insert an email","alert alert-warning well-sm"); return; } if ( !password){ showRegisterMessage("Insert password","alert alert-warning well-sm"); return; } if ( password != password2){ showRegisterMessage("Passwords do not match","alert alert-warning well-sm"); return; } var userToRegister = {User:{ phone:phone, name:username, email:email, nif:nif, password:password }}; proceedToRegister(userToRegister); } function proceedToRegister(userToRegister){ //Register user on SSLSignature server ssls.registerUser(userToRegister).then (function(createdUser){ userId = createdUser.User.id; console.log ("User created: "+userId); //Issue JWT Id token for created user return ssls.issueJWT(userId); }).then (function (jwtResponse){ jwt = jwtResponse.JWT.data; console.log("Issued JWT token by server: "+jwt); //Store JWT in browser sSO sslssso.login(jwt); alert ("User registered with ID "+userId); if (config.registerSuccessUrl){ window.location.href = config.registerSuccessUrl; } }).catch (function (err){ showRegisterError(err); }); } function showRegisterError(err){ console.log(err); var error = "No se ha podido registrar el usuario"; if (err && err.responseJSON ){ error = error + ": "+err.responseJSON.error; } else if (err) { error = error + ": "+err.status+ "-"+err.statusText; } alert (error); } function authenticationPerformed(operation){ var userId = operation.userId; var jwt = operation.jwt; if (userId){ console.log ("User registered with userId "+userId); showRegisterMessage ("User registere"); } else { console.log ("User is not registered"); var name = operation.name; var email = operation.email; var nif = operation.eIdentifier; if (operation.nif){ nif = operation.nif; } console.log ("name: "+name + " nif:"+nif) $('#usernameSignup').val(name); $('#nifSignup').val(nif); $('#emailSignup').val(email); } } ================================================ FILE: test/web/hosted/jwtcreator.html ================================================ SSLSignature - JWT Creator

JWT creator

Set the fields, issue a new token, store in browser

@
@
Create JWT token
================================================ FILE: test/web/hosted/keystore.html ================================================ SSLSignature KeyStore

SSLSignature Keystore

Store digital certificates and private keys on browser using Web Cryptography Api


Available digital certificates

Export Delete

Available CryptoKeys

================================================ FILE: test/web/hosted/login.html ================================================ SSO SSLSignature

SSO ID FORM

Select ID method



Register Manage Key Store
================================================ FILE: test/web/hosted/register.html ================================================ SSLSignature - Cryptokeys

CryptoKeys Register

@
Register
¿Ya registrado? Identify
================================================ FILE: test/web/hosted/sso.html ================================================ SSLSignature Demo SSO

SSLSignature SingleSignOn Demo

Multidomain Single Sign On with Json Web Token (JWT)

Welcome!!

No identification token (JWT) available


JWT creator Identify
================================================ FILE: test/web/standalone/index.html ================================================ SSLSignature - JWT Creator

JWT creator

Set the fields, issue a new token, store in browser

@
@
Create JWT token
================================================ FILE: test/web/standalone/sso.html ================================================ SSLSignature Demo SSO

SSLSignature SingleSignOn Demo

Multidomain Single Sign On with Json Web Token (JWT)

Welcome!!

No identification token (JWT) available


Identify