Example usage for javax.security.auth Subject Subject

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

Introduction

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

Prototype

public Subject() 

Source Link

Document

Create an instance of a Subject with an empty Set of Principals and empty Sets of public and private credentials.

Usage

From source file:freeipa.client.JSONRequestServlet.java

private void testRequest(final String jsonRequest, final PrintWriter writer) {

    writer.print(jsonRequest);//from ww w. ja  v a2s .c  o m
    writer.println("'</p>");
    URL ipaUrl;
    byte[] token = new byte[0];
    Subject subject = new Subject();
    try {
        ipaUrl = new URL("https://vm-144.idm.lab.eng.brq.redhat.com/ipa/json");

        KerberosHttpClient ipaClient = new KerberosHttpClient(token, subject);
        String response = ipaClient.makeRequest(ipaUrl, httpClient, jsonRequest);
        writer.println(response);
    } catch (Exception e) {
        writer.println("<h5>Failed!</h5>");
        writer.print("<p>");
        writer.print(e.getClass().getName());
        writer.print(" - ");
        writer.print(e.getMessage());
        writer.println("</p>");

        log.error("testDomain Failed", e);
    }

}

From source file:org.betaconceptframework.astroboa.client.service.RepositoryServiceClientWrapper.java

private void createClientContextIFLoggedInClientIsRemote(String repositoryId, String authenticationToken) {
    //Furthermore if client is using remote service then it should create a RepositoryContext
    //on its own Thread Local
    if (!localServiceIsUsed) {
        //Create a repository context and put it to ThreadLocal in order to be available to subsequent
        //service method calls
        CmsRepository connectedCmsRepository = repositoryServiceSecure.getCmsRepository(repositoryId);

        //Subject is not needed by this remote client
        //Neither authentication time out
        SecurityContext securityContext = new SecurityContext(authenticationToken, new Subject(), 0,
                getAvailableRepositoryIds());

        RepositoryContext repositoryContext = new RepositoryContext(connectedCmsRepository, securityContext);

        LazyLoader lazyLoader = new LazyLoader(client.getSpaceService(), client.getTopicService(),
                client.getDefinitionService(), client.getContentService());

        AstroboaClientContext clientContext = new AstroboaClientContext(repositoryContext, lazyLoader);

        registerClientToContext(clientContext);
    }/*from  w  w  w. ja v a  2s  . c o  m*/
}

From source file:org.betaconceptframework.astroboa.test.engine.security.CmsLoginTest.java

@Test
public void testAuthenticationTokenIsSameForPermanentKey() {

    Subject subject = new Subject();

    String identity = IdentityPrincipal.ANONYMOUS;
    IdentityPrincipal identityPrincipal = new IdentityPrincipal(identity);
    subject.getPrincipals().add(identityPrincipal);

    String permanentKey = "specialKey";

    String authToken1 = repositoryService.login(TestConstants.TEST_REPOSITORY_ID, subject, permanentKey);

    String authToken2 = repositoryService.login(TestConstants.TEST_REPOSITORY_ID, subject, permanentKey);

    Assert.assertEquals(authToken2, authToken1);

}

From source file:org.apache.hadoop.registry.secure.TestSecureLogins.java

@Test
public void testKerberosAuth() throws Throwable {
    File krb5conf = getKdc().getKrb5conf();
    String krbConfig = FileUtils.readFileToString(krb5conf);
    LOG.info("krb5.conf at {}:\n{}", krb5conf, krbConfig);
    Subject subject = new Subject();

    final Krb5LoginModule krb5LoginModule = new Krb5LoginModule();
    final Map<String, String> options = new HashMap<String, String>();
    options.put("keyTab", keytab_alice.getAbsolutePath());
    options.put("principal", ALICE_LOCALHOST);
    options.put("debug", "true");
    options.put("doNotPrompt", "true");
    options.put("isInitiator", "true");
    options.put("refreshKrb5Config", "true");
    options.put("renewTGT", "true");
    options.put("storeKey", "true");
    options.put("useKeyTab", "true");
    options.put("useTicketCache", "true");

    krb5LoginModule.initialize(subject, null, new HashMap<String, String>(), options);

    boolean loginOk = krb5LoginModule.login();
    assertTrue("Failed to login", loginOk);
    boolean commitOk = krb5LoginModule.commit();
    assertTrue("Failed to Commit", commitOk);
}

From source file:fi.okm.mpass.idp.authn.impl.OAuth2Identity.java

@Override
public Subject getSubject(HttpServletRequest httpRequest) throws SocialUserAuthenticationException {
    log.trace("Entering");
    try {/*from w w w .  ja  va2s.  co m*/
        TokenRequest request = getTokenRequest(httpRequest);
        if (request == null) {
            log.debug("User is not authenticated yet");
            log.trace("Leaving");
            return null;
        }
        TokenResponse tokenResponse = TokenResponse.parse(request.toHTTPRequest().send());
        if (!tokenResponse.indicatesSuccess()) {
            TokenErrorResponse errorResponse = (TokenErrorResponse) tokenResponse;
            String error = errorResponse.getErrorObject().getCode();
            String errorDescription = errorResponse.getErrorObject().getDescription();
            if (errorDescription != null && !errorDescription.isEmpty()) {
                error += " : " + errorDescription;
            }
            log.error("error:" + error);
            log.trace("Leaving");
            throw new SocialUserAuthenticationException(error, SocialUserErrorIds.EXCEPTION);
        }
        AccessTokenResponse tokenSuccessResponse = (AccessTokenResponse) tokenResponse;
        // Get the access token, the server may also return a refresh token
        AccessToken accessToken = tokenSuccessResponse.getAccessToken();
        // try reading stuff from accesstoken
        Subject subject = new Subject();
        log.debug("claims from provider: " + accessToken.toJSONString());
        parsePrincipalsFromClaims(subject, accessToken.toJSONObject());
        if (getUserinfoEndpoint() != null && !getUserinfoEndpoint().toString().isEmpty()) {
            // The protected resource / web API
            URL resourceURL = new URL(getUserinfoEndpoint().toString());
            // Open the connection and include the token
            URLConnection conn = resourceURL.openConnection();
            conn.setRequestProperty("Authorization", accessToken.toAuthorizationHeader());
            String userinfo = IOUtils.toString(conn.getInputStream());
            conn.getInputStream().close();
            try {
                parsePrincipalsFromClaims(subject, JSONObjectUtils.parseJSONObject(userinfo));
            } catch (java.text.ParseException e) {
                log.error("error parsing userinfo endpoint");
                log.trace("Leaving");
                throw new SocialUserAuthenticationException(e.getMessage(), SocialUserErrorIds.EXCEPTION);
            }
        }
        addDefaultPrincipals(subject);
        return subject;

    } catch (SerializeException | IOException | URISyntaxException | ParseException e) {
        log.error("Something bad happened " + e.getMessage());
        log.trace("Leaving");
        throw new SocialUserAuthenticationException(e.getMessage(), SocialUserErrorIds.EXCEPTION);
    }

}

From source file:org.flowerplatform.web.tests.codesync.CodeSyncWikiTest.java

public void testDokuWiki() {
    Subject subject = new Subject();
    final FlowerWebPrincipal principal = new FlowerWebPrincipal(0);
    final String technology = "Doku";
    String url = "http://csp1/dokuwiki/lib/exe/xmlrpc.php";
    String user = "";
    String password = "";
    principal.getWikiClientConfigurations().put(technology,
            new DokuWikiClientConfiguration(url, user, password));
    subject.getPrincipals().add(principal);
    Subject.doAsPrivileged(subject, new PrivilegedAction<Void>() {

        @Override/* w  w  w .  j a v a  2s .  com*/
        public Void run() {
            FlexContext.setThreadLocalSession(new HttpFlexSession());
            FlexContext.setUserPrincipal(principal);
            RecordingTestWebCommunicationChannel cc = new RecordingTestWebCommunicationChannel();
            cc.setPrincipal((FlowerWebPrincipal) principal);
            ServiceInvocationContext context = new ServiceInvocationContext(cc);

            Object wiki = DokuWikiPlugin.getInstance().getWikiPages("proiecte:flower:teste");

            WikiPlugin.getInstance().getConfigurationProviders().put(technology,
                    new DokuWikiConfigurationProvider());

            WikiPlugin wikiPlugin = WikiPlugin.getInstance();
            File project = getProject();
            ResourceSet resourceSet = CodeSyncPlugin.getInstance().getOrCreateResourceSet(project,
                    "mindmapEditorStatefulService");
            CodeSyncRoot leftRoot = wikiPlugin.getWikiTree(null, resourceSet, wiki, "proiecte:flower:teste",
                    technology);
            CodeSyncRoot rightRoot = wikiPlugin.getWikiTree(project, resourceSet, null, "proiecte:flower:teste",
                    technology);

            expected = new Pair[] { new Pair(WikiPlugin.FOLDER_CATEGORY, 0), // Crispico
                    new Pair(WikiPlugin.FOLDER_CATEGORY, 1), // proiecte
                    new Pair(WikiPlugin.FOLDER_CATEGORY, 2), // flower
                    new Pair(WikiPlugin.PAGE_CATEGORY, 3), // teste

                    new Pair(WikiPlugin.FOLDER_CATEGORY, 4), // teste
                    new Pair(WikiPlugin.PAGE_CATEGORY, 5), // new_test
                    new Pair(WikiPlugin.HEADING_LEVEL_2_CATEGORY, 6),
                    new Pair(WikiPlugin.HEADING_LEVEL_3_CATEGORY, 7),
                    new Pair(WikiPlugin.PARAGRAPH_CATEGORY, 8),

                    new Pair(WikiPlugin.HEADING_LEVEL_1_CATEGORY, 4),
                    new Pair(WikiPlugin.HEADING_LEVEL_1_CATEGORY, 4),
                    new Pair(WikiPlugin.HEADING_LEVEL_2_CATEGORY, 5),
                    new Pair(WikiPlugin.PARAGRAPH_CATEGORY, 6), new Pair(WikiPlugin.FLOWER_BLOCK_CATEGORY, 6),
                    new Pair(WikiPlugin.PARAGRAPH_CATEGORY, 6), new Pair(WikiPlugin.PARAGRAPH_CATEGORY, 6),
                    new Pair(WikiPlugin.PARAGRAPH_CATEGORY, 6), new Pair(WikiPlugin.PARAGRAPH_CATEGORY, 6),
                    new Pair(WikiPlugin.HEADING_LEVEL_2_CATEGORY, 5),
                    new Pair(WikiPlugin.HEADING_LEVEL_1_CATEGORY, 4)

            };
            test(leftRoot, rightRoot, resourceSet, technology, expected);

            return null;
        }
    }, null);
}

From source file:org.wso2.carbon.identity.application.authenticator.iwa.servlet.IWAServelet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String commonAuthURL = IdentityUtil.getServerURL(IWAConstants.COMMON_AUTH_EP);
    String param = request.getParameter(IWAConstants.IWA_PARAM_STATE);
    if (param == null) {
        throw new IllegalArgumentException(IWAConstants.IWA_PARAM_STATE + " parameter is null.");
    }/*w w  w.  j  av  a 2 s .co m*/
    commonAuthURL += "?" + IWAConstants.IWA_PARAM_STATE + "=" + URLEncoder.encode(param, IWAConstants.UTF_8)
            + "&" + IWAAuthenticator.IWA_PROCESSED + "=1";

    if (doFilterPrincipal(request)) {
        // previously authenticated user
        response.sendRedirect(commonAuthURL);
        return;
    }
    AuthorizationHeader authorizationHeader = new AuthorizationHeader(request);
    // authenticate user
    if (!authorizationHeader.isNull()) {
        // log the user in using the token
        IWindowsIdentity windowsIdentity;
        try {
            windowsIdentity = IWAServiceDataHolder.getInstance().getProviders().doFilter(request, response);
            if (windowsIdentity == null) {
                return;
            }
        } catch (IOException e) {
            log.warn("error logging in user.", e);
            sendUnauthorized(response, true);
            return;
        }
        IWindowsImpersonationContext ctx = null;
        try {
            if (!IWAServiceDataHolder.getInstance().isAllowGuestLogin() && windowsIdentity.isGuest()) {
                log.warn("guest login disabled: " + windowsIdentity.getFqn());
                sendUnauthorized(response, true);
                return;
            }
            if (log.isDebugEnabled()) {
                log.debug("logged in user: " + windowsIdentity.getFqn() + " (" + windowsIdentity.getSidString()
                        + ")");
            }
            HttpSession session = request.getSession(true);
            if (session == null) {
                throw new ServletException("Expected HttpSession");
            }

            Subject subject = (Subject) session.getAttribute(IWAConstants.SUBJECT_ATTRIBUTE);
            if (subject == null) {
                subject = new Subject();
            }

            WindowsPrincipal windowsPrincipal;
            if (IWAServiceDataHolder.getInstance().isImpersonate()) {
                windowsPrincipal = new AutoDisposableWindowsPrincipal(windowsIdentity,
                        IWAServiceDataHolder.getInstance().getPrincipalFormat(),
                        IWAServiceDataHolder.getInstance().getRoleFormat());
            } else {
                windowsPrincipal = new WindowsPrincipal(windowsIdentity,
                        IWAServiceDataHolder.getInstance().getPrincipalFormat(),
                        IWAServiceDataHolder.getInstance().getRoleFormat());
            }
            if (log.isDebugEnabled()) {
                log.debug("roles: " + windowsPrincipal.getRolesString());
            }
            subject.getPrincipals().add(windowsPrincipal);
            session.setAttribute(IWAConstants.SUBJECT_ATTRIBUTE, subject);

            log.info("Successfully logged in user: " + windowsIdentity.getFqn());

            request.getSession().setAttribute(PRINCIPAL_SESSION_KEY, windowsPrincipal);
            if (IWAServiceDataHolder.getInstance().isImpersonate()) {
                if (log.isDebugEnabled()) {
                    log.debug("impersonating user");
                }
                ctx = windowsIdentity.impersonate();
            }
        } finally {
            if (IWAServiceDataHolder.getInstance().isImpersonate() && ctx != null) {
                if (log.isDebugEnabled()) {
                    log.debug("terminating impersonation");
                }
                ctx.revertToSelf();
            } else {
                windowsIdentity.dispose();
            }
        }
        response.sendRedirect(commonAuthURL);
        return;
    }
    if (log.isDebugEnabled()) {
        log.debug("authorization required");
    }
    sendUnauthorized(response, false);
}

From source file:org.wso2.carbon.identity.application.authenticator.iwa.ntlm.servlet.IWAServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String commonAuthURL = IdentityUtil.getServerURL(IWAConstants.COMMON_AUTH_EP, false, true);
    String param = request.getParameter(IWAConstants.IWA_PARAM_STATE);
    if (param == null) {
        throw new IllegalArgumentException(IWAConstants.IWA_PARAM_STATE + " parameter is null.");
    }/*w ww.  ja  v  a 2s. co  m*/
    commonAuthURL += "?" + IWAConstants.IWA_PARAM_STATE + "=" + URLEncoder.encode(param, IWAConstants.UTF_8)
            + "&" + IWAAuthenticator.IWA_PROCESSED + "=1";

    if (doFilterPrincipal(request)) {
        // previously authenticated user
        response.sendRedirect(commonAuthURL);
        return;
    }
    AuthorizationHeader authorizationHeader = new AuthorizationHeader(request);
    // authenticate user
    if (!authorizationHeader.isNull()) {
        // log the user in using the token
        IWindowsIdentity windowsIdentity;
        try {
            windowsIdentity = IWAServiceDataHolder.getInstance().getProviders().doFilter(request, response);
            if (windowsIdentity == null) {
                return;
            }
        } catch (IOException e) {
            log.warn("error logging in user.", e);
            sendUnauthorized(response, true);
            return;
        }
        IWindowsImpersonationContext ctx = null;
        try {
            if (!IWAServiceDataHolder.getInstance().isAllowGuestLogin() && windowsIdentity.isGuest()) {
                log.warn("guest login disabled: " + windowsIdentity.getFqn());
                sendUnauthorized(response, true);
                return;
            }
            if (log.isDebugEnabled()) {
                log.debug("logged in user: " + windowsIdentity.getFqn() + " (" + windowsIdentity.getSidString()
                        + ")");
            }
            HttpSession session = request.getSession(true);
            if (session == null) {
                throw new ServletException("Expected HttpSession");
            }

            Subject subject = (Subject) session.getAttribute(IWAConstants.SUBJECT_ATTRIBUTE);
            if (subject == null) {
                subject = new Subject();
            }

            WindowsPrincipal windowsPrincipal;
            if (IWAServiceDataHolder.getInstance().isImpersonate()) {
                windowsPrincipal = new AutoDisposableWindowsPrincipal(windowsIdentity,
                        IWAServiceDataHolder.getInstance().getPrincipalFormat(),
                        IWAServiceDataHolder.getInstance().getRoleFormat());
            } else {
                windowsPrincipal = new WindowsPrincipal(windowsIdentity,
                        IWAServiceDataHolder.getInstance().getPrincipalFormat(),
                        IWAServiceDataHolder.getInstance().getRoleFormat());
            }
            if (log.isDebugEnabled()) {
                log.debug("roles: " + windowsPrincipal.getRolesString());
            }
            subject.getPrincipals().add(windowsPrincipal);
            session.setAttribute(IWAConstants.SUBJECT_ATTRIBUTE, subject);

            log.info("Successfully logged in user: " + windowsIdentity.getFqn());

            request.getSession().setAttribute(PRINCIPAL_SESSION_KEY, windowsPrincipal);
            if (IWAServiceDataHolder.getInstance().isImpersonate()) {
                if (log.isDebugEnabled()) {
                    log.debug("impersonating user");
                }
                ctx = windowsIdentity.impersonate();
            }
        } finally {
            if (IWAServiceDataHolder.getInstance().isImpersonate() && ctx != null) {
                if (log.isDebugEnabled()) {
                    log.debug("terminating impersonation");
                }
                ctx.revertToSelf();
            } else {
                windowsIdentity.dispose();
            }
        }
        response.sendRedirect(commonAuthURL);
        return;
    }
    if (log.isDebugEnabled()) {
        log.debug("authorization required");
    }
    sendUnauthorized(response, false);
}

From source file:org.exist.security.realm.openid.AuthenticatorOpenIdServlet.java

private void processReturn(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    Account principal = this.verifyResponse(req);

    //System.out.println(principal);

    String returnURL = req.getParameter("exist_return");

    if (principal == null) {
        //this.getServletContext().getRequestDispatcher("/openid/login.xql").forward(req, resp);
        resp.sendRedirect(returnURL);//from  w ww  .ja v  a2  s.c o m
    } else {
        HttpSession session = req.getSession(true);

        //((XQueryURLRewrite.RequestWrapper)req).setUserPrincipal(principal);

        Subject subject = new Subject();

        //TODO: hardcoded to jetty - rewrite
        //*******************************************************
        DefaultIdentityService _identityService = new DefaultIdentityService();
        UserIdentity user = _identityService.newUserIdentity(subject, principal, new String[0]);

        Authentication cached = new HttpSessionAuthentication(session, user);
        session.setAttribute(HttpSessionAuthentication.__J_AUTHENTICATED, cached);
        //*******************************************************

        resp.sendRedirect(returnURL);
    }
}

From source file:lia.gsi.net.GSIGssSocketFactory.java

/**
 * Retrieve the Globus Subject from a GssSocket
 * /*from   w w  w.  ja  va2s  .  c  om*/
 * @param socket
 * @return javax.security.auth.Subject having a single Principal elementt : The Globus DN
 * @throws GSSException
 *             if the supplied socket is not a GssSocket or the Globus Credentials is not set on the socket
 */
public static Subject getLocalSubject(Socket socket) throws GSSException {

    if (!(socket instanceof GssSocket))
        throw new GSSException(GSSException.NO_CRED);

    GssSocket gssSocket;
    gssSocket = (GssSocket) socket;
    Subject mySubject = new Subject();
    GlobusPrincipal nm;
    try {
        nm = JaasGssUtil.toGlobusPrincipal(gssSocket.getContext().getSrcName());
    } catch (Throwable t) {
        throw new GSSException(GSSException.NO_CRED);
    }
    mySubject.getPrincipals().add(nm);
    return mySubject;
}