001/* 002 * The contents of this file are subject to the license and copyright 003 * detailed in the LICENSE and NOTICE files at the root of the source 004 * tree. 005 */ 006package org.fcrepo.auth.common; 007 008import javax.servlet.http.HttpServletRequest; 009 010import java.security.Principal; 011import java.util.Set; 012 013import org.fcrepo.kernel.api.exception.RepositoryConfigurationException; 014 015/** 016 * An example principal provider that extracts principals from request headers. 017 * 018 * @author awoods 019 * @since 2015-10-31 020 */ 021public class DelegateHeaderPrincipalProvider extends HttpHeaderPrincipalProvider { 022 023 private static final String SEP = "no-separator"; 024 protected static final String DELEGATE_HEADER = "On-Behalf-Of"; 025 026 public static class DelegatedHeaderPrincipal implements Principal { 027 028 private final String name; 029 030 protected DelegatedHeaderPrincipal(final String name) { 031 this.name = name; 032 } 033 034 @Override 035 public String getName() { 036 return name; 037 } 038 039 @Override 040 public String toString() { 041 return name; 042 } 043 044 @Override 045 public boolean equals(final Object o) { 046 if (o instanceof DelegatedHeaderPrincipal) { 047 return ((DelegatedHeaderPrincipal) o).getName().equals( 048 this.getName()); 049 } 050 return false; 051 } 052 053 @Override 054 public int hashCode() { 055 if (name == null) { 056 return 0; 057 } 058 return name.hashCode(); 059 } 060 061 } 062 063 /** 064 * Default Constructor 065 */ 066 public DelegateHeaderPrincipalProvider() { 067 super(); 068 setHeaderName(DELEGATE_HEADER); 069 setSeparator(SEP); 070 } 071 072 /** 073 * @param request from which the principal header is extracted 074 * @return null if no delegate found, and the delegate if one found 075 * @throws RepositoryConfigurationException if more than one delegate found 076 */ 077 public Principal getDelegate(final HttpServletRequest request) { 078 final Set<Principal> principals = getPrincipals(request); 079 // No delegate 080 if (principals.size() == 0) { 081 return null; 082 } 083 084 // One delegate 085 if (principals.size() == 1) { 086 return principals.iterator().next(); 087 } 088 089 throw new RepositoryConfigurationException("Too many delegates! " + principals); 090 } 091 092 @Override 093 protected Principal createPrincipal(final String name) { 094 return new DelegatedHeaderPrincipal(name.trim()); 095 } 096 097}