Skip to content

Commit

Permalink
Issue #11560 - Add embedded example for jetty-siwe
Browse files Browse the repository at this point in the history
Signed-off-by: Lachlan Roberts <lachlan@webtide.com>
  • Loading branch information
lachlan-roberts committed Jun 6, 2024
1 parent 144710b commit 2e35df0
Show file tree
Hide file tree
Showing 3 changed files with 105 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,6 @@ public class EthereumAuthenticator extends LoginAuthenticator

public EthereumAuthenticator()
{
// todo: javadoc and documentation
// testing improvements (validation, parsing, end-to-end test, signature verification)
}

public void includeDomains(String... domains)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
//
// ========================================================================
// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.org/licenses/LICENSE-2.0.
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//

package org.eclipse.jetty.security.siwe.example;

import java.io.PrintWriter;
import java.nio.file.Paths;
import java.util.Objects;

import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.io.Content;
import org.eclipse.jetty.security.AuthenticationState;
import org.eclipse.jetty.security.Constraint;
import org.eclipse.jetty.security.SecurityHandler;
import org.eclipse.jetty.security.siwe.EthereumAuthenticator;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Response;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.ResourceHandler;
import org.eclipse.jetty.session.SessionHandler;
import org.eclipse.jetty.util.Callback;

public class SignInWithEthereumEmbeddedExample
{
public static void main(String[] args) throws Exception
{
Server server = new Server();
ServerConnector connector = new ServerConnector(server);
connector.setPort(8080);
server.addConnector(connector);

String resourcePath = Paths.get(Objects.requireNonNull(SignInWithEthereumEmbeddedExample.class.getClassLoader().getResource("")).toURI())
.resolve("../../src/test/resources/")
.normalize().toString();
ResourceHandler resourceHandler = new ResourceHandler();
resourceHandler.setDirAllowed(false);
resourceHandler.setBaseResourceAsString(resourcePath);

Handler.Abstract handler = new Handler.Wrapper(resourceHandler)
{
@Override
public boolean handle(Request request, Response response, Callback callback) throws Exception
{
String pathInContext = Request.getPathInContext(request);
if ("/login.html".equals(pathInContext))
{
return super.handle(request, response, callback);
}
else if ("/logout".equals(pathInContext))
{
AuthenticationState.logout(request, response);
Response.sendRedirect(request, response, callback, "/");
callback.succeeded();
return true;
}

AuthenticationState authState = Objects.requireNonNull(AuthenticationState.getAuthenticationState(request));
response.getHeaders().add(HttpHeader.CONTENT_TYPE, "text/html");
try (PrintWriter writer = new PrintWriter(Content.Sink.asOutputStream(response)))
{
writer.write("UserPrincipal: " + authState.getUserPrincipal());
writer.write("<br><a href=\"/logout\">Logout</a>");
}
callback.succeeded();
return true;
}
};

EthereumAuthenticator authenticator = new EthereumAuthenticator();
authenticator.setLoginPath("/login.html");
SecurityHandler.PathMapped securityHandler = new SecurityHandler.PathMapped();
securityHandler.setAuthenticator(authenticator);
securityHandler.setHandler(handler);
securityHandler.put("/*", Constraint.ANY_USER);

SessionHandler sessionHandler = new SessionHandler();
sessionHandler.setHandler(securityHandler);

ContextHandler contextHandler = new ContextHandler();
contextHandler.setContextPath("/");
contextHandler.setHandler(sessionHandler);

server.setHandler(contextHandler);
server.start();
System.err.println(resourceHandler.getBaseResource());
server.join();
}
}
13 changes: 4 additions & 9 deletions jetty-core/jetty-siwe/src/test/resources/login.html
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ <h4>Sign-In with Ethereum</h4>
<input type="hidden" id="signatureField" name="signature">
<input type="hidden" id="messageField" name="message">
</form>
<p class="alert">Result: <span id="siweResult"></span></p>
<p class="alert" style="display: none;">Result: <span id="siweResult"></span></p>

<script>
let provider = window.ethereum; // Reference to the Ethereum provider (e.g., MetaMask)
let accounts; // This will store fetched accounts
let provider = window.ethereum;
let accounts;

if (!provider) {
document.getElementById('siweResult').innerText = 'MetaMask is not installed. Please install MetaMask to use this feature.';
Expand Down Expand Up @@ -49,15 +49,10 @@ <h4>Sign-In with Ethereum</h4>
} catch (error) {
console.error('Error during login:', error);
document.getElementById('siweResult').innerText = `Error: ${error.message}`;
document.getElementById('siweResult').parentElement.style.display = 'block';
}
});
}

function stringToHex(str) {
const encoder = new TextEncoder();
const bytes = encoder.encode(str);
return bytes.reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '0x');
}
</script>
</body>
</html>

0 comments on commit 2e35df0

Please sign in to comment.