Package com.evasion.sam

Source Code of com.evasion.sam.MyCBH

package com.evasion.sam;

import java.io.IOException;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import sun.misc.BASE64Decoder;

/**
* CallbackHandler to parse the HTTP Authorization header in order to get the username and password,
* @author nasradu8
*/
class MyCBH implements CallbackHandler {

    private HttpServletRequest request = null;

    public MyCBH(HttpServletRequest request, HttpServletResponse response) {
        this.request = request;
    }

    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }

    public MyCBH() {
    }

    @Override
    public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
        String username = null;
        String password = null;
        String authorization = request.getHeader("authorization");
        //Get credentials from authourization header.
        if (authorization != null
                && authorization.toLowerCase().startsWith("basic ")) {
            authorization = authorization.substring(6).trim();
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] bs = decoder.decodeBuffer(authorization);
            String decodedString = new String(bs);
            int ind = decodedString.indexOf(':');
            if (ind > 0) {
                username = decodedString.substring(0, ind);
                password = decodedString.substring(ind + 1);
            }
        } else if (authorization ==null) {
            username = request.getParameter(Constants.USERNAME_PARAMETER);
            password = request.getParameter(Constants.PASSWORD_PARAMETER);
        }
        for (Callback callback : callbacks) {
            if (callback instanceof NameCallback) {
                ((NameCallback) callback).setName(username);
                continue;
            } else if (callback instanceof PasswordCallback) {
                ((PasswordCallback) callback).setPassword((password != null)
                        ? password.toCharArray() : null);
                continue;
            } else {
                throw new UnsupportedCallbackException(callback);
            }
        }
    }
}
TOP

Related Classes of com.evasion.sam.MyCBH

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.