Example usage for javax.security.auth Subject doAs

List of usage examples for javax.security.auth Subject doAs

Introduction

In this page you can find the example usage for javax.security.auth Subject doAs.

Prototype

public static <T> T doAs(final Subject subject, final java.security.PrivilegedExceptionAction<T> action)
        throws java.security.PrivilegedActionException 

Source Link

Document

Perform work as a particular Subject .

Usage

From source file:com.flipkart.fdp.migration.distcp.security.KerberosAuthenticator2.java

/**
 * Implements the SPNEGO authentication sequence interaction using the
 * current default principal in the Kerberos cache (normally set via kinit).
 * //from w  ww .ja  va2 s. co m
 * @param token
 *            the authentication token being used for the user.
 * 
 * @throws IOException
 *             if an IO error occurred.
 * @throws AuthenticationException
 *             if an authentication error occurred.
 */
private void doSpnegoSequence(AuthenticatedURL.Token token) throws IOException, AuthenticationException {
    try {

        /*
         * // AccessControlContext context = AccessController.getContext();
         * Subject subject = Subject.getSubject(context); if (subject ==
         * null) { subject = new Subject(); LoginContext login = new
         * LoginContext("", subject, null, new KerberosConfiguration());
         * login.login(); }
         */

        LoginContext loginContext = new LoginContext("", null,
                new KerberosClientCallbackHandler(username, password), new LoginConfig(this.debug));
        loginContext.login();
        // if (LOG.isDebugEnabled()) {
        // LOG.debug("Kerberos authenticated user: "
        // + loginContext.getSubject());
        // }
        Subject subject = loginContext.getSubject();

        Subject.doAs(subject, new PrivilegedExceptionAction<Void>() {

            public Void run() throws Exception {
                GSSContext gssContext = null;
                try {
                    GSSManager gssManager = GSSManager.getInstance();
                    Oid oid = KerberosUtil.getOidInstance("NT_GSS_KRB5_PRINCIPAL");
                    String sp = KerberosAuthenticator2.this.servicePrincipal;
                    if (sp == null) {
                        sp = "HTTP/" + KerberosAuthenticator2.this.url.getHost();
                    }
                    GSSName serviceName = gssManager.createName(sp, oid);
                    oid = KerberosUtil.getOidInstance("GSS_KRB5_MECH_OID");
                    gssContext = gssManager.createContext(serviceName, oid, null, GSSContext.DEFAULT_LIFETIME);
                    gssContext.requestCredDeleg(true);
                    gssContext.requestMutualAuth(true);

                    byte[] inToken = new byte[0];
                    byte[] outToken;
                    boolean established = false;

                    // Loop while the context is still not established
                    while (!established) {
                        outToken = gssContext.initSecContext(inToken, 0, inToken.length);
                        if (outToken != null) {
                            sendToken(outToken);
                        }

                        if (!gssContext.isEstablished()) {
                            inToken = readToken();
                        } else {
                            established = true;
                        }
                    }
                } finally {
                    if (gssContext != null) {
                        gssContext.dispose();
                        gssContext = null;
                    }
                }
                return null;
            }
        });
    } catch (PrivilegedActionException ex) {
        throw new AuthenticationException(ex.getException());
    } catch (LoginException ex) {
        throw new AuthenticationException(ex);
    }
    AuthenticatedURL.extractToken(conn, token);
}

From source file:main.client.http.KerberosAuthenticator2.java

/**
 * Implements the SPNEGO authentication sequence interaction using the
 * current default principal in the Kerberos cache (normally set via kinit).
 * /*from  w w  w .j  av a  2 s.  c  o  m*/
 * @param token
 *            the authentication token being used for the user.
 * 
 * @throws IOException
 *             if an IO error occurred.
 * @throws AuthenticationException
 *             if an authentication error occurred.
 */
private void doSpnegoSequence(AuthenticatedURL.Token token) throws IOException, AuthenticationException {
    try {

        /*      //   
                   AccessControlContext context = AccessController.getContext();
                 Subject subject = Subject.getSubject(context);
                 if (subject == null) {
                    subject = new Subject();
                    LoginContext login = new LoginContext("", subject, null,
          new KerberosConfiguration());
                    login.login();
                 }
        */

        LoginContext loginContext = new LoginContext("", null,
                new KerberosClientCallbackHandler(username, password), new LoginConfig(this.debug));
        loginContext.login();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Kerberos authenticated user: " + loginContext.getSubject());
        }
        Subject subject = loginContext.getSubject();

        Subject.doAs(subject, new PrivilegedExceptionAction<Void>() {

            @Override
            public Void run() throws Exception {
                GSSContext gssContext = null;
                try {
                    GSSManager gssManager = GSSManager.getInstance();
                    String servicePrincipal = "HTTP/" + KerberosAuthenticator2.this.url.getHost();
                    Oid oid = KerberosUtil.getOidInstance("NT_GSS_KRB5_PRINCIPAL");
                    GSSName serviceName = gssManager.createName(servicePrincipal, oid);
                    oid = KerberosUtil.getOidInstance("GSS_KRB5_MECH_OID");
                    gssContext = gssManager.createContext(serviceName, oid, null, GSSContext.DEFAULT_LIFETIME);
                    gssContext.requestCredDeleg(true);
                    gssContext.requestMutualAuth(true);

                    byte[] inToken = new byte[0];
                    byte[] outToken;
                    boolean established = false;

                    // Loop while the context is still not established
                    while (!established) {
                        outToken = gssContext.initSecContext(inToken, 0, inToken.length);
                        if (outToken != null) {
                            sendToken(outToken);
                        }

                        if (!gssContext.isEstablished()) {
                            inToken = readToken();
                        } else {
                            established = true;
                        }
                    }
                } finally {
                    if (gssContext != null) {
                        gssContext.dispose();
                        gssContext = null;
                    }
                }
                return null;
            }
        });
    } catch (PrivilegedActionException ex) {
        throw new AuthenticationException(ex.getException());
    } catch (LoginException ex) {
        throw new AuthenticationException(ex);
    }
    AuthenticatedURL.extractToken(conn, token);
}

From source file:org.springframework.security.kerberos.client.KerberosRestTemplate.java

@Override
protected final <T> T doExecute(final URI url, final HttpMethod method, final RequestCallback requestCallback,
        final ResponseExtractor<T> responseExtractor) throws RestClientException {

    try {/*from  w ww .ja  v  a  2s  .  com*/
        LoginContext lc = buildLoginContext();
        lc.login();
        Subject serviceSubject = lc.getSubject();
        return Subject.doAs(serviceSubject, new PrivilegedAction<T>() {

            @Override
            public T run() {
                return KerberosRestTemplate.this.doExecuteSubject(url, method, requestCallback,
                        responseExtractor);
            }
        });

    } catch (Exception e) {
        throw new RestClientException("Error running rest call", e);
    }
}

From source file:ca.nrc.cadc.web.SearchJobServlet.java

/**
 * Called by the server (via the <code>service</code> method)
 * to allow a servlet to handle a POST request.
 *
 * The HTTP POST method allows the client to send
 * data of unlimited length to the Web server a single time
 * and is useful when posting information such as
 * credit card numbers.//from   ww  w  .  j  av a2 s .c  o m
 *
 *When overriding this method, read the request data,
 * write the response headers, get the response's writer or output
 * stream object, and finally, write the response data. It's best
 * to include content type and encoding. When using a
 * <code>PrintWriter</code> object to return the response, set the
 * content type before accessing the <code>PrintWriter</code> object.
 *
 *The servlet container must write the headers before committing the
 * response, because in HTTP the headers must be sent before the
 * response body.
 *
 *Where possible, set the Content-Length header (with the
 * {@link ServletResponse#setContentLength} method),
 * to allow the servlet container to use a persistent connection
 * to return its response to the client, improving performance.
 * The content length is automatically set if the entire response fits
 * inside the response buffer.
 *
 *When using HTTP 1.1 chunked encoding (which means that the response
 * has a Transfer-Encoding header), do not set the Content-Length header.
 *
 *This method does not need to be either safe or idempotent.
 * Operations requested through POST can have side effects for
 * which the user can be held accountable, for example,
 * updating stored data or buying items online.
 *
 *If the HTTP POST request is incorrectly formatted,
 * <code>doPost</code> returns an HTTP "Bad Request" message.
 *
 * @param request  an {@link HttpServletRequest} object that
 *                 contains the request the client has made
 *                 of the servlet
 * @param response an {@link HttpServletResponse} object that
 *                 contains the response the servlet sends
 *                 to the client
 * @throws IOException      if an input or output error is
 *                          detected when the servlet handles
 *                          the request
 * @throws ServletException if the request for the POST
 *                          could not be handled
 * @see ServletOutputStream
 * @see ServletResponse#setContentType
 */
@Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    try {
        final Subject subject = AuthenticationUtil.getSubject(request);

        if ((subject == null) || (subject.getPrincipals().isEmpty())) {
            processRequest(request, response);
        } else {
            Subject.doAs(subject, new PrivilegedExceptionAction<Object>() {
                @Override
                public Object run() throws Exception {
                    processRequest(request, response);
                    return null;
                }
            });
        }
    } catch (TransientException ex) {
        // OutputStream not open, write an error response
        response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        response.addHeader("Retry-After", Integer.toString(ex.getRetryDelay()));
        response.setContentType("text/plain");
        PrintWriter w = response.getWriter();
        w.println("failed to get or persist job state.");
        w.println("   reason: " + ex.getMessage());
        w.close();
    } catch (JobPersistenceException ex) {
        // OutputStream not open, write an error response
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentType("text/plain");
        PrintWriter w = response.getWriter();
        w.println("failed to get or persist job state.");
        w.println("   reason: " + ex.getMessage());
        w.close();
    } catch (Throwable t) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentType("text/plain");
        PrintWriter w = response.getWriter();
        w.println("Unable to proceed with job execution.\n");
        w.println("Reason: " + t.getMessage());
        w.close();
    }
}

From source file:org.apache.coheigea.cxf.kerberos.authentication.TokenPreAuthTest.java

@org.junit.Test
public void unitTokenAuthGSSTest() throws Exception {

    // 1. Get a TGT from the KDC for the client + create an armor cache
    KrbClient client = new KrbClient();

    client.setKdcHost("localhost");
    client.setKdcTcpPort(kerbyServer.getKdcPort());
    client.setAllowUdp(false);//  w  w w .  j  av a 2 s.  c o  m

    client.setKdcRealm(kerbyServer.getKdcSetting().getKdcRealm());
    client.init();

    TgtTicket tgt = client.requestTgt("alice@service.ws.apache.org", "alice");
    assertNotNull(tgt);

    // Write to cache
    Credential credential = new Credential(tgt);
    CredentialCache cCache = new CredentialCache();
    cCache.addCredential(credential);
    cCache.setPrimaryPrincipal(tgt.getClientPrincipal());

    File cCacheFile = File.createTempFile("krb5_alice@service.ws.apache.org", "cc");
    cCache.store(cCacheFile);

    // Now read in JAAS config + substitute in the armor cache file path value
    String basedir = System.getProperty("basedir");
    if (basedir == null) {
        basedir = new File(".").getCanonicalPath();
    }
    File f = new File(basedir + "/target/test-classes/kerberos/kerberos.jaas");

    FileInputStream inputStream = new FileInputStream(f);
    String content = IOUtils.toString(inputStream, "UTF-8");
    inputStream.close();
    content = content.replaceAll("armorCacheVal", cCacheFile.getPath());

    File f2 = new File(basedir + "/target/test-classes/kerberos/kerberos.jaas");
    FileOutputStream outputStream = new FileOutputStream(f2);
    IOUtils.write(content, outputStream, "UTF-8");
    outputStream.close();

    // 2. Create a JWT token using CXF
    JwtClaims claims = new JwtClaims();
    claims.setSubject("alice");
    claims.setIssuer("DoubleItSTSIssuer");
    claims.setIssuedAt(new Date().getTime() / 1000L);
    claims.setExpiryTime(new Date().getTime() + (60L + 1000L));
    String address = "krbtgt/service.ws.apache.org@service.ws.apache.org";
    claims.setAudiences(Collections.singletonList(address));

    KeyStore keystore = KeyStore.getInstance("JKS");
    keystore.load(Loader.getResourceAsStream("clientstore.jks"), "cspass".toCharArray());

    Properties signingProperties = new Properties();
    signingProperties.put(JoseConstants.RSSEC_SIGNATURE_ALGORITHM, SignatureAlgorithm.RS256.name());
    signingProperties.put(JoseConstants.RSSEC_KEY_STORE, keystore);
    signingProperties.put(JoseConstants.RSSEC_KEY_STORE_ALIAS, "myclientkey");
    signingProperties.put(JoseConstants.RSSEC_KEY_PSWD, "ckpass");

    JwsHeaders jwsHeaders = new JwsHeaders(signingProperties);
    JwsJwtCompactProducer jws = new JwsJwtCompactProducer(jwsHeaders, claims);

    JwsSignatureProvider sigProvider = JwsUtils.loadSignatureProvider(signingProperties, jwsHeaders);

    String signedToken = jws.signWith(sigProvider);

    // Store the JWT token in the token cache
    File tokenCache = new File(basedir + "/target/tokencache.txt");
    if (!tokenCache.exists()) {
        tokenCache.createNewFile();
    }
    TokenCache.writeToken(signedToken, tokenCache.getPath());

    // 3. Now log in using JAAS
    LoginContext loginContext = new LoginContext("aliceTokenAuth", new KerberosCallbackHandler());
    loginContext.login();

    Subject clientSubject = loginContext.getSubject();
    //Set<Principal> clientPrincipals = clientSubject.getPrincipals();
    //assertFalse(clientPrincipals.isEmpty());

    // Get the TGT
    Set<KerberosTicket> privateCredentials = clientSubject.getPrivateCredentials(KerberosTicket.class);
    assertFalse(privateCredentials.isEmpty());

    // Get the service ticket using GSS
    KerberosClientExceptionAction action = new KerberosClientExceptionAction(
            new KerberosPrincipal("alice@service.ws.apache.org"), "bob@service.ws.apache.org");
    byte[] ticket = (byte[]) Subject.doAs(clientSubject, action);
    assertNotNull(ticket);

    loginContext.logout();

    validateServiceTicket(ticket);

    cCacheFile.delete();
    tokenCache.delete();
}

From source file:org.apache.hadoop.hbase.thrift.TestThriftSpnegoHttpServer.java

private CloseableHttpClient createHttpClient() throws Exception {
    final Subject clientSubject = JaasKrbUtil.loginUsingKeytab(clientPrincipal, clientKeytab);
    final Set<Principal> clientPrincipals = clientSubject.getPrincipals();
    // Make sure the subject has a principal
    assertFalse(clientPrincipals.isEmpty());

    // Get a TGT for the subject (might have many, different encryption types). The first should
    // be the default encryption type.
    Set<KerberosTicket> privateCredentials = clientSubject.getPrivateCredentials(KerberosTicket.class);
    assertFalse(privateCredentials.isEmpty());
    KerberosTicket tgt = privateCredentials.iterator().next();
    assertNotNull(tgt);// www  .j ava 2  s . c  o  m

    // The name of the principal
    final String clientPrincipalName = clientPrincipals.iterator().next().getName();

    return Subject.doAs(clientSubject, new PrivilegedExceptionAction<CloseableHttpClient>() {
        @Override
        public CloseableHttpClient run() throws Exception {
            // Logs in with Kerberos via GSS
            GSSManager gssManager = GSSManager.getInstance();
            // jGSS Kerberos login constant
            Oid oid = new Oid("1.2.840.113554.1.2.2");
            GSSName gssClient = gssManager.createName(clientPrincipalName, GSSName.NT_USER_NAME);
            GSSCredential credential = gssManager.createCredential(gssClient, GSSCredential.DEFAULT_LIFETIME,
                    oid, GSSCredential.INITIATE_ONLY);

            Lookup<AuthSchemeProvider> authRegistry = RegistryBuilder.<AuthSchemeProvider>create()
                    .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, true)).build();

            BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY, new KerberosCredentials(credential));

            return HttpClients.custom().setDefaultAuthSchemeRegistry(authRegistry)
                    .setDefaultCredentialsProvider(credentialsProvider).build();
        }
    });
}

From source file:com.example.ManualSpnegoNegotiateServlet.java

/**
 * Use of Kerberos is wrapped in an HTTP auth-scheme of "Negotiate" [RFC 4559].
 *
 * The auth-params exchanged use data formats defined for use with the GSS-API [RFC 2743]. In particular, they follow the formats set for the SPNEGO [RFC 4178] and
 * Kerberos [RFC 4121] mechanisms for GSSAPI. The "Negotiate" auth-scheme calls for the use of SPNEGO GSSAPI tokens that the specific mechanism type specifies.
 *
 * The current implementation of this protocol is limited to the use of SPNEGO with the Kerberos protocol.
 *
 * @param request//from w w  w. j a va 2 s .c om
 * @param response
 * @throws ServletException
 *
 * @return true upon successful authentication, false otherwise
 */
protected boolean attemptNegotiation(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, UnsupportedEncodingException, IOException {
    log.debug("Attempting negotiation.");

    String header = request.getHeader("Authorization");

    /**
     * Guard clause to check for Negotiate header.
     *
     * If the server receives a request for an access-protected object, and if an acceptable Authorization header has not been sent, the server responds with a "401
     * Unauthorized" status code, and a "WWW-Authenticate:" header as per the framework described in [RFC 2616]. The initial WWW-Authenticate header will not carry
     * any gssapi-data.
     */
    if (header == null || header.length() < 10 || !header.startsWith("Negotiate ")) {
        response.setHeader("WWW-Authenticate", "Negotiate");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        log.debug("Proper authorization header not found, returning challenge.");
        return false;
    }

    /**
     * A client may initiate a connection to the server with an "Authorization" header containing the initial token for the server. This form will bypass the initial
     * 401 error from the server when the client knows that the server will accept the Negotiate HTTP authentication type.
     */
    log.debug("Authorization header found, continuing negotiation.");

    /**
     * The data following the word Negotiate is the GSS-API data to process.
     */
    byte gssapiData[] = Base64.decode(header.substring(10));

    log.debug("GSS API data: " + Arrays.toString(gssapiData));

    /**
     * Guard clause to check for the unsupported NTLM authentication mechanism.
     */
    if (isNtlmMechanism(gssapiData)) {
        log.warn("Got request for unsupported NTLM mechanism, aborting negotiation.");
        return false;
    }

    /**
     * The server attempts to establish a security context. Establishment may result in tokens that the server must return to the client. Tokens are BASE-64 encoded
     * GSS-API data.
     */
    GSSContext gssContext = null;
    LoginContext loginContext = null;
    String outToken = null;

    try {
        final String domainUsername = "Zeus";
        final String domainUserPassword = "Z3usP@55";
        final CallbackHandler handler = SpnegoProvider.getUsernamePasswordHandler(domainUsername,
                domainUserPassword);

        loginContext = new LoginContext("spnego-server", handler);
        loginContext.login();
        Subject subject = loginContext.getSubject();

        Oid spnegoOid = new Oid("1.3.6.1.5.5.2"); // for spnego answers
        Oid kerbv5Oid = new Oid("1.2.840.113554.1.2.2"); // for chromium (they send a kerbv5 token instead of spnego)
        final Oid[] oids = new Oid[] { spnegoOid, kerbv5Oid };

        final GSSManager manager = GSSManager.getInstance();
        final PrivilegedExceptionAction<GSSCredential> action = new PrivilegedExceptionAction<GSSCredential>() {
            public GSSCredential run() throws GSSException {
                return manager.createCredential(null, GSSCredential.INDEFINITE_LIFETIME, oids,
                        GSSCredential.ACCEPT_ONLY);
            }
        };

        GSSCredential serverCreds = Subject.doAs(subject, action);

        log.debug("Mechs: " + Arrays.toString(serverCreds.getMechs()));

        gssContext = manager.createContext(serverCreds);

        log.debug("Context created. " + gssContext);

        byte tokenBytes[] = gssContext.acceptSecContext(gssapiData, 0, gssapiData.length);
        outToken = Base64.encode(tokenBytes);
    } catch (PrivilegedActionException ex) {
        log.error("", ex);
    } catch (LoginException ex) {
        log.error("", ex);
    } catch (GSSException gsse) {
        gsse.printStackTrace();
        log.error("GSSException:       " + gsse.getMessage());
        log.error("GSSException major: " + gsse.getMajorString());
        log.error("GSSException minor: " + gsse.getMinorString());
        throw new ServletException(gsse);
    }

    /**
     * If the context is established, we can attempt to retrieve the name of the "context initiator." In the case of the Kerberos mechanism, the context initiator is
     * the Kerberos principal of the client. Additionally, the client may be delegating credentials.
     */
    if (gssContext != null && gssContext.isEstablished()) {
        log.debug("Context established, attempting Kerberos principal retrieval.");

        try {
            Subject subject = new Subject();
            GSSName clientGSSName = gssContext.getSrcName();
            KerberosPrincipal clientPrincipal = new KerberosPrincipal(clientGSSName.toString());
            subject.getPrincipals().add(clientPrincipal);
            log.info("Got client Kerberos principal: " + clientGSSName);
            response.getWriter().println("Hello, " + clientPrincipal);

            /**
             * Retrieve LogonInfo (for example, GroupSIDs) from the PAC Authorization Data
             * from a Kerberos Ticket that was issued by Active Directory.
             */
            byte[] kerberosTokenData = gssapiData;
            try {
                SpnegoToken token = SpnegoToken.parse(gssapiData);
                kerberosTokenData = token.getMechanismToken();
            } catch (DecodingException dex) {
                // Chromium bug: sends a Kerberos response instead of an spnego response with a Kerberos mechanism
            } catch (Exception ex) {
                log.error("", ex);
            }

            try {
                Object[] keyObjs = IteratorUtils
                        .toArray(loginContext.getSubject().getPrivateCredentials(KerberosKey.class).iterator());
                KerberosKey[] keys = new KerberosKey[keyObjs.length];
                System.arraycopy(keyObjs, 0, keys, 0, keyObjs.length);

                KerberosToken token = new KerberosToken(kerberosTokenData, keys);
                log.info("Authorizations: ");
                for (KerberosAuthData authData : token.getTicket().getEncData().getUserAuthorizations()) {
                    if (authData instanceof KerberosPacAuthData) {
                        PacSid[] groupSIDs = ((KerberosPacAuthData) authData).getPac().getLogonInfo()
                                .getGroupSids();
                        log.info("GroupSids: " + Arrays.toString(groupSIDs));
                        response.getWriter().println("Found group SIDs: " + Arrays.toString(groupSIDs));
                    } else {
                        log.info("AuthData without PAC: " + authData.toString());
                    }
                }
            } catch (Exception ex) {
                log.error("", ex);
            }

            if (gssContext.getCredDelegState()) {
                GSSCredential delegateCredential = gssContext.getDelegCred();
                GSSName delegateGSSName = delegateCredential.getName();
                Principal delegatePrincipal = new KerberosPrincipal(delegateGSSName.toString());
                subject.getPrincipals().add(delegatePrincipal);
                subject.getPrivateCredentials().add(delegateCredential);
                log.info("Got delegated Kerberos principal: " + delegateGSSName);
            }

            /**
             * A status code 200 status response can also carry a "WWW-Authenticate" response header containing the final leg of an authentication. In this case, the
             * gssapi-data will be present.
             */
            if (outToken != null && outToken.length() > 0) {
                response.setHeader("WWW-Authenticate", "Negotiate " + outToken.getBytes());
                response.setStatus(HttpServletResponse.SC_OK);
                log.debug("Returning final authentication data to client to complete context.");
                log.debug("Negotiation completed.");
                return true;
            }
        } catch (GSSException gsse) {
            log.error("GSSException:       " + gsse.getMessage());
            log.error("GSSException major: " + gsse.getMajorString());
            log.error("GSSException minor: " + gsse.getMinorString());

            response.addHeader("Client-Warning", gsse.getMessage());
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        }
    } else {
        /**
         * Any returned code other than a success 2xx code represents an authentication error. If a 401 containing a "WWW-Authenticate" header with "Negotiate" and
         * gssapi-data is returned from the server, it is a continuation of the authentication request.
         */
        if (outToken != null && outToken.length() > 0) {
            response.setHeader("WWW-Authenticate", "Negotiate " + outToken.getBytes());
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            log.debug("Additional authentication processing required, returning token.");
            return false;
        } else {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            log.warn("Kerberos negotiation failed.");
        }
    }

    log.debug("Negotiation completed.");

    return true;
}

From source file:org.apache.qpid.server.management.plugin.servlet.rest.AbstractServlet.java

protected void authoriseManagement(HttpServletRequest request, Subject subject) {
    // TODO: We should eliminate SecurityManager.setThreadSubject in favour of Subject.doAs
    SecurityManager.setThreadSubject(subject); // Required for accessManagement check
    LogActor actor = createHttpManagementActor(request);
    CurrentActor.set(actor);/* w  w  w  . j  av  a  2s .c  om*/
    try {
        try {
            Subject.doAs(subject, new PrivilegedExceptionAction<Void>() // Required for proper logging of Subject
            {
                @Override
                public Void run() throws Exception {
                    boolean allowed = getSecurityManager().accessManagement();
                    if (!allowed) {
                        throw new AccessControlException("User is not authorised for management");
                    }
                    return null;
                }
            });
        } catch (PrivilegedActionException e) {
            throw new RuntimeException("Unable to perform access check", e);
        }
    } finally {
        try {
            CurrentActor.remove();
        } finally {
            SecurityManager.setThreadSubject(null);
        }
    }
}

From source file:org.apache.zeppelin.realm.kerberos.KerberosRealm.java

/**
 * Initializes the KerberosRealm by 'kinit'ing using principal and keytab.
 * <p>/*from w w  w.  j  a  v a  2  s.  c om*/
 * It creates a Kerberos context using the principal and keytab specified in
 * the Shiro configuration.
 * <p>
 * This method should be called only once.
 *
 * @throws RuntimeException thrown if the handler could not be initialized.
 */
@Override
protected void onInit() {
    super.onInit();
    config = getConfiguration();
    try {
        if (principal == null || principal.trim().length() == 0) {
            throw new RuntimeException("Principal not defined in configuration");
        }

        if (keytab == null || keytab.trim().length() == 0) {
            throw new RuntimeException("Keytab not defined in configuration");
        }

        File keytabFile = new File(keytab);
        if (!keytabFile.exists()) {
            throw new RuntimeException("Keytab file does not exist: " + keytab);
        }

        // use all SPNEGO principals in the keytab if a principal isn't
        // specifically configured
        final String[] spnegoPrincipals;
        if (principal.equals("*")) {
            spnegoPrincipals = KerberosUtil.getPrincipalNames(keytab, Pattern.compile("HTTP/.*"));
            if (spnegoPrincipals.length == 0) {
                throw new RuntimeException("Principals do not exist in the keytab");
            }
        } else {
            spnegoPrincipals = new String[] { principal };
        }
        KeyTab keytabInstance = KeyTab.getInstance(keytabFile);

        serverSubject = new Subject();
        serverSubject.getPrivateCredentials().add(keytabInstance);
        for (String spnegoPrincipal : spnegoPrincipals) {
            Principal krbPrincipal = new KerberosPrincipal(spnegoPrincipal);
            LOG.info("Using keytab {}, for principal {}", keytab, krbPrincipal);
            serverSubject.getPrincipals().add(krbPrincipal);
        }

        if (nameRules == null || nameRules.trim().length() == 0) {
            LOG.warn("No auth_to_local rules defined, DEFAULT will be used.");
            nameRules = "DEFAULT";
        }

        KerberosName.setRules(nameRules);

        if (null == gssManager) {
            try {
                gssManager = Subject.doAs(serverSubject, new PrivilegedExceptionAction<GSSManager>() {
                    @Override
                    public GSSManager run() {
                        return GSSManager.getInstance();
                    }
                });
                LOG.trace("SPNEGO gssManager initialized.");
            } catch (PrivilegedActionException ex) {
                throw ex.getException();
            }
        }

        if (null == signer) {
            initializeSecretProvider();
        }

        Configuration hadoopConfig = new Configuration();
        hadoopGroups = new Groups(hadoopConfig);

    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}