001/* 002 * Copyright 2011-2016 UnboundID Corp. 003 * 004 * This program is free software; you can redistribute it and/or modify 005 * it under the terms of the GNU General Public License (GPLv2 only) 006 * or the terms of the GNU Lesser General Public License (LGPLv2.1 only) 007 * as published by the Free Software Foundation. 008 * 009 * This program is distributed in the hope that it will be useful, 010 * but WITHOUT ANY WARRANTY; without even the implied warranty of 011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 012 * GNU General Public License for more details. 013 * 014 * You should have received a copy of the GNU General Public License 015 * along with this program; if not, see <http://www.gnu.org/licenses>. 016 */ 017 018package com.unboundid.scim.sdk; 019 020import org.apache.wink.client.ClientRequest; 021import org.apache.wink.client.ClientResponse; 022import org.apache.wink.client.handlers.ClientHandler; 023import org.apache.wink.client.handlers.HandlerContext; 024 025import javax.xml.bind.DatatypeConverter; 026import java.io.UnsupportedEncodingException; 027 028 029/** 030 * This class provides HTTP Basic Authentication handling. 031 */ 032public class HttpBasicAuthSecurityHandler implements ClientHandler 033{ 034 035 private volatile String encodedCredentials; 036 037 /** 038 * Constructs a fully initialized Security handler. 039 * @param username The Consumer username. 040 * @param password The Consumer password. 041 */ 042 public HttpBasicAuthSecurityHandler(final String username, 043 final String password) 044 { 045 String encoded = null; 046 try 047 { 048 encoded = DatatypeConverter.printBase64Binary( 049 (username + ":" + password).getBytes("UTF-8")); 050 } 051 catch(UnsupportedEncodingException e) 052 { 053 //UTF-8 is pretty standard, so this should not happen. 054 throw new IllegalArgumentException(e.getMessage()); 055 } 056 this.encodedCredentials = "Basic " + encoded; 057 } 058 059 /** 060 * Attempts to authenticate a Consumer via Http Basic. 061 * 062 * @param request The Client Resource request. 063 * @param context The provided handler chain. 064 * @return Client Response that may indicate success or failure. 065 * @throws Exception Thrown if error handling authentication. 066 */ 067 public ClientResponse handle(final ClientRequest request, 068 final HandlerContext context) throws Exception 069 { 070 request.getHeaders().putSingle("Authorization", this.encodedCredentials); 071 return null; 072 } 073}