Skip to content

Instantly share code, notes, and snippets.

@davidmc24
Last active August 29, 2015 14:20
Show Gist options
  • Save davidmc24/395d0012eec435969ebd to your computer and use it in GitHub Desktop.
Save davidmc24/395d0012eec435969ebd to your computer and use it in GitHub Desktop.
Pac4j example
/*
* Copyright 2015 the original author or authors.
*
* Licensed 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.
*/
import com.google.inject.AbstractModule;
import org.pac4j.openid.client.YahooOpenIdClient;
import org.pac4j.openid.profile.yahoo.YahooOpenIdProfile;
import ratpack.guice.Guice;
import ratpack.handling.Context;
import ratpack.handling.Handler;
import ratpack.pac4j.AbstractAuthorizer;
import ratpack.pac4j.Pac4jModule;
import ratpack.session.SessionModule;
import ratpack.session.store.MapSessionsModule;
import ratpack.test.embed.EmbeddedApp;
import static org.junit.Assert.assertEquals;
public class Example {
public static class AuthenticateAllAuthorizer extends AbstractAuthorizer {
@Override
public boolean isAuthenticationRequired(Context context) {
return true;
}
}
public static class MyHandler implements Handler {
@Override
public void handle(Context ctx) throws Exception {
ctx.render("Authenticated as " + ctx.getRequest().maybeGet(YahooOpenIdProfile.class).map(YahooOpenIdProfile::getDisplayName).orElse("noone"));
}
}
public static class ServiceModule extends AbstractModule {
protected void configure() {
install(new SessionModule());
install(new MapSessionsModule(10, 5));
install(new Pac4jModule<>(new YahooOpenIdClient(), new AuthenticateAllAuthorizer()));
}
}
public static void main(String... args) throws Exception {
EmbeddedApp.of(s -> s
.registry(Guice.registry(b -> b.module(ServiceModule.class)))
.handler(r -> new MyHandler())
).test(httpClient -> {
assertEquals("Authenticated as noone", httpClient.getText());
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment