com.sector91.wit.http.BasicAuthInterceptor.java Source code

Java tutorial

Introduction

Here is the source code for com.sector91.wit.http.BasicAuthInterceptor.java

Source

// ~~~~~~~~~~~~~~~~~~~~~~~~~~ //

////   ///   /// ///       
//////  ////   // ////  //// 
/// ////  ////  //  ////  //// 
///  //// /////  //        ///  
///  //// ///// //  //// ////// 
//   /// /////  //  ////  ////  
// //// ///// //  ////  ////   
/////////////  ////  ////   
////////////   ///   ///    
///// /////   ////  ////    
///// /////   //// ///// // 
////  ////    /// ///// //  
///// /////   ////////////   
////  ////     ////  ////    

// The Web framework with class.

// ~~~~~~~~~~~~~~~~~~~~~~~~~~ //

// Copyright (c) 2013 Adam R. Nelson
//
// 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.

package com.sector91.wit.http;

import org.simpleframework.http.Request;
import org.simpleframework.http.Response;
import org.simpleframework.http.Status;

import com.google.common.base.Charsets;
import com.google.common.io.BaseEncoding;
import com.google.common.net.HttpHeaders;
import com.sector91.wit.Interceptor;

public class BasicAuthInterceptor implements Interceptor {

    private static final String PREFIX = "Basic";

    final String realm;
    private final Authenticator authenticator;

    public BasicAuthInterceptor(String realm, Authenticator provider) {
        this.realm = realm;
        this.authenticator = provider;
    }

    @Override
    public void intercept(Request request, Response response) throws HttpException {
        final String auth = request.getValue(HttpHeaders.AUTHORIZATION);
        try {
            if (auth.startsWith(PREFIX)) {
                final String b64 = auth.split("\\s+")[1];
                final String parsed = new String(BaseEncoding.base64().decode(b64), Charsets.UTF_8);
                final String[] parts = parsed.split("[:]");
                if (!authenticator.auth(parts[0], parts[1]))
                    throw new HttpException(Status.UNAUTHORIZED).withHeader(HttpHeaders.WWW_AUTHENTICATE,
                            "Basic realm=\"" + realm + "\"");
            }
        } catch (RuntimeException ex) {
        }
    }
}