Java Code Examples for org.ietf.jgss.GSSManager#getInstance()

The following examples show how to use org.ietf.jgss.GSSManager#getInstance() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LifeTimeInSeconds.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    new OneKDC(null).writeJAASConf();
    System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");

    GSSManager gm = GSSManager.getInstance();
    GSSCredential cred = gm.createCredential(GSSCredential.INITIATE_AND_ACCEPT);
    int time = cred.getRemainingLifetime();
    int time2 = cred.getRemainingInitLifetime(null);
    // The test KDC issues a TGT with a default lifetime of 11 hours
    int elevenhrs = KDC.DEFAULT_LIFETIME;
    if (time > elevenhrs+60 || time < elevenhrs-60) {
        throw new Exception("getRemainingLifetime returns wrong value.");
    }
    if (time2 > elevenhrs+60 || time2 < elevenhrs-60) {
        throw new Exception("getRemainingInitLifetime returns wrong value.");
    }
}
 
Example 2
Source File: LifeTimeInSeconds.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    new OneKDC(null).writeJAASConf();
    System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");

    GSSManager gm = GSSManager.getInstance();
    GSSCredential cred = gm.createCredential(GSSCredential.INITIATE_AND_ACCEPT);
    int time = cred.getRemainingLifetime();
    int time2 = cred.getRemainingInitLifetime(null);
    // The test KDC issues a TGT with a default lifetime of 11 hours
    int elevenhrs = 11*3600;
    if (time > elevenhrs+60 || time < elevenhrs-60) {
        throw new Exception("getRemainingLifetime returns wrong value.");
    }
    if (time2 > elevenhrs+60 || time2 < elevenhrs-60) {
        throw new Exception("getRemainingInitLifetime returns wrong value.");
    }
}
 
Example 3
Source File: CrossRealm.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
static void xRealmAuth() throws Exception {
    Security.setProperty("auth.login.defaultCallbackHandler", "CrossRealm");
    System.setProperty("java.security.auth.login.config", "jaas-localkdc.conf");
    System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");
    FileOutputStream fos = new FileOutputStream("jaas-localkdc.conf");
    fos.write(("com.sun.security.jgss.krb5.initiate {\n" +
            "    com.sun.security.auth.module.Krb5LoginModule\n" +
            "    required\n" +
            "    principal=dummy\n" +
            "    doNotPrompt=false\n" +
            "    useTicketCache=false\n" +
            "    ;\n" +
            "};").getBytes());
    fos.close();

    GSSManager m = GSSManager.getInstance();
    m.createContext(
            m.createName("[email protected]", GSSName.NT_HOSTBASED_SERVICE),
            GSSUtil.GSS_KRB5_MECH_OID,
            null,
            GSSContext.DEFAULT_LIFETIME).initSecContext(new byte[0], 0, 0);
}
 
Example 4
Source File: LifeTimeInSeconds.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    new OneKDC(null).writeJAASConf();
    System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");

    GSSManager gm = GSSManager.getInstance();
    GSSCredential cred = gm.createCredential(GSSCredential.INITIATE_AND_ACCEPT);
    int time = cred.getRemainingLifetime();
    int time2 = cred.getRemainingInitLifetime(null);
    // The test KDC issues a TGT with a default lifetime of 11 hours
    int elevenhrs = 11*3600;
    if (time > elevenhrs+60 || time < elevenhrs-60) {
        throw new Exception("getRemainingLifetime returns wrong value.");
    }
    if (time2 > elevenhrs+60 || time2 < elevenhrs-60) {
        throw new Exception("getRemainingInitLifetime returns wrong value.");
    }
}
 
Example 5
Source File: LifeTimeInSeconds.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    new OneKDC(null).writeJAASConf();
    System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");

    GSSManager gm = GSSManager.getInstance();
    GSSCredential cred = gm.createCredential(GSSCredential.INITIATE_AND_ACCEPT);
    int time = cred.getRemainingLifetime();
    int time2 = cred.getRemainingInitLifetime(null);
    // The test KDC issues a TGT with a default lifetime of 11 hours
    int elevenhrs = KDC.DEFAULT_LIFETIME;
    if (time > elevenhrs+60 || time < elevenhrs-60) {
        throw new Exception("getRemainingLifetime returns wrong value.");
    }
    if (time2 > elevenhrs+60 || time2 < elevenhrs-60) {
        throw new Exception("getRemainingInitLifetime returns wrong value.");
    }
}
 
Example 6
Source File: LifeTimeInSeconds.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    new OneKDC(null).writeJAASConf();
    System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");

    GSSManager gm = GSSManager.getInstance();
    GSSCredential cred = gm.createCredential(GSSCredential.INITIATE_AND_ACCEPT);
    int time = cred.getRemainingLifetime();
    int time2 = cred.getRemainingInitLifetime(null);
    // The test KDC issues a TGT with a default lifetime of 11 hours
    int elevenhrs = 11*3600;
    if (time > elevenhrs+60 || time < elevenhrs-60) {
        throw new Exception("getRemainingLifetime returns wrong value.");
    }
    if (time2 > elevenhrs+60 || time2 < elevenhrs-60) {
        throw new Exception("getRemainingInitLifetime returns wrong value.");
    }
}
 
Example 7
Source File: CtorTests2.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] argv) throws Exception {
    try {
        GSSManager manager = GSSManager.getInstance();
        GSSName name = manager.createName("anonymous", GSSName.NT_ANONYMOUS);
        boolean anonymous = name.isAnonymous();
        if (anonymous == false) {
            throw new RuntimeException("GSSName.isAnonymous() returns false for GSSName.NT_ANONYMOUS");
        }
    } catch (GSSException e) {
        System.out.println("Not supported, ignored!");
    }
}
 
Example 8
Source File: HttpNegotiateServer.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public MyServerAuthenticator(boolean proxy, String scheme,
        String principal, String ktab) throws Exception {

    this.scheme = scheme;
    if (proxy) {
        reqHdr = "Proxy-Authenticate";
        respHdr = "Proxy-Authorization";
        err = HttpURLConnection.HTTP_PROXY_AUTH;
    }

    Krb5LoginModule krb5 = new Krb5LoginModule();
    Map<String, String> map = new HashMap<>();
    Map<String, Object> shared = new HashMap<>();

    map.put("storeKey", "true");
    map.put("isInitiator", "false");
    map.put("useKeyTab", "true");
    map.put("keyTab", ktab);
    map.put("principal", principal);
    krb5.initialize(s, null, shared, map);
    krb5.login();
    krb5.commit();
    m = GSSManager.getInstance();
    cred = Subject.doAs(s, new PrivilegedExceptionAction<GSSCredential>() {
        @Override
        public GSSCredential run() throws Exception {
            System.err.println("Creating GSSCredential");
            return m.createCredential(
                    null,
                    GSSCredential.INDEFINITE_LIFETIME,
                    MyServerAuthenticator.this.scheme.equalsIgnoreCase("Negotiate")?
                            GSSUtil.GSS_SPNEGO_MECH_OID:
                            GSSUtil.GSS_KRB5_MECH_OID,
                    GSSCredential.ACCEPT_ONLY);
        }
    });
}
 
Example 9
Source File: HttpNegotiateServer.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public MyServerAuthenticator(boolean proxy, String scheme,
        String principal, String ktab) throws Exception {

    this.scheme = scheme;
    if (proxy) {
        reqHdr = "Proxy-Authenticate";
        respHdr = "Proxy-Authorization";
        err = HttpURLConnection.HTTP_PROXY_AUTH;
    }

    Krb5LoginModule krb5 = new Krb5LoginModule();
    Map<String, String> map = new HashMap<>();
    Map<String, Object> shared = new HashMap<>();

    map.put("storeKey", "true");
    map.put("isInitiator", "false");
    map.put("useKeyTab", "true");
    map.put("keyTab", ktab);
    map.put("principal", principal);
    krb5.initialize(s, null, shared, map);
    krb5.login();
    krb5.commit();
    m = GSSManager.getInstance();
    cred = Subject.doAs(s, new PrivilegedExceptionAction<GSSCredential>() {
        @Override
        public GSSCredential run() throws Exception {
            System.err.println("Creating GSSCredential");
            return m.createCredential(
                    null,
                    GSSCredential.INDEFINITE_LIFETIME,
                    MyServerAuthenticator.this.scheme.equalsIgnoreCase("Negotiate")?
                            GSSUtil.GSS_SPNEGO_MECH_OID:
                            GSSUtil.GSS_KRB5_MECH_OID,
                    GSSCredential.ACCEPT_ONLY);
        }
    });
}
 
Example 10
Source File: GssMemoryIssues.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] argv) throws Exception {
    GSSManager man = GSSManager.getInstance();
    String s = "me@REALM";
    GSSName name = man.createName(s, GSSName.NT_USER_NAME);
    byte[] exported = name.export();
    // Offset of the length of the mech name. Length in big endian
    int lenOffset = exported.length - s.length() - 4;
    // Make it huge
    exported[lenOffset] = 0x7f;
    try {
        man.createName(exported, GSSName.NT_EXPORT_NAME);
    } catch (GSSException gsse) {
        System.out.println(gsse);
    }
}
 
Example 11
Source File: KerberosAuthenticationFilter.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected GSSContext createGSSContext() throws GSSException {
    boolean useKerberosOid = PropertyUtils.isTrue(
        messageContext.getContextualProperty(PROPERTY_USE_KERBEROS_OID));
    Oid oid = new Oid(useKerberosOid ? KERBEROS_OID : SPNEGO_OID);

    GSSManager gssManager = GSSManager.getInstance();

    String spn = getCompleteServicePrincipalName();
    GSSName gssService = gssManager.createName(spn, null);

    return gssManager.createContext(gssService.canonicalize(oid),
               oid, null, GSSContext.DEFAULT_LIFETIME);
}
 
Example 12
Source File: ServiceCredsCombination.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Checks the correct bound
 * @param a get a creds for this principal, null for default one
 * @param b expected name, null for still unbound, "NOCRED" for no creds
 * @param objs princs, keys and keytabs in the subject
 */
private static void check(final String a, String b, Object... objs)
        throws Exception {
    Subject subj = new Subject();
    for (Object obj: objs) {
        if (obj instanceof KerberosPrincipal) {
            subj.getPrincipals().add((KerberosPrincipal)obj);
        } else if (obj instanceof KerberosKey || obj instanceof KeyTab) {
            subj.getPrivateCredentials().add(obj);
        }
    }
    final GSSManager man = GSSManager.getInstance();
    try {
        String result = Subject.doAs(
                subj, new PrivilegedExceptionAction<String>() {
            @Override
            public String run() throws GSSException {
                GSSCredential cred = man.createCredential(
                        a == null ? null : man.createName(r(a), null),
                        GSSCredential.INDEFINITE_LIFETIME,
                        GSSUtil.GSS_KRB5_MECH_OID,
                        GSSCredential.ACCEPT_ONLY);
                GSSName name = cred.getName();
                return name == null ? null : name.toString();
            }
        });
        if (!Objects.equals(result, r(b))) {
            throw new Exception("Check failed: getInstance(" + a
                    + ") has name " + result + ", not " + b);
        }
    } catch (PrivilegedActionException e) {
        if (!"NOCRED".equals(b)) {
            throw new Exception("Check failed: getInstance(" + a
                    + ") is null " + ", but not one with name " + b);
        }
    }
}
 
Example 13
Source File: HttpNegotiateServer.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public MyServerAuthenticator(boolean proxy, String scheme,
        String principal, String ktab) throws Exception {

    this.scheme = scheme;
    if (proxy) {
        reqHdr = "Proxy-Authenticate";
        respHdr = "Proxy-Authorization";
        err = HttpURLConnection.HTTP_PROXY_AUTH;
    }

    Krb5LoginModule krb5 = new Krb5LoginModule();
    Map<String, String> map = new HashMap<>();
    Map<String, Object> shared = new HashMap<>();

    map.put("storeKey", "true");
    map.put("isInitiator", "false");
    map.put("useKeyTab", "true");
    map.put("keyTab", ktab);
    map.put("principal", principal);
    krb5.initialize(s, null, shared, map);
    krb5.login();
    krb5.commit();
    m = GSSManager.getInstance();
    cred = Subject.doAs(s, new PrivilegedExceptionAction<GSSCredential>() {
        @Override
        public GSSCredential run() throws Exception {
            System.err.println("Creating GSSCredential");
            return m.createCredential(
                    null,
                    GSSCredential.INDEFINITE_LIFETIME,
                    MyServerAuthenticator.this.scheme.equalsIgnoreCase("Negotiate")?
                            GSSUtil.GSS_SPNEGO_MECH_OID:
                            GSSUtil.GSS_KRB5_MECH_OID,
                    GSSCredential.ACCEPT_ONLY);
        }
    });
}
 
Example 14
Source File: HttpNegotiateServer.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
public MyServerAuthenticator(boolean proxy, String scheme,
        String principal, String ktab) throws Exception {

    this.scheme = scheme;
    if (proxy) {
        reqHdr = "Proxy-Authenticate";
        respHdr = "Proxy-Authorization";
        err = HttpURLConnection.HTTP_PROXY_AUTH;
    }

    Krb5LoginModule krb5 = new Krb5LoginModule();
    Map<String, String> map = new HashMap<>();
    Map<String, Object> shared = new HashMap<>();

    map.put("storeKey", "true");
    map.put("isInitiator", "false");
    map.put("useKeyTab", "true");
    map.put("keyTab", ktab);
    map.put("principal", principal);
    krb5.initialize(s, null, shared, map);
    krb5.login();
    krb5.commit();
    m = GSSManager.getInstance();
    cred = Subject.doAs(s, new PrivilegedExceptionAction<GSSCredential>() {
        @Override
        public GSSCredential run() throws Exception {
            System.err.println("Creating GSSCredential");
            return m.createCredential(
                    null,
                    GSSCredential.INDEFINITE_LIFETIME,
                    MyServerAuthenticator.this.scheme.equalsIgnoreCase("Negotiate")?
                            GSSUtil.GSS_SPNEGO_MECH_OID:
                            GSSUtil.GSS_KRB5_MECH_OID,
                    GSSCredential.ACCEPT_ONLY);
        }
    });
}
 
Example 15
Source File: ServiceCredsCombination.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Checks the correct bound
 * @param a get a creds for this principal, null for default one
 * @param b expected name, null for still unbound, "NOCRED" for no creds
 * @param objs princs, keys and keytabs in the subject
 */
private static void check(final String a, String b, Object... objs)
        throws Exception {
    Subject subj = new Subject();
    for (Object obj: objs) {
        if (obj instanceof KerberosPrincipal) {
            subj.getPrincipals().add((KerberosPrincipal)obj);
        } else if (obj instanceof KerberosKey || obj instanceof KeyTab) {
            subj.getPrivateCredentials().add(obj);
        }
    }
    final GSSManager man = GSSManager.getInstance();
    try {
        String result = Subject.doAs(
                subj, new PrivilegedExceptionAction<String>() {
            @Override
            public String run() throws GSSException {
                GSSCredential cred = man.createCredential(
                        a == null ? null : man.createName(r(a), null),
                        GSSCredential.INDEFINITE_LIFETIME,
                        GSSUtil.GSS_KRB5_MECH_OID,
                        GSSCredential.ACCEPT_ONLY);
                GSSName name = cred.getName();
                return name == null ? null : name.toString();
            }
        });
        if (!Objects.equals(result, r(b))) {
            throw new Exception("Check failed: getInstance(" + a
                    + ") has name " + result + ", not " + b);
        }
    } catch (PrivilegedActionException e) {
        if (!"NOCRED".equals(b)) {
            throw new Exception("Check failed: getInstance(" + a
                    + ") is null " + ", but not one with name " + b);
        }
    }
}
 
Example 16
Source File: ServiceCredsCombination.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Checks the correct bound
 * @param a get a creds for this principal, null for default one
 * @param b expected name, null for still unbound, "NOCRED" for no creds
 * @param objs princs, keys and keytabs in the subject
 */
private static void check(final String a, String b, Object... objs)
        throws Exception {
    Subject subj = new Subject();
    for (Object obj: objs) {
        if (obj instanceof KerberosPrincipal) {
            subj.getPrincipals().add((KerberosPrincipal)obj);
        } else if (obj instanceof KerberosKey || obj instanceof KeyTab) {
            subj.getPrivateCredentials().add(obj);
        }
    }
    final GSSManager man = GSSManager.getInstance();
    try {
        String result = Subject.doAs(
                subj, new PrivilegedExceptionAction<String>() {
            @Override
            public String run() throws GSSException {
                GSSCredential cred = man.createCredential(
                        a == null ? null : man.createName(r(a), null),
                        GSSCredential.INDEFINITE_LIFETIME,
                        GSSUtil.GSS_KRB5_MECH_OID,
                        GSSCredential.ACCEPT_ONLY);
                GSSName name = cred.getName();
                return name == null ? null : name.toString();
            }
        });
        if (!Objects.equals(result, r(b))) {
            throw new Exception("Check failed: getInstance(" + a
                    + ") has name " + result + ", not " + b);
        }
    } catch (PrivilegedActionException e) {
        if (!"NOCRED".equals(b)) {
            throw new Exception("Check failed: getInstance(" + a
                    + ") is null " + ", but not one with name " + b);
        }
    }
}
 
Example 17
Source File: GssMemoryIssues.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] argv) throws Exception {
    GSSManager man = GSSManager.getInstance();
    String s = "me@REALM";
    GSSName name = man.createName(s, GSSName.NT_USER_NAME);
    byte[] exported = name.export();
    // Offset of the length of the mech name. Length in big endian
    int lenOffset = exported.length - s.length() - 4;
    // Make it huge
    exported[lenOffset] = 0x7f;
    try {
        man.createName(exported, GSSName.NT_EXPORT_NAME);
    } catch (GSSException gsse) {
        System.out.println(gsse);
    }
}
 
Example 18
Source File: AbstractSpnegoNegotiatorTest.java    From elasticsearch-hadoop with Apache License 2.0 4 votes vote down vote up
@Test
public void testSuccessfulNegotiateWithRealmName() throws IOException, GSSException, InterruptedException {
    // Mechanisms
    final GSSManager gssManager = GSSManager.getInstance();
    final Oid spnegoOid = new Oid("1.3.6.1.5.5.2");

    // Configure logins
    Configuration configuration = new Configuration();
    SecurityUtil.setAuthenticationMethod(UserGroupInformation.AuthenticationMethod.KERBEROS, configuration);
    UserGroupInformation.setConfiguration(configuration);

    // Login as Server
    UserGroupInformation server = UserGroupInformation.loginUserFromKeytabAndReturnUGI(withRealm(KerberosSuite.PRINCIPAL_SERVER), KEYTAB_FILE.getAbsolutePath());
    final GSSName gssServicePrincipalName = gssManager.createName(withRealm(KerberosSuite.PRINCIPAL_SERVER), GSSName.NT_USER_NAME);
    final GSSCredential gssServiceCredential = server.doAs(new PrivilegedExceptionAction<GSSCredential>() {
        @Override
        public GSSCredential run() throws Exception {
            return gssManager.createCredential(
                    gssServicePrincipalName,
                    GSSCredential.DEFAULT_LIFETIME,
                    spnegoOid,
                    GSSCredential.ACCEPT_ONLY
            );
        }
    });
    final GSSContext serverCtx = gssManager.createContext(gssServiceCredential);

    // Login as Client and Create negotiator
    UserGroupInformation client = UserGroupInformation.loginUserFromKeytabAndReturnUGI(withRealm(KerberosSuite.PRINCIPAL_CLIENT), KEYTAB_FILE.getAbsolutePath());
    final SpnegoNegotiator spnegoNegotiator = client.doAs(new PrivilegedExceptionAction<SpnegoNegotiator>() {
        @Override
        public SpnegoNegotiator run() throws Exception {
            return new SpnegoNegotiator(withRealm(KerberosSuite.PRINCIPAL_CLIENT), withRealm(KerberosSuite.PRINCIPAL_SERVER));
        }
    });

    byte[] token = new byte[0];
    boolean authenticated = false;

    for (int idx = 0; idx < 100; idx++) {
        if (!spnegoNegotiator.established()) {
            final byte[] sendToken = token;
            String baseToken = client.doAs(new PrivilegedExceptionAction<String>() {
                @Override
                public String run() throws Exception {
                    if (sendToken.length > 0) {
                        return spnegoNegotiator.send(Base64.encodeBase64String(sendToken));
                    } else {
                        return spnegoNegotiator.send();
                    }
                }
            });
            token = Base64.decodeBase64(baseToken);
        }

        if (!spnegoNegotiator.established() && serverCtx.isEstablished()) {
            fail("Server is established, but client is not.");
        }

        if (!serverCtx.isEstablished()) {
            final byte[] currentToken = token;
            token = server.doAs(new PrivilegedExceptionAction<byte[]>() {
                @Override
                public byte[] run() throws Exception {
                    return serverCtx.acceptSecContext(currentToken, 0, currentToken.length);
                }
            });
        }

        if (serverCtx.isEstablished() && spnegoNegotiator.established()) {
            authenticated = true;
            break;
        }
    }

    assertThat(authenticated, is(true));
    assertThat(serverCtx.isEstablished(), is(true));
    assertThat(spnegoNegotiator.established(), is(true));

    spnegoNegotiator.close();
    assertThat(spnegoNegotiator.established(), is(false));
}
 
Example 19
Source File: Test5653.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args)
        throws Exception {

    Oid oldOid = new Oid("1.3.6.1.5.6.2");
    new OneKDC(null).writeJAASConf();

    System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");
    GSSManager m = GSSManager.getInstance();
    boolean found = false;

    // Test 1: the getMechsForName() method accepts it.
    for (Oid tmp: m.getMechsForName(oldOid)) {
        if (tmp.equals(GSSUtil.GSS_KRB5_MECH_OID)) {
            found = true;
            break;
        }
    }
    if (!found) {
        throw new Exception("Cannot found krb5 mech for old name type");
    }

    // Test 2: the createName() method accepts it.
    GSSName name = m.createName("[email protected]", oldOid);

    // Test 3: its getStringNameType() output is correct
    if (!name.getStringNameType().equals(GSSName.NT_HOSTBASED_SERVICE)) {
        throw new Exception("GSSName not correct name type");
    }

    // Test 4: everything still works.
    GSSContext c1 = m.createContext(
            name,
            GSSUtil.GSS_KRB5_MECH_OID,
            null,
            GSSContext.DEFAULT_LIFETIME);
    byte[] token = c1.initSecContext(new byte[0], 0, 0);

    Context s;
    s = Context.fromJAAS("server");
    s.startAsServer(GSSUtil.GSS_KRB5_MECH_OID);
    s.x().acceptSecContext(token, 0, token.length);
}
 
Example 20
Source File: GSSAPIAuthenticationMechanism.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public AuthenticationMechanismOutcome run() throws GSSException {
    NegotiationContext negContext = exchange.getAttachment(NegotiationContext.ATTACHMENT_KEY);
    if (negContext == null) {
        negContext = new NegotiationContext();
        exchange.putAttachment(NegotiationContext.ATTACHMENT_KEY, negContext);
        // Also cache it on the connection for future calls.
        exchange.getConnection().putAttachment(NegotiationContext.ATTACHMENT_KEY, negContext);
    }

    GSSContext gssContext = negContext.getGssContext();
    if (gssContext == null) {
        GSSManager manager = GSSManager.getInstance();

        GSSCredential credential = manager.createCredential(null, GSSCredential.INDEFINITE_LIFETIME, mechanisms, GSSCredential.ACCEPT_ONLY);

        gssContext = manager.createContext(credential);

        negContext.setGssContext(gssContext);
    }

    byte[] respToken = gssContext.acceptSecContext(challenge.array(), challenge.arrayOffset(), challenge.limit());
    negContext.setResponseToken(respToken);

    if (negContext.isEstablished()) {

        if (respToken != null) {
            // There will be no further challenge but we do have a token so set it here.
            exchange.getResponseHeaders().add(WWW_AUTHENTICATE,
                    NEGOTIATE_PREFIX + FlexBase64.encodeString(respToken, false));
        }
        IdentityManager identityManager = securityContext.getIdentityManager();
        final Account account = identityManager.verify(new GSSContextCredential(negContext.getGssContext()));
        if (account != null) {
            securityContext.authenticationComplete(account, name, false);
            return AuthenticationMechanismOutcome.AUTHENTICATED;
        } else {
            return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
        }
    } else {
        // This isn't a failure but as the context is not established another round trip with the client is needed.
        return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
    }
}