Full Code of Aralink/ssojwt for AI

master e47856e5594f cached
35 files
181.2 KB
47.6k tokens
193 symbols
1 requests
Download .txt
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. <http://fsf.org/>
 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 <http://www.gnu.org/licenses/>.

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
<http://www.gnu.org/licenses/>.

  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
<http://www.gnu.org/philosophy/why-not-lgpl.html>.


================================================
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 `<meta>` field to indicate the sslsignature accountId
```
<meta name="ssls.accountId" content="5995a3c9-678b-4338-a674-362af68b9ef9" />
```
Include javascript
```
<script src="https://produccion.sslsignature.com/sso/resources/js/sslssso.js"></script>
```
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
```
<script src="{yourserver.com}/{ssopath}/js/sslssso.js"></script>
```
or use hosted
```
<script src="https://produccion.sslsignature.com/sso/resources/js/sslssso.js"></script>
```
### 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 <meta> tags of the page or using javascript. The accountId will reference the identifier that will take the token in the local storage.
```
<meta name="ssls.accountId" content="myTokenId" />
<meta name="ssls.validationUrl" content="{yourserver.com}/{ssoValidationUri}" />
<meta name="ssls.validate" content="true"/>
<script src="https://produccion.sslsignature.com/sso/resources/js/sslssso.js"></script>

//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 `<meta name="ssls.validationUrl">` (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<String,String> params = new HashMap<String,String>();
	
	/**
	 * 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
================================================
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
  <display-name>SSLSIGNATURE {env.SVN_REVISION} </display-name>
  <session-config>
    <session-timeout>300</session-timeout>
  </session-config>
 
  <servlet>
	<servlet-name>jwt</servlet-name>
	<servlet-class>com.aralink.sslsignature.sso.jwt.JWTServlet</servlet-class>
	<init-param>
            <param-name>keyFile</param-name>
            <param-value>jwt.hmac</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
	<servlet-name>jwt</servlet-name>
	<url-pattern>/jwt</url-pattern>
  </servlet-mapping>
</web-app>

================================================
FILE: build/build.xml
================================================
<?xml version="1.0" encoding="UTF-8" ?>
<project name="SSO SSLSignature GIT" default="" basedir=".." xmlns:ivy="antlib:org.apache.ivy.ant">
    
    <property name="version" value="1.0.0" />
    <property name="builddir" value="${basedir}/build" />
    <property name="buildlibdir" value="${basedir}/backend/build-lib" />
	<property name="libdir" value="${builddir}/lib" />
	<property name="compilation" value="${builddir}/bin" />
	<property name="distdir" value="${basedir}/dist" />
	
	<property name="jssource" value="${basedir}/client" />
	<property name="javasource" value="${basedir}/backend/src/java" />
	<property name="websource" value="${basedir}/backend/src/web" />
	<property name="testsource" value="${basedir}/test/web" />
        
	<property name="ivy.dep.file" value="${builddir}/ivy.xml" />
	<target name="RESOLVE" description="retrieve dependencies with ivy" >
		<ivy:retrieve pattern="${libdir}/[artifact].[ext]" />
	</target>
	
	
	
	<target name="init">
		<mkdir dir="${builddir}" />
		<mkdir dir="${libdir}" />
		<delete dir="${compilation}" />
		<mkdir dir="${compilation}" />		
	</target>
	
	<target name="backend" description="" depends="init">
	    <path id="libraries">
			<fileset dir="${libdir}" includes="*.jar" />	
			<fileset dir="${buildlibdir}" includes="*.jar" />							
		</path>
	    <javac destdir="${compilation}" classpathref="libraries" source="1.5" target="1.5" debug="on" includeantruntime="true">
			<src path="${javasource}" />
		</javac>
				
		<war destfile="${builddir}/sso.war" webxml="${websource}/WEB-INF/web.xml" update="true">
			<fileset dir="${jssource}" />
		    <fileset dir="${websource}" />
			<fileset dir="${testsource}" />			
			<classes dir="${compilation}" />
			<lib dir="${libdir}" includes="**" />
		</war>
	</target>
	
</project>

================================================
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
================================================
<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. 
	See the NOTICE file distributed with this work for additional information regarding copyright ownership. 
	The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not 
	use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 
	Unless required by applicable law or agreed to in writing, software distributed under the License is 
	distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
	See the License for the specific language governing permissions and limitations under the License. -->
<ivy-module version="2.0">
	<info organisation="com.aralink" module="sslssso" />
	<dependencies>
		<dependency org="io.jsonwebtoken" name="jjwt" rev="0.6.0" conf="default"/>
	</dependencies>
</ivy-module>


================================================
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
================================================
<!DOCTYPE HTML>
<html>
	<head>
		<title>SSLSignature SSO IFRAME</title>
		<!-- <script src="../js/jquery-1.7.1.min.js"></script> -->
		<script src="sso_common.js"></script>
		<script src="sso_rest.js"></script>
		<script src="sso.js"></script>
		<script>
			//GET your params from sslssso.js config or generate this page dynamically on server
			
			var accountId = getGetParam("accountId");
			var domain = getGetParam("domain");
			var validationUrl = getGetParam("validationUrl");
			var validate = !(getGetParam("validate") == 'false'); 
			if (validate && !validationUrl)
				validationUrl = getOrigin() + '/sslsignature/sso/' + accountId + '/jwt';
			
			
			var config = {
				validationUrl: validationUrl,
                accountId: accountId,
                apiKey: '',
                domain: domain,
                tokenId: 'ssls.sso.jwt.' + accountId,
                validate: validate
			}    
			init(config);
			
		</script>
	</head>
</html>

================================================
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<e.length){n=e.charCodeAt(f++);r=e.charCodeAt(f++);i=e.charCodeAt(f++);s=n>>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<e.length){s=this._keyStr.indexOf(e.charAt(f++));o=this._keyStr.indexOf(e.charAt(f++));u=this._keyStr.indexOf(e.charAt(f++));a=this._keyStr.indexOf(e.charAt(f++));n=s<<2|o>>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;n<e.length;n++){var r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r)}else if(r>127&&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(n<e.length){r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r);n++}else if(r>191&&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<metas.length; i++) { 
		     if (metas[i].getAttribute("name") == name) { 
		        return metas[i].getAttribute("content"); 
		     } 
		}
		return null;
	}	
	
	function _getAccountId() { 
		if (config.accountId){
			return config.accountId;
		} else if (_getMeta("ssls.accountId")){
			return _getMeta("ssls.accountId");
		} else if (typeof ssls_accountId !== 'undefined' && ssls_accountId) {
		   return ssls_accountId;
		}	
		
	    return null;
	}
	function _getValidationUrl() { 
		if (config.validationUrl){
			return config.validationUrl;
		} else if (_getMeta("ssls.validationUrl")){
			return _getMeta("ssls.validationUrl");
		} else if (typeof ssls_validationUrl !== 'undefined' && ssls_validationUrl) {
		   return ssls_validationUrl;
		}
		
	    return null;
	}
	
	function _getValidate() { 
		if (config.validate){
			return config.validate;
		} else if (_getMeta("ssls.validate")){
			return _getMeta("ssls.validate");
		} 
		
	    return null;
	}
    
	 var _getScriptURL = (function() {
	        var scripts = document.getElementsByTagName('script');
	        var index = scripts.length - 1;
	        var myScript = scripts[index];
	        return function() { return myScript.src; };
	 })();
	 
	
	function _getIframeUrl(){
		var parser = document.createElement('a');
    	parser.href = _getScriptURL();   	

    	var pathname = parser.pathname.substring(0, parser.pathname.lastIndexOf("/"));
    	var url = parser.protocol + "//"+ parser.host + "/" + pathname + "/" + DEFAULT_IFRAME_URI;
    	
    	var origin = document.location.origin;
    	var accountId = _getAccountId();
    	var validationUrl = _getValidationUrl();
    	var validate = _getValidate();
    	
    	url = url + "?domain="+origin;
    	if (accountId){
    		url = url + "&accountId="+accountId;
    	}
    	
    	if (validationUrl){
    		url = url + "&validationUrl="+validationUrl;
    	}
    	
    	if (validate != null){
    		url = url + "&validate="+validate;
    	}
    	return url;
	}	
	
    function _getUrl(){
    	
    	//https://gist.github.com/jlong/2428561
    	var parser = document.createElement('a');
    	parser.href = _getScriptURL();
    	return parser.protocol + "//"+ parser.host

       /*
    	var metas = document.getElementsByTagName('meta'); 
    	
 	   for (var i=0; i<metas.length; i++) { 
 		  
 	      if (metas[i].getAttribute("name") == "ssls.url") { 
 	         return metas[i].getAttribute("content"); 
 	      } 
 	   }
 	  if (typeof ssls_url !== 'undefined' && ssls_url) {
		   return ssls_url;
	  }
 	  return DEFAULT_URL;
 	  */
    }
    
    function postSSOMessage(message,domain){
    	var win = document.getElementById("ssls.sso.iframe").contentWindow;
    	console.log("[SSLS SSO] postMessage "+message.action+" to "+_getUrl());
    	if (window.attachEvent) {   // IE before version 9
			//TODO No acaba de funcionar en ie8
  			win.postMessage(JSON.stringify(message), "*");	
		} else {
			win.postMessage(message, _getUrl());
		}
    }
    
    function dispatchEvent(eventName, detail){
    	console.log ("[SSLS SSO] dispatchEvent "+eventName);
    	obs.fireEvent(eventName, detail);
    }

	function _listener(event){
		
		if (  _getUrl().lastIndexOf(event.origin ) == -1){
			return;
		}

		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 && data .action == "sso.onlogout"){
			console.log("[SSLS SSO] received event onlogout");
			if (typeof(onLogout) == "function")
				onLogout();
			dispatchEvent('sso.onlogout'); 
		} else if (data && data.action == "sso.onload") {
			console.log("[SSLS SSO] received event onload ");
			if (typeof(onLoad) == "function")
				onLoad();
			dispatchEvent('sso.onload'); 
			
		}else if (data && data.action == "sso.onidentification") {
			console.log("[SSLS SSO] received event onidentification ");
			if (typeof(onIdentification) == "function")
				onIdentification(data);
			dispatchEvent('sso.onidentification',data);
		}	
	}
	
	
	
	function _init(){
		
		
		var accountId = _getAccountId();
		console.log ("[SSLS SSO] accountId = "+accountId + " SSOServerUrl= " +_getUrl());
		
		//Message listener for SSO events (created by the SSO iframe)
		if (window.addEventListener){
			addEventListener("message", _listener, false)
		} else {
			attachEvent("onmessage", _listener)
		}
					
		//Creates the iframe with reference to server SSO functions
		var iframeUrl = _getIframeUrl()
		console.log ("[SSLS SSO] create iframe: "+ iframeUrl);
	    var iframe = document.createElement('iframe');
		iframe.style.display = "none";
		iframe.src = iframeUrl;
		iframe.id = 'ssls.sso.iframe';
		document.body.appendChild(iframe);
	}
	
	function init(conf){
		if (conf){
			config = conf;
		}	
	}
	
	if (window.addEventListener) {
		// W3C standard
	  window.addEventListener('load', _init, false); // NB **not** 'onload'
	} else if (window.attachEvent){
		 // Microsoft
	  window.attachEvent('onload', _init);
	}

}	
	
	






================================================
FILE: test/java/com/aralink/sslsignature/sso/jwt/test/JWTTest.java
================================================
package com.aralink.sslsignature.sso.jwt.test;


import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.impl.crypto.MacProvider;

import java.security.Key;
import java.util.HashMap;
import java.util.Map;







import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import com.aralink.sslsignature.sso.jwt.JWTManager;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;


public class JWTTest {
	RestClient client;
	
	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
	}

	@AfterClass
	public static void tearDownAfterClass() throws Exception {

	}

	@Before
	public void setUp() throws Exception {
		client = new RestClient("https://pfb.sslsignature.com");
	}

	@After
	public void tearDown() throws Exception {
	}


	@Test
	public void issueAndValidateJWT() throws Exception {
		Map<String,String> jwtInfo = new HashMap<String,String>();
		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<String,String> jwtValidationInfo = new HashMap<String,String>();
		jwtValidationInfo.put("jwt", jwt);
		String authenticationResponseJson = client.postForm("/sso/jwt", jwtValidationInfo);
		SimpleConsoleLogger.info(authenticationResponseJson);
		
		//JWT token validated on server to Java Object 
		Map<String, Object> map = new HashMap<String, Object>();
		ObjectMapper mapper = new ObjectMapper();
		map = mapper.readValue(authenticationResponseJson, new TypeReference<Map<String, String>>(){});
		
		SimpleConsoleLogger.info("STATUS: "+map.get("status")+ " eidentifier"+ map.get("eidentifier"));
		
		Assert.assertEquals("SUCCESS", map.get("status"));
				
	}
	
	@Test
	public void alteredJWT() throws Exception {
		Map<String,String> jwtInfo = new HashMap<String,String>();
		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<String,String> jwtValidationInfo = new HashMap<String,String>();
		jwtValidationInfo.put("jwt", jwt);
		String authenticationResponseJson = client.postForm("/sso/jwt", jwtValidationInfo);
		SimpleConsoleLogger.info(authenticationResponseJson);
		
		//JWT token validated on server to Java Object 
		Map<String, Object> map = new HashMap<String, Object>();
		ObjectMapper mapper = new ObjectMapper();
		map = mapper.readValue(authenticationResponseJson, new TypeReference<Map<String, String>>(){});
		
		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<String,String> jwtValidationInfo = new HashMap<String,String>();
		jwtValidationInfo.put("jwt", jwt);
		String authenticationResponseJson = client.postForm("/sso/jwt", jwtValidationInfo);
		SimpleConsoleLogger.info(authenticationResponseJson);
		
		
		//JWT token validated on server to Java Object 
		Map<String, Object> map = new HashMap<String, Object>();
		ObjectMapper mapper = new ObjectMapper();
		map = mapper.readValue(authenticationResponseJson, new TypeReference<Map<String, String>>(){});
		
		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<String, String> 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<String,String> 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
================================================
<!DOCTYPE HTML>

<html>
	<head>
		<title>SSLSignature - CryptoKeys</title>
		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
		<meta name="description" content="" />
		<meta name="keywords" content="" />
		<META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">
		<link rel="icon" href="img/favicon.ico">
		<meta name="ssls.accountId" content="5995a3c9-678b-4338-a674-362af68b9ef9" />
		<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
		
		
	</head>
	<body>
		<div id="notIdentified" class="container" hidden>
			<h2>Welcome</h2>
			<p>You do not have an authentication token</p>
			<a type="button" class="btn btn-success" aria-label="Left Align" href="register.html"> Register </a>
			<a type="button" class="btn btn-default" aria-label="Left Align" href="login.html"> Identify</a>
		</div>	
		
		<div id="identified" class="container" hidden>
			<h2 id="identifiedTitle">Identificación realizada</h2>
			<section id="identificationInfo" ></section>
			<div id="idOk" class="row">
				<hr/>
				<p>User not registered in CryptoKeys</p>
				<a type="button" class="btn btn-success" aria-label="Left Align" href="register.html">  Register  </a>
				<button type="button" class="btn btn-danger" aria-label="Left Align" onclick="handleLogoutClick();"><span class="glyphicon glyphicon-off" aria-hidden="true"></span> Logout</button>
			</div>
			<div id="idFailed" class="row">
				<hr/>
				<p>You do not have an authentication token</p>
				<a type="button" class="btn btn-success" aria-label="Left Align" href="register.html">  Register  </a>
				<a type="button" class="btn btn-default" aria-label="Left Align" href="login.html"> Identify</a>
			</div>
		</div>	
		
		
		<section id="logged" hidden>
			<div class="container" >
				<h2 id="pageTitle">Identification performed</h2>
				<button type="button" class="btn btn-danger" aria-label="Left Align" onclick="handleLogoutClick();"><span class="glyphicon glyphicon-off" aria-hidden="true"></span> Logout</button>
			</div>
				
			<div  id = "newDevice" class="container" hidden>
				<h3>CryptoKeys not enabled</h3>
				<p>It is the first time you connect with this device, to enable CryptoKeys an additional identification is required. Below you will create your security private key </p>
				<section id="newDeviceSend" hidden>
					<p>Enter the 4-digit code that is sent to your mobile phone</p>
					<div class='row'>
						<div class='col-md-2'>
							<div class="form-group input-group">
                            	<span class="input-group-addon"><i class="glyphicon glyphicon-phone-alt"  ></i></span>
                            	<input type="text" name="otp" id="otp" value=""  class="form-control" placeholder="OTP" />
	                        </div>
	                    </div>    
	                    <div class='col-md-1'>
	                    	<button type="button" id="sendOtp" class="btn btn-primary" aria-label="Left Align" onclick="handleEnrollClick()"> Send </button>
						</div>										
					</div>	
				</section>
				<section id="newDeviceError" hidden>
				 	<div id="newDeviceErrorMessage" class="alert alert-warning" role="alert">Invalid identification</div>
					<a href="javascript:handleResendClick()" id="resendOtp" class="btn btn-primary" >Enable CryptoKeys</a>
				</section>
			</div>
			
			<div id ="registeredDevice" class="container" hidden>
				<hr/>
				<h3>Device registered</h3>
				<p>Your current browser has a security key. </p>
				<table id="theDeviceList" class="table table-striped">
					<thead>
						<tr>
							<th><a href="javascript:handleRefreshDevicesClick()"><span class="glyphicon glyphicon-refresh" aria-hidden="true"></span> Dispositivos habilitados</a></th>
							
							<th>Private</th>
							<th>Type</th>
							<th>Enabled</th>
						</tr>
					</thead>
					<tbody>
					</tbody>
				</table>
				
				
				<div class="checkbox">
				    <label>
				      <input type="checkbox" id="showOnlyActive" name="showOnlyActive" checked> Show only enabled keys
				    </label>
				 </div>
				<div class="row">
					<section id="checkRegisterMessage"></section>
				</div>
				<hr/>
				<h3>Link mobile</h3>
				<p>You can link mobile devices to perform operations with double safety factor. Download the app (android) first</p>
				<p>
					<a href="javascript:handleRegisterDeviceClick()" id="registerDeviceKey" class="btn btn-success" >Link</a>
					<span class="image"> <a href="javascript:handleDownloadAppClick()"><img src="img/android2.png" height="32" alt="Download app"/></a></span>
				</p>
			</div>
			<div id="dialogQr"></div>
			
			<div class="container" id = "signedTransaction" hidden>
				<hr/>
				<h3>Use your key on a transaction</h3>
				<p>The transaction is signed with your private key and validated by the public. Only an authorized device can perform operations. In operations with double safety factor you will need a connected mobile device. An authorization request will be sent to the device</p>
				<section id="checkResultMessage"></section>
								
				<p>
					<a href="javascript:handleExecuteSignedTransactionClick()" id="sendTransaction" class="btn btn-primary" >Level 1 : WebCrypto</a>
					<a href="javascript:handleExecuteSignedTransactionDoubleFactorClick()" id="sendTransactionDoubleFactor" class="btn btn-primary" >Level 2: Double Factor</a>
					<a href="javascript:handleAbortClick()" id="abortButton" class="btn btn-danger" hidden>Abort</a>
				</p>
				
			</div>					
			
		</section>
		
		<div class="modal fade" id="downloadAndroidDialog" tabindex="-1" role="dialog">
		  <div class="modal-dialog">
		    <div class="modal-content">
		      <div class="modal-header">
		        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
		        <h4 class="modal-title">Download for Android</h4>
		      </div>
		      <div class="modal-body">
		        <p>Scan QR with your device</p>
		        <img src="#" width="500" id="qrimage"  alt="Descargar aplicación">
				
		      </div>
		      <div class="modal-footer">
		        
		        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
		      </div>
		    </div>
		  </div>
		</div>
		<div class="modal fade" id="registerDeviceDialog" tabindex="-1" role="dialog">
		  <div class="modal-dialog">
		    <div class="modal-content">
		      <div class="modal-header">
		        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
		        <h4 class="modal-title">Register new device</h4>
		      </div>
		      <div class="modal-body">
		        <p>Scan QR with your device</p>
		        <img src="#" width="500" id="qrdevice"  alt="Vincular dispositivo">
				
		      </div>
		      <div class="modal-footer">
		        
		        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
		      </div>
		    </div>
		  </div>
		</div>
		
		
		<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
	    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
   		 <!--SSO--><script src="https://produccion.sslsignature.com/sslsignature/resources/js/sslssso.js"></script><!--SSO-->
	    <script src="https://produccion.sslsignature.com/sslsignature/resources/js/es6-promise.min.js"></script>
	    <script src="https://produccion.sslsignature.com/sslsignature/resources/js/forge.min.js"></script>
	    <script src="https://produccion.sslsignature.com/sslsignature/resources/js/ssls.min.js"></script>
	    <script src="js/index.js"></script>
	    <script src="js/config.js"></script>
	    <script>
	    	start (config);
    	</script>
	</body>
</html>

================================================
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 = "<img src='img/checkmark.png'/>";
			status = "ID successful";
			alertClass = "alert alert-success well-sm";
		}else if  (status == "FAIL"){
			image = "<img src='img/no_entry.png'/>";
			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 = 
			 "        <ul>"
			 +"          <li>ID: "+idInfo+"</li>"
		 	 +"          <li>"+nameInfo+"</li>"
		 	 +"          <li>"+jwtInfo+"</li>"
		 	 +"       </ul>";

		var section = "<div class='row'>"
						 +"   <div class='col-md-2'>"
						 +"      <span class='image'>"+image+"</span>"
						 +"    </div>"
						 +"    <div class='col-md-10'>"
						 +"      <h4>"+status+"</h4>"
						 +       infoSection
						 + "   </div>"
						 + "</div>";
		
		var text = $("<section id='identificationInfo'>"+section+"</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 <br/>";

		var st = new SignatureToken();
    	st.webcryptosign(textToSign,currentKey,pin).then (function (signature){
    		message = message + "2. Sending signature to server<br/>";
    		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 = "<div id='checkResultMessage' class='alert "+alertType+"' role='alert'>"+mensaje+"</div>";
		$('#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<list.DeviceKey.length; i++) {
	       		addToDeviceList (list.DeviceKey[i]);
	        }
	   	}).catch(function(err) {
	   		if (err.status!= 404)
	   			callFailed(err);
	    });
	 }
		
	function addToDeviceList(key){
		var id = key.id;
		var name = key.deviceDescription
		var actual = "";
		var deleteAction ="";
		var showOnlyActive = $('#showOnlyActive').is(':checked');

		console.log("add key to list id:"+id +  " name: "+name+ " revoked:"+key.revoked);
		//var keyStatus = "SI";
		//if (key.revoked)
		//	keyStatus = "Revocada";
		var keyStatus = "<img src='img/checkmark.png' alt='Clave activa' title='Clave activa' height='32'/>";
		if (key.revoked)
			keyStatus = "<img src='img/no_entry.png' alt='Clave revocada' title='Clave revocada' height='32'/>";
		
		var keyEngine = "<img src='img/w3c-icon.png' alt='WEBCRYPTO' title='WEBCRYPTO' height='32'/>";
		if (key.engine == 'ANDROID')
			keyEngine = "<img src='img/android-icon.png' alt='ANDROID' title='ANDROID' height='32'/>";
		else if (key.engine == 'IOS')
			keyEngine = "<img src='img/ios-icon.png' alt='ANDROID' title='ANDROID' height='32'/>";		
				
		
		if (currentKey && currentKey.keyId == key.id){
			name = name+ " [ACTUAL]";
			actual = "<img src='img/key-icon.png' alt='Clave privada' title='Private key' height='32'/>";
			//deleteAction = "	<li><a href='javascript:doDeleteKey()'>Eliminar del navegador</a></li>";
			deleteAction="doDeleteKey()";
		} else {
			deleteAction ="doRevokeKey(\""+id+"\")";
		}
		
		
		
		var keyActions = "<button type='button' class='btn btn-default' onclick="+deleteAction+" >"
			+"<span class='glyphicon glyphicon-trash' ></span> " 
			+  "</button>";
		
		if (key.revoked){
			keyActions = "";
		}
		
		  
		var tableElement = "<tr>"
		//	+ "<td><input type='radio' name='key' value='"+id+"' id='"+id+"'><label for='"+id+"'>"+name+"</label></td>"
			+ "<td>"+name+"</td>"
			+ "<td>"+actual+"</td>"
			+ "<td>"+keyEngine+"</td>"
			+ "<td>"+keyStatus+"</td>"
			+ "<td>"+keyActions+"</td>"
			+"</tr>";
		
		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 = "<div id='checkResultMessage' class='alert alert-info' role='alert'>"
				 + message
				 + "<a href='"+link+"'  class='btn btn-default' target='_blank'>CryptoKeys app</a>"
				 +	"</div>";
			$('#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 = "<div id='checkResultMessage' class='alert alert-info' role='alert'>"
				 + message
				 + "<a href='"+link+"'  class='btn btn-default' target='_blank'>Cryptokeys app</a>"
				 +	"</div>";
			$('#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 = "<img src='img/yield.png'/>";
			alertType = "alert-warning";
		}else if  (status == "SUCCESS"){
			image = "<img src='img/checkmark.png'/>";
			alertType = "alert-success";
		}else if  (status == "FAIL"){
			image = "<img src='img/no_entry.png'/>";
			alertType = "alert-danger";
		}else{ 
			image = "<img src='img/no_entry.png'/>";
			alertType = "alert-info";
		}	
		
		var section = "<div id='checkResultMessage'  class='alert "+alertType+"' role='alert'><h5>Respuesta obtenida </h5>"+image+"<h5>"+status+"</h5></section>";
		$('#checkResultMessage').replaceWith(section);	
		
		$('#abortButton').hide();
		$('#sendTransactionDoubleFactor').show();	
		//$('#textToSignDoubleFactor').show();	
	}	

	
	
	
	function doAbort(){
		finishAuthorization('CANCEL');
	}
	
	function handleAbortClick(){
		cancelTimer();		
		
		image = "<img src='img/yield.png'/>";
		var section = "<div id='checkResultMessage' class='alert alert-warning' role='alert'><h5>Resultado de la autorización</h5>"+image+"<h5>CANCEL</h5></div>";
		$('#checkResultMessage').replaceWith(section);
		
		$('#abortButton').hide();
		$('#sendTransactionDoubleFactor').show();	
		//$('#textToSignDoubleFactor').show();	
	}
	
	
	function initTimer(){
		timeout = 90;
		intervalId = window.setInterval(runTimer, 1000);
	}
	
	function runTimer(){
		var oElem = document.getElementById("otp");
		
		timeout = timeout - 1;
		$('#abortButton').html("Abortar ("+timeout+")");
		if (timeout < 0){
			$('#abortButton').html("Timeout");
			doAbort();
		} else {	
			//Cada 5 segundos check call status
			if (timeout % 5 == 0)
				checkCallStatus();
		}	
	}
	
	function cancelTimer(){
		clearInterval(intervalId);
	}
	
	/***************
	 * 
	 * Utilities
	 */
	
	function getGetParam (vr){
		var src = window.location.href;
		if (src != null) {
			var vrs = src.split('?');

			for (var x = 0, c = vrs.length; x < c; x++){	
				if (vrs[x].indexOf(vr) != -1){
					return decodeURI( vrs[x].split('=')[1] );
					break;
				};
			};
		}
		else {
			 return "";
		}
	};
	
	function getBrowserInfo(){
	    var ua=navigator.userAgent,tem,M=ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || []; 
	    if(/trident/i.test(M[1])){
	        tem=/\brv[ :]+(\d+)/g.exec(ua) || []; 
	        return {name:'IE',version:(tem[1]||'')};
	        }   
	    if(M[1]==='Chrome'){
	        tem=ua.match(/\bOPR\/(\d+)/)
	        if(tem!=null)   {return {name:'Opera', version:tem[1]};}
	        }   
	    M=M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
	    if((tem=ua.match(/version\/(\d+)/i))!=null) {M.splice(1,1,tem[1]);}
	    return {
	      name: M[0],
	      version: M[1]
	    };
	 }
	
	

================================================
FILE: test/web/hosted/js/jwtcreator.js
================================================

var config;
	
	function start(conf){
		config = conf;
	}
	
	
	
	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 handleCreateJWTClick(){
		
		var params = $('#jwtForm').serialize();
		console.log("POST "+config.url);
		console.log(params);
		$.post(
				config.url, 
				params,
				function(jwt) {
					console.log("JWT: "+jwt);
					//Store JWT in browser SSO
					sslssso.login(jwt);
                });
		
	}	
		
	
	
	

================================================
FILE: test/web/hosted/js/keystore.js
================================================

	var ssls;
	var crypto = window.crypto || window.msCrypto;
	var keyStore;
	var cbKeyStore;
	var webcrypto = true;
	
	$(document).ready(function(){
		configureForm();
		
		checkWebCrypto();
		openWebCryptoKeyStore();
		openCryptoKeysKeyStore();
	    
	});
	
	function configureForm(){
	}
		
	
	function checkWebCrypto(){
		if (window.crypto && !window.crypto.subtle && window.crypto.webkitSubtle) {
	        window.crypto.subtle = window.crypto.webkitSubtle;
	    }
		if (!window.crypto &&  window.msCrypto){
			window.crypto = window.msCrypto;
		}
		
		if (!window.crypto || !window.crypto.subtle) {
			disableWebCrypto("Web Cryptographi API no soportada!");
	    }
	    
	    if (!window.indexedDB) {
			disableWebCrypto("IndexedDB no soportada!");
	    } 
	}
	
	function disableWebCrypto(message){
		webcrypto = false;
		$("#webcryptoAlert").text(message);
		$("#webcryptoAlert").show();
	}
	
	function openWebCryptoKeyStore(){
		if (webcrypto){
			 keyStore = new KeyStore();	
			 keyStore.open().then(function() {
			   	console.log ("KeyStore opened");
			    listKeyStore();
			 }).catch(function(err) {
			    alert("Could not open key store: " + err);
			 });		   
		}
	}
	function openCryptoKeysKeyStore(){
		if (webcrypto){
			 cbKeyStore = new KeyStore();	
			 cbKeyStore.open("CBKeyStore").then(function() {
			   	console.log ("CryptoKeyStore opened");
			    listCryptoKeyStore();
			 }).catch(function(err) {
			    alert("Could not open key store: " + err);
			 });		   
		}
	}
	
		
	function importPkcs12(file,password, extractable){
		console.log("importPkcs12 "+password + " extractable:"+extractable);
		var reader = new FileReader();
		reader.onload = function(e) { 				
			//var mime = convertMimetype(file.type);
			var contents = e.target.result;
			var pkcs12Bin = arrayBufferToString(contents)
			var pkcs12B64 = forge.util.encode64(pkcs12Bin);		
			
			
			keyStore.importKey(pkcs12B64,password,extractable).then(function(savedObject) {
	    		console.log ("Imported key: "+savedObject.name);
	    		$('#importCertificateModal').modal('hide')
	    		listKeyStore();
			}).catch(function(err) {
	            alert("Could not import pcks12: " + err);
	        });
		}	
		reader.readAsArrayBuffer(file);
	}
	
	function listKeyStore(){
		keyStore.listKeys().then(function(list) {
			$( "#keyList" ).empty();
			for (var i=0; i<list.length; i++) {
				$( "#keyList" ).append( 
						addToKeyList (list[i]));
        	}
   		 }).catch(function(err) {
        	alert("Could not list key store: " + err);
    	});
	}
	
	function addToKeyList(keystoreObject){
		var id = keystoreObject.id;
		var savedObject = keystoreObject.value;
		var name = escapeHTML(savedObject.name);
		console.log("add key to list id:"+id +  " name: "+name);
		
		var keyElement = 
			"<div class='radio'>" +
			"<label>"+
			"<input type='radio' name='key' value='"+id+"' id='"+id+"'>"+
		    name+
		    "</label>"+
		    "</div>";
		return keyElement;
		
	}
		
	
	function listCryptoKeyStore(){
		cbKeyStore.listKeys().then(function(list) {
			$( "#cryptoKeyList" ).empty();
			for (var i=0; i<list.length; i++) {
       			$( "#cryptoKeyList" ).append( 
       					addToCryptoKeyList (list[i]));
        	}
   		 }).catch(function(err) {
        	alert("Could not list key store: " + err);
    	});
	}
	
	function addToCryptoKeyList(keystoreObject){
		var id = keystoreObject.id;
		var savedObject = keystoreObject.value;
		var name = escapeHTML(savedObject.keyName);
		console.log("add key to list id:"+id +  " name: "+name);
		
		var keyElement = 
			"<div class='radio'>" +
			"<label>"+
			"<input type='radio' name='cryptokey' value='"+id+"' id='"+id+"'>"+
		    name+
		    "</label>"+
		    "</div>";
		return keyElement;
		
	}
	
	function escapeHTML(s) {
        return s.toString().replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
    }
	
		
	
	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<list.length; i++) {
			console.log("key "+i+ " id:"+list[i].id +  " name: "+list[i].value.name+ " keyId: "+list[i].value.keyId+ " keyName: "+list[i].value.keyName);
			id = list[i].id;
			name = list[i].value.name;
			$("#webcryptoList").append("<li><a href='javascript:loginByWebCryptoId("+id+")'>"+name+"</a></li>");
		}
		$('#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<list.length; i++) {
				console.log("key "+i+ " id:"+list[i].id +  " userId: "+list[i].value.name+ " keyId: "+list[i].value.keyId+ " keyName: "+list[i].value.keyName);
				userId = list[i].value.name;
				keyName = list[i].value.keyName;
				$("#cryptokeysList").append("<li><a href='javascript:loginByCryptoId(\""+userId+"\")'>"+keyName+"</a></li>");
			}
			$('#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 = "<login></login>";
		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 = "<login></login>";
		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
================================================
<!DOCTYPE HTML>

<html>
	<head>
		<title>SSLSignature - JWT Creator</title>
		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
		
		<META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">
		
		<meta name="ssls.accountId" content="5995a3c9-678b-4338-a674-362af68b9ef9" />
		<meta name="ssls.validate" content="false" />
		 
		<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
	</head>
	<body>

		<!-- CTA -->
		<div id="cta" class="container">
			
			<div class="text-center pad-top ">
				<h2>JWT creator </h2>
				<p>Set the fields, issue a new token, store in browser</hp>
			</div>	
 			<div class="row  pad-top">
               
                <div class="col-md-4 col-md-offset-4 col-sm-6 col-sm-offset-3 col-xs-10 col-xs-offset-1">
                
                        <div class="panel panel-default">
                            
                            <div class="panel-body">
                                <form id="jwtForm" role="form" >
                                	
										<div id="identifiedUser" class="well well-sm"  hidden>JWT issued <a href="index.html">(view)</a></div>
									<!-- 									<br/> -->
                                        <div class="form-group input-group">
                                            <span class="input-group-addon"><i class="glyphicon glyphicon-user"  ></i></span>
                                            <input type="text" class="form-control" placeholder="User unique ID (sub)" id="sub"  value="123456"/>
                                        </div>
                                        <div class="form-group input-group">
                                            <span class="input-group-addon"><i class="glyphicon glyphicon-credit-card"  ></i></span>
                                            <input type="text" class="form-control" placeholder="Your unique identifier(eidentifier)" id="eidentifier"  value="john.smith"/>
                                        </div>
                                        <div class="form-group input-group">
                                            <span class="input-group-addon">@</span>
                                            <input type="text" class="form-control" placeholder="Full name (name)" id="name" value="John Smith"/>
                                        </div>
                                     	<div class="form-group input-group">
                                            <span class="input-group-addon"><i class="glyphicon glyphicon-phone-alt"  ></i></span>
                                            <input type="text" class="form-control" placeholder="Your phone number (phone)" id="phone" value="34 661661661"/>
                                        </div>
                                        <div class="form-group input-group">
                                            <span class="input-group-addon">@</span>
                                            <input type="text" class="form-control" placeholder="Your email (email)" id="email" value="john.smith@mycompany.com"/>
                                        </div>
                                        <div class="form-group input-group">
                                            <span class="input-group-addon"><i class="glyphicon glyphicon-credit-card"  ></i></span>
                                            <input type="text" class="form-control" placeholder="Other interesting field (other)" id="other" value="..."/>
                                        </div>
                                     
                                     
                                     <a href="javascript:handleCreateJWTClick()" class="btn btn-success ">Create JWT token</a>
                                    </form>
                            </div>
                           
                        </div>
                    </div>
                
                
        </div>
	</div>
		
		
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <!--SSO--><script src="https://produccion.sslsignature.com/sslsignature/resources/js/sslssso.js"></script><!--SSO-->
    <script src="js/config.js"></script>
    
    <script>
    	    	
    	function onIdentification(operation){
    		console.log("SSO PAGE onIdentification event" );
    		$('#identifiedUser').show();
    		
    	}
    	function onLoad(){
    		console.log("SSO PAGE onLoad event");
    	}
    	function onLogout(){
    		console.log("SSO PAGE onLogout event");
    		$('#identifiedUser').hide();
    	}
    	
    	
    	function handleCreateJWTClick(){
    		var url = config.apiUrl + "/account/jwt";
    		var params = {
    			sub:	$('#sub').val(),
    			eidentifier:	$('#eidentifier').val(),
    			name:	$('#name').val(),
    			phone:	$('#phone').val(),
    			email:	$('#email').val(),
    			other:	$('#other').val()
    		}
    		console.log("POST "+url);
    		console.log(params);
    		
    		$.ajax({
    			  type: "POST",
    			  url: url,
    			  data: JSON.stringify(params),
    			  success: function(jwt) {
  					console.log("JWT: "+jwt.JWT.data);
					//Store JWT in browser SSO
					sslssso.login(jwt.JWT.data);
					$('#identifiedUser').show();
                  },
                  contentType: "application/json",
    			  beforeSend: function (xhr) {
    				var auth =  config.tokenType+" " + btoa(config.accountId + ':' + config.apiKey);
  					xhr.setRequestHeader("Authorization", auth);
  				  }
			});
    		
    	}	
    	
    	
    </script>
	</body>
</html>

================================================
FILE: test/web/hosted/keystore.html
================================================
<!DOCTYPE HTML>
<html>
	<head>
	
		<title>SSLSignature KeyStore</title>
	    <meta http-equiv="X-UA-Compatible" content="IE=edge">
	    <meta name="viewport" content="width=device-width, initial-scale=1">
	    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
		<link rel="icon" href="img/favicon.ico">
		 <!-- Bootstrap core CSS -->
    	<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
	
	</head>
<body>
	<div class="container">
		<div>
   			<h2>SSLSignature Keystore</h2>
   	 		<p>Store digital certificates and private keys on browser using Web Cryptography Api</p>
   	 	</div>
    
    	<div id="webcryptoAlert" class="alert alert-warning well-sm" role="alert" hidden></div>
   	 	<div>
   	 		<hr/>
   	 		<h3>Available digital certificates</h3>
			
			<div id = "keyList" class="input-group">				
	        </div>
	        <div class="btn-group">
				<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#importCertificateModal">Import</button>
				<a href="javascript:handleExportClick();" id="export" class="btn btn-default " role="button">Export</a>
				<a href="javascript:handleDeleteClick();" id="delete" class="btn btn-default" role="button">Delete</a>
			</div>
		</div>
	
   	 	<div>
   	 		<hr/>
   	 		<h3>Available CryptoKeys </h3>
			
			<div id = "cryptoKeyList" class="input-group">				
	        </div>
	        <div class="btn-group">
				<a href="javascript:handleDeleteCryptoKeyClick();" id="deleteCryptoKey" class="btn btn-default" role="button">Delete</a>
			</div>
		</div>
	</div>
	
	
	<div class="modal fade" id="importCertificateModal" tabindex="-1" role="dialog">
	  <div class="modal-dialog">
	    <div class="modal-content">
	      <div class="modal-header">
	        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
	        <h4 class="modal-title">Import certificate (PFX o P12)</h4>
	      </div>
	      <div class="modal-body">
	        <p>Select the file with your certificate and enter the password. The certificate will be stored in the native keystore of the browser and could not be exportable, therefore you should maintain an additional copy of your certificates</p>
			<div class="form-group">
			    <input type="file" name="content" id="pkcs12File" placeholder=".pfx o .p12 file" />
			</div>
			<div class="form-group">
    			<label for="password">Password</label>
    			<input type="password" name="password" id="password" value="" placeholder ="Contrasea .p12 or .pfx " class="form-control">
  			</div>
					
				
			<div class="checkbox">
			  <label>
			    <input type="checkbox" id="extractable" name="extractable">
			    Mark the key as exportable
			  </label>
			</div>	
	      </div>
	      <div class="modal-footer">
	        <button type="button" class="btn btn-primary" onclick="handleImportPkcs12Click();">Import</button>
	        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
	      </div>
	    </div>
	  </div>
	</div>
	
	
	

	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <!-- <script src="https://produccion.sslsignature.com/sslsignature/resources/js/sslssso.js"></script> -->
        
    <script src="https://produccion.sslsignature.com/sslsignature/resources/js/es6-promise.min.js"></script>
    <script src="https://produccion.sslsignature.com/sslsignature/resources/js/forge.min.js"></script>
    <script src="https://produccion.sslsignature.com/sslsignature/resources/js/ssls.min.js"></script>
	
	<script src="js/keystore.js"></script>
	</body>	
</html>

================================================
FILE: test/web/hosted/login.html
================================================
<!DOCTYPE HTML>
<html>
<head>
	<title>SSO SSLSignature</title>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
	<meta name="description" content="" />
	<meta name="keywords" content="" />
	<META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">
	<link rel="icon" href="img/favicon.ico">
	
	<meta name="ssls.accountId" content="5995a3c9-678b-4338-a674-362af68b9ef9" />
	
	<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">

</head>


 <body>
 	<div class="container">
   		<div class="text-center pad-top ">
   			<h2 id="siteTitle">SSO ID FORM</h2>
   	 		<p id="siteDescription">Select ID method</p>
   	 	</div>
   	 	<div class="row pad-top">
           	<div class="col-md-4 col-md-offset-4 col-sm-6 col-sm-offset-3 col-xs-10 col-xs-offset-1">	
                <hr/>
                <button type="button" class="btn btn-default btn-block" aria-label="Left Align" onclick="loginByCert();" id="idByCert"><span><img  src="img/cert.png" alt="Identificación por certificado electrónico SSL"  height="20" class="pull-left"></span> ID por certificado (SSL)</button>
                <button type="button" class="btn btn-default btn-block" aria-label="Left Align" onclick="loginByClave();" id="idByClave"><span><img  src="img/clave.gif" alt="Identificación por cl@ve"  height="20" class="pull-left"></span> ID por cl@ve</button>
			 	
			 	 <!-- WebCryptographyApi -->
			 	<div class="btn-group btn-block" id="webcryptoListOn">
          	  		<button type="button" class="btn btn-default col-lg-11" aria-label="Left Align" onclick="loginByWebCrypto();"><span><img  src="img/cert.png" alt="Identificación por certificado electrónico con WebCrypto"  height="20" class="pull-left"></span> ID por certificado (WebCrypto)</button>
			  		<button type="button" class="btn btn-default dropdown-toggle col-lg-1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
			  	 		<span class="caret"></span>
			     		<span class="sr-only">Toggle Dropdown</span>
			  		</button>
			  		<ul class="dropdown-menu" id="webcryptoList">
			  		</ul>
		  		</div> 
		  		<!-- 
		  		<div class="form-group has-error has-feedback" id="webcryptoOff">
          			<button type="button" class="btn btn-default btn-block" aria-label="Left Align" disabled>
          				<span><img  src="img/cert.png" alt="Identificación por certificado electrónico con WebCrypto"  height="20" class="pull-left"></span> 
          				ID por certificado (WebCrypto)
          			</button> 
          			<span class="glyphicon glyphicon-warning-sign form-control-feedback" aria-hidden="true"></span> 
          			<span id="webcryptoAlert" class="help-block" hidden></span> 
          		
          		</div>
          		-->
          		
          		<button type="button" class="btn btn-default btn-block" aria-label="Left Align" id="webcryptoOff" data-toggle="tooltip" title="">
         				<span><img  src="img/cert.png" alt="Identificación por certificado electrónico con WebCrypto"  height="20" class="pull-left"></span> 
         				ID with digital certificate (WebCrypto)
         				<span class="glyphicon glyphicon-warning-sign pull-right" aria-hidden="true"></span>
       			</button> 
        			
			 	<!-- CryptoKeys -->
			 	
			 	<button id="cryptokeysOn" type="button" class="btn btn-default btn-block" aria-label="Left Align">
			 		<span><img  src="img/cryptokeys.png" alt="Identificación por CryptoKey"  height="20" class="pull-left" ></span> 
		        	 ID with CryptoKey
		        </button>  
			 	<div id="cryptokeysListOn" class="btn-group btn-block" >
					  <button type="button" class="btn btn-default btn-block dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
					  	<span><img  src="img/cryptokeys.png" alt="Identificación por CryptoKey"  height="20" class="pull-left"></span> ID with CryptoKey <span class="caret pull-right"></span>
					  </button>
					  <ul class="dropdown-menu" id="cryptokeysList">
					  </ul>
				</div>
		        
		       	      
		        <button  id="cryptokeysOff" type="button" class="btn btn-default btn-block" aria-label="Left Align"   data-toggle="tooltip" title="opa">
		        	<span><img  src="img/cryptokeys.png" alt="Identificación por CryptoKey"  height="20" class="pull-left" ></span> 
		        	 ID with CryptoKey
		        	 <span class="glyphicon glyphicon-warning-sign pull-right" aria-hidden="true"></span>  
		        </button>
		         
		        <!-- Usuario y contraseña -->
		        
			 	<button type="button" class="btn btn-default btn-block" data-toggle="modal" data-target="#loginByUserPwd" id="idByPassword"> <span><img  src="img/pwd.png" alt="Identificación por usuario y contraseña"  height="20" class="pull-left"></span> ID por contraseña</button>
			 	<hr/>
			 	<a href="register.html" class="btn btn-success ">Register</a>
			 	<a href="keystore.html" class="pull-right" >Manage Key Store</a>
		 	</div>
		 	 
		</div>
	</div>	
	
	<div class="modal fade" id="loginByUserPwd" tabindex="-1" role="dialog">
	  <div class="modal-dialog">
	    <div class="modal-content">
	      <div class="modal-header">
	        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
	        <h4 class="modal-title">ID with username and password</h4>
	      </div>
	      <div class="modal-body">
	        <p>Enter your CryptoKeys credentials. You have to be registered to use this service</p>
			<div class="form-group">
    			<label for="password">User</label>
    			<input type="text" name="username" id="username" value="" placeholder ="username / email / private ID / phone" class="form-control">
  			</div>
			<div class="form-group">
    			<label for="password">Password</label>
    			<input type="password" name="password" id="password" value="" placeholder ="Password " class="form-control">
  			</div>
					
				<!-- 
			<div class="checkbox">
			  <label>
			    <input type="checkbox" id="extractable" name="extractable">
			    Marcar la clave como exportable
			  </label>
			</div>	
			 -->
	      </div>
	      <div class="modal-footer">
	        <button type="button" class="btn btn-primary" onclick="loginByUserPwd();">Identify</button>
	        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
	      </div>
	    </div>
	  </div>
	</div>	
	
	
	
	
	 <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
 	 <!--SSO--><script src="https://produccion.sslsignature.com/sslsignature/resources/js/sslssso.js"></script><!--SSO-->
    <script src="https://produccion.sslsignature.com/sslsignature/resources/js/es6-promise.min.js"></script>
    <script src="https://produccion.sslsignature.com/sslsignature/resources/js/forge.min.js"></script>
    <script src="https://produccion.sslsignature.com/sslsignature/resources/js/ssls.min.js"></script>
    <script src="js/login.js"></script>
    <script src="js/config.js"></script>

    <script>
    	
    	start (config);
    	
    	sslssso.listen("sso.onload", function(observable, eventType, data){
	        console.log("----------------");
	        console.log("sso.onload");
	        console.log("----------------");
	    });
    	sslssso.listen("sso.onidentification", function(observable, eventType, data){
	        console.log("----------------");
	        console.log("sso.onidentification");
	        console.log("----------------");
	    });
    </script>
   
</body>
</html>

================================================
FILE: test/web/hosted/register.html
================================================
<!DOCTYPE HTML>

<html>
	<head>
		<title>SSLSignature - Cryptokeys</title>
		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
		
		<META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">
		<link rel="icon" href="img/favicon.ico">
		<meta name="ssls.accountId" content="5995a3c9-678b-4338-a674-362af68b9ef9" />
		<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
	</head>
	<body>

		<!-- CTA -->
		<div id="cta" class="container">
			
			<div class="text-center pad-top ">
				<h2>CryptoKeys Register</h2>
			</div>	
 			<div class="row  pad-top">
               
                <div class="col-md-4 col-md-offset-4 col-sm-6 col-sm-offset-3 col-xs-10 col-xs-offset-1">
                
                        <div class="panel panel-default">
                            
                            <div class="panel-body">
                                <form role="form">
                                	<div id="identifiedUser" class="alert alert-info well-sm" role="alert">User not identified</div>
									<!-- 									<br/> -->
                                        <div class="form-group input-group">
                                            <span class="input-group-addon"><i class="glyphicon glyphicon-user"  ></i></span>
                                            <input type="text" class="form-control" placeholder="Su nombre" id="usernameSignup"/>
                                        </div>
                                     	<div class="form-group input-group">
                                            <span class="input-group-addon"><i class="glyphicon glyphicon-phone-alt"  ></i></span>
                                            <input type="text" class="form-control" placeholder="Su teléfono (+34xxxxx)" id="phoneSignup"/>
                                        </div>
                                         <div class="form-group input-group">
                                            <span class="input-group-addon">@</span>
                                            <input type="text" class="form-control" placeholder="Su correo (email@server.es)" id="emailSignup"/>
                                        </div>
                                        <div class="form-group input-group">
                                            <span class="input-group-addon"><i class="glyphicon glyphicon-credit-card"  ></i></span>
                                            <input type="text" class="form-control" placeholder="Su NIF (12345678A)" id="nifSignup"/>
                                        </div>
                                      <div class="form-group input-group">
                                            <span class="input-group-addon"><i class="glyphicon glyphicon-lock"  ></i></span>
                                            <input type="password" class="form-control" placeholder="Contraseña de recuperación" id="passwordSignup"/>
                                        </div>
                                     <div class="form-group input-group">
                                            <span class="input-group-addon"><i class="glyphicon glyphicon-lock"  ></i></span>
                                            <input type="password" class="form-control" placeholder="Vuelva a introducir la contraseña" id="passwordSignup2"/>
                                        </div>
                                     
                                     <a href="javascript:handleRegisterUserClick()" class="btn btn-success ">Register</a>
                                    <hr />
                                    ¿Ya registrado? <a href="login.html" >Identify</a>
                                    </form>
                            </div>
                           
                        </div>
                    </div>
                
                
        </div>
	</div>
		
		
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
	<!--SSO--><script src="https://produccion.sslsignature.com/sslsignature/resources/js/sslssso.js"></script><!--SSO-->
    <script src="https://produccion.sslsignature.com/sslsignature/resources/js/es6-promise.min.js"></script>
    <script src="https://produccion.sslsignature.com/sslsignature/resources/js/forge.min.js"></script>
    <script src="https://produccion.sslsignature.com/sslsignature/resources/js/ssls.min.js"></script>
    <script src="js/register.js"></script>
    <script src="js/config.js"></script>
    <script>
    	start (config);
    	</script>
	</body>
</html>

================================================
FILE: test/web/hosted/sso.html
================================================
<!DOCTYPE HTML>
<html>
	<head>
		<title>SSLSignature Demo SSO</title>
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<meta name="ssls.accountId" content="5995a3c9-678b-4338-a674-362af68b9ef9" />
		<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
		
	</head>
	<script>
		// Fired after validating JWT on page onLoad process, or after a successful identification
		function onIdentification(operation){
			$( "#title" ).html("Welcome "+operation.name + "("+operation.eIdentifier+")");
			$( "#token" ).html("JWT");
			
			$( "#body" ).val(JSON.stringify(operation, null, '\t'));
			$( "#body" ).show();
		}
		//Fired when sso is fully loaded
		function onLoad(){
		}
		//Fired onLogout
		function onLogout(){
			console.log("[PAGE] logout");
			$( "#title" ).html("Welcome!! ");
			$( "#token" ).html("No identification token (JWT) available");
			$( "#body" ).hide();
		}
	</script>
		
<body>

	<div class="jumbotron">
      <div class="container">
        <h1>SSLSignature SingleSignOn Demo</h1>
        <p>Multidomain Single Sign On with Json Web Token (JWT)</p>
      </div>
    </div>
    
    <section id="main">
   	 	<div class="container">
   	 		<h2 id="title">Welcome!!</h2>
   	 		<p id="token">No identification token (JWT) available</p>
 	 			<textarea  id="body" rows=10 disabled class="form-control" style="min-width: 100%"></textarea>
   	 		
			<hr/>
			 <a type="button" class="btn btn-success" aria-label="Left Align" href="jwtcreator.html">JWT creator</a>
			 <a type="button" class="btn btn-primary" aria-label="Left Align" href="login.html">Identify</a>
			 <button type="button" class="btn btn-danger" aria-label="Left Align" onclick="sslssso.logout();"><span class="glyphicon glyphicon-off" aria-hidden="true"></span> Logout</button>
		</div>
	</section>
	
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
     <!--SSO--><script src="https://produccion.sslsignature.com/sslsignature/resources/js/sslssso.js"></script><!--SSO-->
   
	
</body>
</html>

================================================
FILE: test/web/standalone/index.html
================================================
<!DOCTYPE HTML>

<html>
	<head>
		<title>SSLSignature - JWT Creator</title>
		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1">
				
		<meta name="ssls.accountId" content="jwtdemo" />
		<meta name="ssls.validate" content="false" />
				 
		<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
	</head>
	<body>

		<!-- CTA -->
		<div id="cta" class="container">
			
			<div class="text-center pad-top ">
				<h2>JWT creator </h2>
				<p>Set the fields, issue a new token, store in browser</hp>
			</div>	
 			<div class="row  pad-top">
               
                <div class="col-md-4 col-md-offset-4 col-sm-6 col-sm-offset-3 col-xs-10 col-xs-offset-1">
                
                        <div class="panel panel-default">
                            
                            <div class="panel-body">
                                <form id="jwtForm" role="form" >
                                	
										<div id="identifiedUser" class="well well-sm"  hidden>JWT issued <a href="sso.html">(view)</a></div>
									<!-- 									<br/> -->
                                        <div class="form-group input-group">
                                            <span class="input-group-addon"><i class="glyphicon glyphicon-user"  ></i></span>
                                            <input type="text" class="form-control" placeholder="User unique ID (sub)" name="sub" value="123456"/>
                                        </div>
                                        <div class="form-group input-group">
                                            <span class="input-group-addon"><i class="glyphicon glyphicon-credit-card"  ></i></span>
                                            <input type="text" class="form-control" placeholder="Your unique identifier(eidentifier)" name="eidentifier" value="john.smith"/>
                                        </div>
                                        <div class="form-group input-group">
                                            <span class="input-group-addon">@</span>
                                            <input type="text" class="form-control" placeholder="Full name (name)" name="name" value="John Smith"/>
                                        </div>
                                     	<div class="form-group input-group">
                                            <span class="input-group-addon"><i class="glyphicon glyphicon-phone-alt"  ></i></span>
                                            <input type="text" class="form-control" placeholder="Your phone number (phone)" name="phone" value="34 661661661"/>
                                        </div>
                                        <div class="form-group input-group">
                                            <span class="input-group-addon">@</span>
                                            <input type="text" class="form-control" placeholder="Your email (email)" name="email" value="john.smith@mycompany.com"/>
                                        </div>
                                        <div class="form-group input-group">
                                            <span class="input-group-addon"><i class="glyphicon glyphicon-credit-card"  ></i></span>
                                            <input type="text" class="form-control" placeholder="Other interesting field (other)" name="other" value="..."/>
                                        </div>
                                     
                                     
                                     <a href="javascript:handleCreateJWTClick()" class="btn btn-success ">Create JWT token</a>
                                    </form>
                            </div>
                           
                        </div>
                    </div>
                
                
        </div>
	</div>
		
		
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <script src="../resources/js/sslssso.js"></script>
   
    
    <script>
    	
  		//URL of server
		var issueTokenUrl = document.location.origin+"/sso/jwt";
  		
    	//1) Sends an AJAX POST request to  the sample server in /sso/jwt with the required fields
    	//2) The server returns a new JWT with sent info which is signed with server  key (hmac)
    	//3) The JWT is stored in browser usign sslsso.login(jwt)
    	//4) An sslssso.onIdentification event is fired to all listeners
    	//
    	// Issue JWT after a successful user authentication in your own login form (on server side) 
    	function handleCreateJWTClick(){
    		
    		var params = $('#jwtForm').serialize();
    		console.log("POST "+issueTokenUrl);
    		console.log(params);
    		$.post(
    				issueTokenUrl, 
    				params,
    				function(jwt) {
    					console.log("JWT: "+jwt);
    					//Store JWT in browser SSO
    					sslssso.login(jwt);
    					$('#identifiedUser').show();
                    });
    		
    	}	
    	
    	
    </script>
	</body>
</html>

================================================
FILE: test/web/standalone/sso.html
================================================
<!DOCTYPE HTML>
<html>
	<head>
		<title>SSLSignature Demo SSO</title>
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<meta name="ssls.accountId" content="jwtdemo" />
		<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
		
	</head>
	<script>
		//sslssso will connect this URL to validate JWT
		//Use full URL because it will be invoked from user browser
		ssls_validationUrl = document.location.origin+"/sso/jwt";
	
		// Fired after validating JWT on page onLoad process, or after a successful identification
		function onIdentification(operation){
			$( "#title" ).html("Welcome "+operation.name + "("+operation.eidentifier+")");
			$( "#token" ).html("JWT");
			
			$( "#body" ).val(JSON.stringify(operation, null, '\t'));
			$( "#body" ).show();
		}
		//Fired when sso is fully loaded
		function onLoad(){
		}
		//Fired onLogout
		function onLogout(){
			console.log("[PAGE] logout");
			$( "#title" ).html("Welcome!! ");
			$( "#token" ).html("No identification token (JWT) available");
			$( "#body" ).hide();
		}
	</script>
		
<body>

	<div class="jumbotron">
      <div class="container">
        <h1>SSLSignature SingleSignOn Demo</h1>
        <p>Multidomain Single Sign On with Json Web Token (JWT)</p>
      </div>
    </div>
    
    <section id="main">
   	 	<div class="container">
   	 		<h2 id="title">Welcome!!</h2>
   	 		<p id="token">No identification token (JWT) available</p>
 	 			<textarea  id="body" rows=10 disabled class="form-control" style="min-width: 100%"></textarea>
   	 		
			<hr/>
			 <a type="button" class="btn btn-primary" aria-label="Left Align" href="index.html">Identify</a>
			 <button type="button" class="btn btn-danger" aria-label="Left Align" onclick="sslssso.logout();"><span class="glyphicon glyphicon-off" aria-hidden="true"></span> Logout</button>
		</div>
	</section>
	
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <script src="../resources/js/sslssso.js"></script>
   
	
</body>
</html>
Download .txt
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
Download .txt
SYMBOL INDEX (193 symbols across 16 files)

FILE: backend/src/java/com/aralink/sslsignature/sso/jwt/AuthenticationOperation.java
  class AuthenticationOperation (line 17) | public class AuthenticationOperation {
    method AuthenticationOperation (line 25) | public AuthenticationOperation(Exception e){
    method AuthenticationOperation (line 35) | public AuthenticationOperation(Claims body){
    method toJSON (line 51) | public String toJSON(){

FILE: backend/src/java/com/aralink/sslsignature/sso/jwt/HMACKeyContainer.java
  class HMACKeyContainer (line 16) | public class HMACKeyContainer {
    method HMACKeyContainer (line 21) | public HMACKeyContainer()throws IOException{
    method HMACKeyContainer (line 24) | public HMACKeyContainer(String keyFile) throws IOException{
    method getHmacKey (line 41) | public Key getHmacKey(){
    method generateKey (line 44) | private Key generateKey(Path path) throws IOException{
    method hmacKeyFromEncoded (line 53) | public static Key hmacKeyFromEncoded(byte encodedHmacKey[]){

FILE: backend/src/java/com/aralink/sslsignature/sso/jwt/JWTManager.java
  class JWTManager (line 24) | public class JWTManager {
    method JWTManager (line 32) | public JWTManager(HMACKeyContainer hmacKeyContainer){
    method getIssuer (line 36) | public String getIssuer() {
    method setIssuer (line 40) | public void setIssuer(String issuer) {
    method getExpirationTimeInHours (line 44) | public int getExpirationTimeInHours() {
    method setExpirationTimeInHours (line 48) | public void setExpirationTimeInHours(int expirationTimeInHours) {
    method exp (line 54) | private  Date exp (int calendar,int len){
    method isExpired (line 61) | private boolean isExpired(Claims body, Date actual){
    method isExpired (line 66) | private boolean isExpired(Claims body){
    method issueJWT (line 71) | public String issueJWT(@SuppressWarnings("rawtypes") Map extra){
    method validateJWT (line 103) | public Claims validateJWT ( String jwtToken)throws Exception{

FILE: backend/src/java/com/aralink/sslsignature/sso/jwt/JWTServlet.java
  class JWTServlet (line 14) | @SuppressWarnings("serial")
    method init (line 20) | public void init(ServletConfig config) throws ServletException {
    method doOptions (line 37) | public void doOptions(HttpServletRequest request, HttpServletResponse ...
    method doGet (line 43) | public void doGet(HttpServletRequest request, HttpServletResponse resp...
    method doPost (line 48) | public void doPost(HttpServletRequest request, HttpServletResponse res...
    method destroy (line 84) | public void destroy()  {

FILE: client/resources/html/sso.js
  function onIdentification (line 7) | function onIdentification(operation){
  function onLogout (line 17) | function onLogout(){
  function onLoad (line 29) | function onLoad(){
  function postMessageToListeners (line 41) | function postMessageToListeners (operation, domain){
  function doLogout (line 52) | function doLogout(){
  function doLogin (line 59) | function doLogin(jwt){
  function localStorageHandler (line 69) | function localStorageHandler(e) {
  function localStorageHandlerIE8 (line 80) | function localStorageHandlerIE8(e) {
  function listener (line 96) | function listener(event){
  function validateJWT (line 125) | function validateJWT(jwtsso){
  function validateJWTRemote (line 136) | function validateJWTRemote(jwtsso){
  function parseJWTLocal (line 185) | function parseJWTLocal(jwtsso){
  function ready (line 212) | function ready(){
  function init (line 224) | function init(config){

FILE: client/resources/html/sso_common.js
  function log (line 7) | function log(level, object){
  function getOrigin (line 13) | function getOrigin(){
  function getGetParam (line 20) | function getGetParam (vr){
  function JWT (line 38) | function JWT (jwt){

FILE: client/resources/html/sso_rest.js
  function RestClient (line 2) | function RestClient (host,accountId,apiKey,scheme){

FILE: client/resources/js/sslssso.js
  function Observable (line 4) | function Observable(){
  function sslssso (line 42) | function sslssso (){

FILE: test/java/com/aralink/sslsignature/sso/jwt/test/JWTTest.java
  class JWTTest (line 29) | public class JWTTest {
    method setUpBeforeClass (line 32) | @BeforeClass
    method tearDownAfterClass (line 36) | @AfterClass
    method setUp (line 41) | @Before
    method tearDown (line 46) | @After
    method issueAndValidateJWT (line 51) | @Test
    method alteredJWT (line 82) | @Test
    method fakeJWT (line 116) | @Test

FILE: test/java/com/aralink/sslsignature/sso/jwt/test/RestClient.java
  class RestClient (line 15) | public class RestClient {
    method RestClient (line 24) | public RestClient (String url){
    method RestClient (line 28) | public RestClient (String url, String user, String password){
    method getUrl (line 35) | public String getUrl() {
    method setUrl (line 38) | public void setUrl(String url) {
    method getUser (line 41) | public String getUser() {
    method setUser (line 44) | public void setUser(String user) {
    method getPassword (line 47) | public String getPassword() {
    method setPassword (line 50) | public void setPassword(String password) {
    method postJson (line 56) | public String postJson(String uri, String jsonRequest) throws IOExcept...
    method postForm (line 66) | public String postForm(String uri, Map<String, String> formParams) thr...
    method post (line 77) | public String post(String uri) throws IOException{
    method get (line 84) | public String get(String uri) throws IOException{
    method getStream (line 93) | public InputStream getStream(String uri) throws IOException{
    method delete (line 101) | public String delete(String uri) throws IOException{
    method postStream (line 108) | public String postStream(String uri, byte data[])throws  IOException{
    method processJsonResponse (line 116) | private String processJsonResponse(HttpURLConnection conn)throws IOExc...
    method processStreamResponse (line 134) | private InputStream processStreamResponse(HttpURLConnection conn)throw...
    method upload (line 150) | private void upload(HttpURLConnection conn, byte data[]) throws IOExce...
    method getConnection (line 157) | private HttpURLConnection getConnection(String method,String uri, Stri...
    method read (line 176) | private static String read(InputStream in) throws IOException{
    method serialize (line 193) | private static String serialize(Map<String,String> params){

FILE: test/java/com/aralink/sslsignature/sso/jwt/test/SimpleConsoleLogger.java
  class SimpleConsoleLogger (line 3) | public class SimpleConsoleLogger {
    type Level (line 4) | public enum Level {	ERROR, WARN, INFO, DEBUG,TRACE}
    method setLevel (line 14) | public static void setLevel (Level l){
    method getLevel (line 17) | public static Level getLevel(){
    method info (line 21) | public static void info(String message){
    method error (line 24) | public static void error(String message){
    method warn (line 27) | public static void warn(String message){
    method debug (line 30) | public static void debug(String message){
    method trace (line 33) | public static void trace(String message){
    method log (line 37) | public static void log(Level level, String message){
    method log (line 40) | public static void log(Level level, String message, Throwable throwable){

FILE: test/web/hosted/js/index.js
  function start (line 18) | function start(conf){
  function onIdentification (line 52) | function onIdentification(operation){
  function onLoad (line 57) | function onLoad(){
  function onLogout (line 67) | function onLogout(){
  function configureForm (line 76) | function configureForm(mode){
  function recoverFailedIdentification (line 113) | function recoverFailedIdentification(otp){
  function identificationPerformed (line 124) | function identificationPerformed(obj){
  function infoSignature (line 155) | function infoSignature(obj) {
  function login (line 214) | function login (username,password,scheme){
  function openCryptoKeyStore (line 257) | function openCryptoKeyStore(){
  function keyExists (line 277) | function keyExists(pkcs12Entry){
  function requestAKey (line 284) | function requestAKey(){
  function keyCreated (line 313) | function keyCreated(pkcs12Entry){
  function handleLogoutClick (line 319) | function handleLogoutClick(){
  function handleEnrollClick (line 322) | function handleEnrollClick () {
  function enrollFailed (line 367) | function enrollFailed(result){
  function configureNewKeyForm (line 375) | function configureNewKeyForm(){
  function configureBadKeyForm (line 385) | function configureBadKeyForm(){
  function handleResendClick (line 396) | function handleResendClick(){
  function handleExecuteSignedTransactionClick (line 405) | function handleExecuteSignedTransactionClick(){
  function executeSignedTransactionImpl (line 419) | function executeSignedTransactionImpl(pin){
  function validateCurrentKeyAndRequestIfNotValid (line 447) | function validateCurrentKeyAndRequestIfNotValid(pkcs12Entry){
  function doDeleteKey (line 481) | function doDeleteKey(){
  function showCheckResultMessage (line 511) | function showCheckResultMessage(mensaje, alertType){
  function callFailed (line 520) | function callFailed(result) {
  function generateCSR (line 527) | function generateCSR(userConnected,keys){
  function createCSR (line 546) | function createCSR(keys, C,CN,SERIALNUMBER){
  function listDevices (line 596) | function listDevices(userId){
  function addToDeviceList (line 610) | function addToDeviceList(key){
  function doRevokeKey (line 665) | function doRevokeKey(selectedKeyId){
  function handleRegisterDeviceClick (line 678) | function handleRegisterDeviceClick(){
  function handleRefreshDevicesClick (line 696) | function handleRefreshDevicesClick(){
  function handleExecuteSignedTransactionDoubleFactorClick (line 701) | function handleExecuteSignedTransactionDoubleFactorClick(){
  function checkCallStatus (line 714) | function checkCallStatus(){
  function authorizationResponse (line 727) | function authorizationResponse(obj) {
  function handleDownloadAppClick (line 749) | function handleDownloadAppClick(){
  function makeAuthorizationLink (line 758) | function makeAuthorizationLink(authorization){
  function makeRegisterLink (line 771) | function makeRegisterLink(userId){
  function isAuthorizationFinished (line 785) | function isAuthorizationFinished(status) {
  function finishAuthorization (line 788) | function finishAuthorization(authorization) {
  function doAbort (line 821) | function doAbort(){
  function handleAbortClick (line 825) | function handleAbortClick(){
  function initTimer (line 838) | function initTimer(){
  function runTimer (line 843) | function runTimer(){
  function cancelTimer (line 858) | function cancelTimer(){
  function getGetParam (line 867) | function getGetParam (vr){
  function getBrowserInfo (line 884) | function getBrowserInfo(){

FILE: test/web/hosted/js/jwtcreator.js
  function start (line 4) | function start(conf){
  function onIdentification (line 10) | function onIdentification(operation){
  function onLoad (line 14) | function onLoad(){
  function onLogout (line 17) | function onLogout(){
  function handleCreateJWTClick (line 22) | function handleCreateJWTClick(){

FILE: test/web/hosted/js/keystore.js
  function configureForm (line 17) | function configureForm(){
  function checkWebCrypto (line 21) | function checkWebCrypto(){
  function disableWebCrypto (line 38) | function disableWebCrypto(message){
  function openWebCryptoKeyStore (line 44) | function openWebCryptoKeyStore(){
  function openCryptoKeysKeyStore (line 55) | function openCryptoKeysKeyStore(){
  function importPkcs12 (line 68) | function importPkcs12(file,password, extractable){
  function listKeyStore (line 89) | function listKeyStore(){
  function addToKeyList (line 101) | function addToKeyList(keystoreObject){
  function listCryptoKeyStore (line 119) | function listCryptoKeyStore(){
  function addToCryptoKeyList (line 131) | function addToCryptoKeyList(keystoreObject){
  function escapeHTML (line 148) | function escapeHTML(s) {
  function handleDeleteClick (line 154) | function handleDeleteClick(){
  function handleDeleteCryptoKeyClick (line 166) | function handleDeleteCryptoKeyClick(){
  function handleImportPkcs12Click (line 179) | function handleImportPkcs12Click(){
  function handleExportClick (line 188) | function handleExportClick(){
  function downloadAsBlob (line 213) | function downloadAsBlob(p12b64,selectedKeyName){

FILE: test/web/hosted/js/login.js
  function start (line 24) | function start(conf){
  function configureForm (line 42) | function configureForm(){
  function isWebCryptoEnabled (line 72) | function isWebCryptoEnabled(){
  function isCryptoKeysEnabled (line 75) | function isCryptoKeysEnabled(){
  function isCertificateEnabled (line 78) | function isCertificateEnabled(){
  function isClaveEnabled (line 81) | function isClaveEnabled(){
  function isPasswordEnabled (line 84) | function isPasswordEnabled(){
  function checkWebCrypto (line 88) | function checkWebCrypto(){
  function checkCryptoKeys (line 97) | function checkCryptoKeys(){
  function disableWebCrypto (line 107) | function disableWebCrypto(message){
  function disableCryptoKeys (line 117) | function disableCryptoKeys(message){
  function enableWebCrypto (line 128) | function enableWebCrypto(list){
  function enableCryptoKeys (line 140) | function enableCryptoKeys(list){
  function openWebCryptoKeyStore (line 162) | function openWebCryptoKeyStore(){
  function openCryptoKeysKeyStore (line 185) | function openCryptoKeysKeyStore(){
  function loginByCert (line 206) | function loginByCert () {
  function loginByClave (line 211) | function loginByClave () {
  function loginByWebCrypto (line 217) | function loginByWebCrypto () {
  function loginByWebCryptoId (line 266) | function loginByWebCryptoId (keyId) {
  function loginByCryptoId (line 313) | function loginByCryptoId(userId){
  function loginByUserPwd (line 341) | function loginByUserPwd(){
  function doRedirect (line 376) | function doRedirect(url){
  function buildRedirect (line 388) | function buildRedirect(){
  function onIdentification (line 398) | function onIdentification(operation){
  function onLoad (line 409) | function onLoad(){
  function onLogout (line 412) | function onLogout(){
  function showMessage (line 416) | function showMessage(message){

FILE: test/web/hosted/js/register.js
  function start (line 8) | function start(conf){
  function onIdentification (line 15) | function onIdentification(operation){
  function onLoad (line 19) | function onLoad(){
  function onLogout (line 22) | function onLogout(){
  function showRegisterMessage (line 27) | function showRegisterMessage(message,alertClass){
  function handleRegisterUserClick (line 38) | function handleRegisterUserClick(){
  function proceedToRegister (line 78) | function proceedToRegister(userToRegister){
  function showRegisterError (line 100) | function showRegisterError(err){
  function authenticationPerformed (line 112) | function authenticationPerformed(operation){
Condensed preview — 35 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (204K chars).
[
  {
    "path": "LICENSE",
    "chars": 35141,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
  },
  {
    "path": "README.md",
    "chars": 9101,
    "preview": "# Cross domain Single sign-on with Json Web Tokens (JWT)\n> Federate your websites using only javascript\n\nAccess to sever"
  },
  {
    "path": "backend/src/java/com/aralink/sslsignature/sso/jwt/AuthenticationOperation.java",
    "chars": 1310,
    "preview": "package com.aralink.sslsignature.sso.jwt;\n\nimport java.io.StringReader;\nimport java.util.HashMap;\nimport java.util.Map;\n"
  },
  {
    "path": "backend/src/java/com/aralink/sslsignature/sso/jwt/HMACKeyContainer.java",
    "chars": 1496,
    "preview": "package com.aralink.sslsignature.sso.jwt;\n\n\nimport io.jsonwebtoken.impl.crypto.MacProvider;\n\nimport java.io.IOException;"
  },
  {
    "path": "backend/src/java/com/aralink/sslsignature/sso/jwt/JWTManager.java",
    "chars": 3526,
    "preview": "package com.aralink.sslsignature.sso.jwt;\n\nimport io.jsonwebtoken.Claims;\nimport io.jsonwebtoken.ExpiredJwtException;\nim"
  },
  {
    "path": "backend/src/java/com/aralink/sslsignature/sso/jwt/JWTServlet.java",
    "chars": 2571,
    "preview": "package com.aralink.sslsignature.sso.jwt;\n\nimport io.jsonwebtoken.Claims;\n\nimport java.io.IOException;\n\nimport javax.ser"
  },
  {
    "path": "backend/src/web/WEB-INF/web.xml",
    "chars": 870,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<web-app xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txmlns=\"http://jav"
  },
  {
    "path": "build/build.xml",
    "chars": 1795,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<project name=\"SSO SSLSignature GIT\" default=\"\" basedir=\"..\" xmlns:ivy=\"antlib:o"
  },
  {
    "path": "build/gruntfile.js",
    "chars": 675,
    "preview": "module.exports = function(grunt) {\n\n  // Project configuration.\n  grunt.initConfig({\n    pkg: grunt.file.readJSON('packa"
  },
  {
    "path": "build/ivy.xml",
    "chars": 973,
    "preview": "<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. \n\tSee the NOTICE"
  },
  {
    "path": "build/package.json",
    "chars": 212,
    "preview": "{\n  \"name\": \"sslssso\",\n  \"version\": \"1.0.0\",\n  \"devDependencies\": {\n    \"grunt\": \"~0.4.5\",\n    \"grunt-contrib-jshint\": \""
  },
  {
    "path": "client/resources/html/sso.html",
    "chars": 959,
    "preview": "<!DOCTYPE HTML>\n<html>\n\t<head>\n\t\t<title>SSLSignature SSO IFRAME</title>\n\t\t<!-- <script src=\"../js/jquery-1.7.1.min.js\"><"
  },
  {
    "path": "client/resources/html/sso.js",
    "chars": 7307,
    "preview": "var validationUrl;\nvar validate;\nvar accountId;\nvar tokenId;\nvar apiKey;\n\t\t\t\nfunction onIdentification(operation){\n\tlog("
  },
  {
    "path": "client/resources/html/sso_common.js",
    "chars": 3445,
    "preview": "\nvar LogLevels = {DEBUG:0, INFO:1, WARN:2, ERROR:3};\nvar logLevel = LogLevels.DEBUG;\nvar console = window.console || { l"
  },
  {
    "path": "client/resources/html/sso_rest.js",
    "chars": 7648,
    "preview": "\t\nfunction RestClient (host,accountId,apiKey,scheme){\n\t\"use strict\";\n\t\n    //this.host = host;\n    //this.accountId = ac"
  },
  {
    "path": "client/resources/js/sslssso.js",
    "chars": 7083,
    "preview": "sslssso = new sslssso();\nvar console = window.console || { log: function() {} };\n\nfunction Observable(){\n\t\n    this.list"
  },
  {
    "path": "test/java/com/aralink/sslsignature/sso/jwt/test/JWTTest.java",
    "chars": 4263,
    "preview": "package com.aralink.sslsignature.sso.jwt.test;\n\n\nimport io.jsonwebtoken.Jwts;\nimport io.jsonwebtoken.impl.crypto.MacProv"
  },
  {
    "path": "test/java/com/aralink/sslsignature/sso/jwt/test/RestClient.java",
    "chars": 5381,
    "preview": "package com.aralink.sslsignature.sso.jwt.test;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.i"
  },
  {
    "path": "test/java/com/aralink/sslsignature/sso/jwt/test/SimpleConsoleLogger.java",
    "chars": 1164,
    "preview": "package com.aralink.sslsignature.sso.jwt.test;\n\npublic class SimpleConsoleLogger {\n\tpublic enum Level {\tERROR, WARN, INF"
  },
  {
    "path": "test/web/hosted/index.html",
    "chars": 8007,
    "preview": "<!DOCTYPE HTML>\n\n<html>\n\t<head>\n\t\t<title>SSLSignature - CryptoKeys</title>\n\t\t<meta charset=\"utf-8\">\n\t\t<meta http-equiv=\""
  },
  {
    "path": "test/web/hosted/js/config.js",
    "chars": 684,
    "preview": "var config = {\n\t\tapiUrl: 'https://produccion.sslsignature.com/sslsignature',\n        accountId: '5995a3c9-678b-4338-a674"
  },
  {
    "path": "test/web/hosted/js/index.js",
    "chars": 26583,
    "preview": "var uAg = navigator.userAgent.toLowerCase();\nvar isMobile = !!uAg.match(/android|iphone|ipad|ipod|blackberry|symbianos/"
  },
  {
    "path": "test/web/hosted/js/jwtcreator.js",
    "chars": 632,
    "preview": "\nvar config;\n\t\n\tfunction start(conf){\n\t\tconfig = conf;\n\t}\n\t\n\t\n\t\n\tfunction onIdentification(operation){\n\t\tconsole.log(\"S"
  },
  {
    "path": "test/web/hosted/js/keystore.js",
    "chars": 6120,
    "preview": "\n\tvar ssls;\n\tvar crypto = window.crypto || window.msCrypto;\n\tvar keyStore;\n\tvar cbKeyStore;\n\tvar webcrypto = true;\n\t\n\t$("
  },
  {
    "path": "test/web/hosted/js/login.js",
    "chars": 12841,
    "preview": "\nvar uAg = navigator.userAgent.toLowerCase();\nvar isMobile = !!uAg.match(/android|iphone|ipad|ipod|blackberry|symbianos/"
  },
  {
    "path": "test/web/hosted/js/register.js",
    "chars": 3401,
    "preview": "\nvar config = {\n        apiUrl: 'https://produccion.sslsignature.com/sslsignature',\n        accountId: '5995a3c9-678b-4"
  },
  {
    "path": "test/web/hosted/jwtcreator.html",
    "chars": 5916,
    "preview": "<!DOCTYPE HTML>\n\n<html>\n\t<head>\n\t\t<title>SSLSignature - JWT Creator</title>\n\t\t<meta charset=\"utf-8\">\n\t\t<meta http-equiv="
  },
  {
    "path": "test/web/hosted/keystore.html",
    "chars": 3830,
    "preview": "<!DOCTYPE HTML>\n<html>\n\t<head>\n\t\n\t\t<title>SSLSignature KeyStore</title>\n\t    <meta http-equiv=\"X-UA-Compatible\" content="
  },
  {
    "path": "test/web/hosted/login.html",
    "chars": 7995,
    "preview": "<!DOCTYPE HTML>\n<html>\n<head>\n\t<title>SSO SSLSignature</title>\n\t<meta charset=\"utf-8\">\n\t<meta http-equiv=\"X-UA-Compatibl"
  },
  {
    "path": "test/web/hosted/register.html",
    "chars": 4911,
    "preview": "<!DOCTYPE HTML>\n\n<html>\n\t<head>\n\t\t<title>SSLSignature - Cryptokeys</title>\n\t\t<meta charset=\"utf-8\">\n\t\t<meta http-equiv=\""
  },
  {
    "path": "test/web/hosted/sso.html",
    "chars": 2244,
    "preview": "<!DOCTYPE HTML>\n<html>\n\t<head>\n\t\t<title>SSLSignature Demo SSO</title>\n\t\t<meta http-equiv=\"X-UA-Compatible\" content=\"IE=e"
  },
  {
    "path": "test/web/standalone/index.html",
    "chars": 5262,
    "preview": "<!DOCTYPE HTML>\n\n<html>\n\t<head>\n\t\t<title>SSLSignature - JWT Creator</title>\n\t\t<meta charset=\"utf-8\">\n\t\t<meta http-equiv="
  },
  {
    "path": "test/web/standalone/sso.html",
    "chars": 2214,
    "preview": "<!DOCTYPE HTML>\n<html>\n\t<head>\n\t\t<title>SSLSignature Demo SSO</title>\n\t\t<meta http-equiv=\"X-UA-Compatible\" content=\"IE=e"
  }
]

// ... and 2 more files (download for full content)

About this extraction

This page contains the full source code of the Aralink/ssojwt GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 35 files (181.2 KB), approximately 47.6k tokens, and a symbol index with 193 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!