Skip to content

Instantly share code, notes, and snippets.

@davidmc24
Created January 14, 2015 18:06
Show Gist options
  • Save davidmc24/c67ec8b4a97c390a422f to your computer and use it in GitHub Desktop.
Save davidmc24/c67ec8b4a97c390a422f to your computer and use it in GitHub Desktop.
Simple Ratpack BasicAuthHandler
package integration.pac4j
import chex.config.AuthConfig
import chex.util.HttpResponseCode
import com.unboundid.ldap.sdk.LDAPConnectionPool
import groovy.util.logging.Slf4j
import io.netty.handler.codec.http.HttpHeaderNames
import org.pac4j.core.profile.UserProfile
import org.pac4j.http.profile.HttpProfile
import ratpack.handling.Context
import ratpack.handling.Handler
import javax.inject.Inject
/**
* Pac4j's basic auth handling uses a redirect even if credentials have already been passed, which is unacceptable for
* an API (where we assume that proper clients will always pass credentials). Thus, a handler that makes it work by
* integrating directly against LDAP.
*/
@Slf4j
class BasicAuthHandler implements Handler {
@Inject
LDAPConnectionPool ldapConnectionPool
@Override
void handle(Context context) throws Exception {
def authHeader = context.request.headers.get("Authorization")
if (!authHeader) {
sendUnauthorized(context)
} else {
def encodedValue = authHeader.split(" ")[1]
def decodedValue = new String(encodedValue.decodeBase64())
def decodedParts = decodedValue.split(":")
def username = decodedParts[0]
def password = decodedParts[1]
// Username must include domain
try {
ldapConnectionPool.bindAndRevertAuthentication(username, password)
log.info("Successfully authenticated {}", username)
addUserProfileToRequest(username, context)
// TODO: consider adding authorization there, and maybe sending 403's.
context.next()
} catch (ex) {
log.error("Failed to authenticate {}", username, ex)
sendUnauthorized(context)
}
}
}
private static void addUserProfileToRequest(String username, Context context) {
def profile = new HttpProfile()
profile.build(username, [:])
context.request.add(UserProfile, profile)
}
private static void sendUnauthorized(Context context) {
def authConfig = context.get(AuthConfig)
context.response.headers.add(HttpHeaderNames.WWW_AUTHENTICATE, "Basic realm=\"${authConfig.realmName}\"")
context.response.status(HttpResponseCode.UNAUTHORIZED).send()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment