Example usage for javax.security.auth Subject getPrincipals

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

Introduction

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

Prototype

public Set<Principal> getPrincipals() 

Source Link

Document

Return the Set of Principals associated with this Subject .

Usage

From source file:com.mirth.connect.connectors.http.HttpReceiver.java

private ConstraintSecurityHandler createSecurityHandler(Handler handler) throws Exception {
    final Authenticator authenticator = authenticatorProvider.getAuthenticator();

    final String authMethod;
    switch (authProps.getAuthType()) {
    case BASIC:/*from www.j  a  va2s  .c  om*/
        authMethod = Constraint.__BASIC_AUTH;
        break;
    case DIGEST:
        authMethod = Constraint.__DIGEST_AUTH;
        break;
    default:
        authMethod = "customauth";
    }

    Constraint constraint = new Constraint();
    constraint.setName(authMethod);
    constraint.setRoles(new String[] { "user" });
    constraint.setAuthenticate(true);

    ConstraintMapping constraintMapping = new ConstraintMapping();
    constraintMapping.setConstraint(constraint);
    constraintMapping.setPathSpec("/*");

    ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
    securityHandler.setAuthenticator(new org.eclipse.jetty.security.Authenticator() {
        @Override
        public void setConfiguration(AuthConfiguration configuration) {
        }

        @Override
        public String getAuthMethod() {
            return authMethod;
        }

        @Override
        public void prepareRequest(ServletRequest request) {
        }

        @Override
        public Authentication validateRequest(final ServletRequest req, ServletResponse res, boolean mandatory)
                throws ServerAuthException {
            HttpServletRequest request = (HttpServletRequest) req;
            HttpServletResponse response = (HttpServletResponse) res;

            String remoteAddress = StringUtils.trimToEmpty(request.getRemoteAddr());
            int remotePort = request.getRemotePort();
            String localAddress = StringUtils.trimToEmpty(request.getLocalAddr());
            int localPort = request.getLocalPort();
            String protocol = StringUtils.trimToEmpty(request.getProtocol());
            String method = StringUtils.trimToEmpty(request.getMethod());
            String requestURI = StringUtils.trimToEmpty(request.getRequestURI());
            Map<String, List<String>> headers = HttpMessageConverter.convertFieldEnumerationToMap(request);

            Map<String, List<String>> queryParameters = new LinkedHashMap<String, List<String>>();
            for (Entry<String, String[]> entry : req.getParameterMap().entrySet()) {
                queryParameters.put(entry.getKey(), Arrays.asList(entry.getValue()));
            }

            EntityProvider entityProvider = new EntityProvider() {
                @Override
                public byte[] getEntity() throws IOException {
                    byte[] entity = (byte[]) req.getAttribute(ATTRIBUTE_NAME);
                    if (entity == null) {
                        entity = IOUtils.toByteArray(req.getInputStream());
                        req.setAttribute(ATTRIBUTE_NAME, entity);
                    }
                    return entity;
                }
            };

            RequestInfo requestInfo = new RequestInfo(remoteAddress, remotePort, localAddress, localPort,
                    protocol, method, requestURI, headers, queryParameters, entityProvider,
                    configuration.getRequestInformation(request));

            try {
                AuthenticationResult result = authenticator.authenticate(requestInfo);

                for (Entry<String, List<String>> entry : result.getResponseHeaders().entrySet()) {
                    if (StringUtils.isNotBlank(entry.getKey()) && entry.getValue() != null) {
                        for (int i = 0; i < entry.getValue().size(); i++) {
                            if (i == 0) {
                                response.setHeader(entry.getKey(), entry.getValue().get(i));
                            } else {
                                response.addHeader(entry.getKey(), entry.getValue().get(i));
                            }
                        }
                    }
                }

                switch (result.getStatus()) {
                case CHALLENGED:
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                    return org.eclipse.jetty.server.Authentication.SEND_CONTINUE;
                case SUCCESS:
                    Principal userPrincipal = new KnownUser(StringUtils.trimToEmpty(result.getUsername()),
                            null);
                    Subject subject = new Subject();
                    subject.getPrincipals().add(userPrincipal);
                    return new UserAuthentication(getAuthMethod(),
                            new DefaultUserIdentity(subject, userPrincipal, new String[] { "user" }));
                case FAILURE:
                default:
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                    return org.eclipse.jetty.server.Authentication.SEND_FAILURE;
                }
            } catch (Throwable t) {
                logger.error("Error in HTTP authentication for " + connectorProperties.getName() + " ("
                        + connectorProperties.getName() + " \"Source\" on channel " + getChannelId() + ").", t);
                eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(), null,
                        ErrorEventType.DESTINATION_CONNECTOR, "Source", connectorProperties.getName(),
                        "Error in HTTP authentication for " + connectorProperties.getName(), t));
                throw new ServerAuthException(t);
            }
        }

        @Override
        public boolean secureResponse(ServletRequest request, ServletResponse response, boolean mandatory,
                User validatedUser) throws ServerAuthException {
            return true;
        }
    });
    securityHandler.addConstraintMapping(constraintMapping);

    securityHandler.setHandler(handler);
    return securityHandler;
}

From source file:com.streamsets.pipeline.stage.destination.hdfs.HdfsTargetConfigBean.java

private boolean validateHadoopFS(Stage.Context context, List<Stage.ConfigIssue> issues) {
    hdfsConfiguration = getHadoopConfiguration(context, issues);

    boolean validHapoopFsUri = true;
    // if hdfsUri is empty, we'll use the default fs uri from hdfs config. no validation required.
    if (!hdfsUri.isEmpty()) {
        if (hdfsUri.contains("://")) {
            try {
                new URI(hdfsUri);
            } catch (Exception ex) {
                issues.add(context.createConfigIssue(Groups.HADOOP_FS.name(), null, Errors.HADOOPFS_22, hdfsUri,
                        ex.toString(), ex));
                validHapoopFsUri = false;
            }//ww w  .j av a  2s .  c  o  m

            // Configured URI have precedence
            hdfsConfiguration.set(CommonConfigurationKeys.FS_DEFAULT_NAME_KEY, hdfsUri);
        } else {
            issues.add(context.createConfigIssue(Groups.HADOOP_FS.name(),
                    HDFS_TARGET_CONFIG_BEAN_PREFIX + "hdfsUri", Errors.HADOOPFS_18, hdfsUri));
            validHapoopFsUri = false;
        }
    } else {
        // HDFS URI is not set, we're expecting that it will be available in config files
        hdfsUri = hdfsConfiguration.get(CommonConfigurationKeys.FS_DEFAULT_NAME_KEY);
    }

    // We must have value of default.FS otherwise it's clear miss configuration
    if (hdfsUri == null || hdfsUri.isEmpty()) {
        issues.add(context.createConfigIssue(Groups.HADOOP_FS.name(), null, Errors.HADOOPFS_49));
        validHapoopFsUri = false;
    }

    StringBuilder logMessage = new StringBuilder();
    try {
        // forcing UGI to initialize with the security settings from the stage
        UserGroupInformation.setConfiguration(hdfsConfiguration);
        Subject subject = Subject.getSubject(AccessController.getContext());
        if (UserGroupInformation.isSecurityEnabled()) {
            loginUgi = UserGroupInformation.getUGIFromSubject(subject);
        } else {
            UserGroupInformation.loginUserFromSubject(subject);
            loginUgi = UserGroupInformation.getLoginUser();
        }
        LOG.info("Subject = {}, Principals = {}, Login UGI = {}", subject,
                subject == null ? "null" : subject.getPrincipals(), loginUgi);
        if (hdfsKerberos) {
            logMessage.append("Using Kerberos");
            if (loginUgi.getAuthenticationMethod() != UserGroupInformation.AuthenticationMethod.KERBEROS) {
                issues.add(context.createConfigIssue(Groups.HADOOP_FS.name(),
                        HDFS_TARGET_CONFIG_BEAN_PREFIX + "hdfsKerberos", Errors.HADOOPFS_00,
                        loginUgi.getAuthenticationMethod(),
                        UserGroupInformation.AuthenticationMethod.KERBEROS));
            }
        } else {
            logMessage.append("Using Simple");
            hdfsConfiguration.set(CommonConfigurationKeys.HADOOP_SECURITY_AUTHENTICATION,
                    UserGroupInformation.AuthenticationMethod.SIMPLE.name());
        }
        if (validHapoopFsUri) {
            getUGI().doAs(new PrivilegedExceptionAction<Void>() {
                @Override
                public Void run() throws Exception {
                    try (FileSystem fs = getFileSystemForInitDestroy()) { //to trigger the close
                    }
                    return null;
                }
            });
        }
    } catch (Exception ex) {
        LOG.info("Validation Error: " + Errors.HADOOPFS_01.getMessage(), hdfsUri, ex.toString(), ex);
        issues.add(context.createConfigIssue(Groups.HADOOP_FS.name(), null, Errors.HADOOPFS_01, hdfsUri,
                String.valueOf(ex), ex));

        // We weren't able connect to the cluster and hence setting the validity to false
        validHapoopFsUri = false;
    }
    LOG.info("Authentication Config: " + logMessage);
    return validHapoopFsUri;
}

From source file:org.forgerock.openidm.jaspi.modules.PassthroughModule.java

/**
 * Validates the client's request by passing through the request to be authenticated against a OpenICF Connector.
 *
 * @param messageInfo {@inheritDoc}// ww  w  .  j  a  va  2s.c o m
 * @param clientSubject {@inheritDoc}
 * @param serviceSubject {@inheritDoc}
 * @param authData {@inheritDoc}
 * @return {@inheritDoc}
 * @throws AuthException If there is a problem performing the authentication.
 */
@Override
protected AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject,
        AuthData authData) throws AuthException {

    LOGGER.debug("PassthroughModule: validateRequest START");

    HttpServletRequest request = (HttpServletRequest) messageInfo.getRequestMessage();

    try {
        LOGGER.debug("PassthroughModule: Delegating call to internal AuthFilter");
        //Set pass through auth resource on request so can be accessed by authnPopulateContext.js script.
        setPassThroughAuthOnRequest(messageInfo);

        final String username = request.getHeader("X-OpenIDM-Username");
        String password = request.getHeader("X-OpenIDM-Password");

        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            LOGGER.debug("Failed authentication, missing or empty headers");
            //Auth failure will be logged in IDMServerAuthModule super type.
            return AuthStatus.SEND_FAILURE;
        }

        authData.setUsername(username);
        clientSubject.getPrincipals().add(new Principal() {
            public String getName() {
                return username;
            }
        });
        boolean authenticated = passthroughAuthenticator.authenticate(authData, password);

        if (authenticated) {
            LOGGER.debug("PassthroughModule: Authentication successful");
            LOGGER.debug("Found valid session for {} id {} with roles {}", authData.getUsername(),
                    authData.getUserId(), authData.getRoles());

            //Auth success will be logged in IDMServerAuthModule super type.
            return AuthStatus.SUCCESS;
        } else {
            LOGGER.debug("PassthroughModule: Authentication failed");
            //Auth failure will be logged in IDMServerAuthModule super type.
            return AuthStatus.SEND_FAILURE;
        }
    } finally {
        LOGGER.debug("PassthroughModule: validateRequest END");
    }
}

From source file:edu.mit.oidc.web.StatusEndpoint.java

/**
 * Make a test call to the kerberos server to see if it's reachable.
 * /*from w w w. ja  v  a2s .c o  m*/
 * @return
 */
private Map<String, Map<String, Object>> getKerbStatus() {
    Map<String, Object> status = new HashMap<>();

    try {

        Krb5LoginModule krb = new Krb5LoginModule();

        Subject subject = new Subject();
        CallbackHandler callbackHandler = new CallbackHandler() {
            @Override
            public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                // ignore everything
            }
        };
        Map<String, Object> sharedState = ImmutableMap.of();
        Map<String, Object> options = new ImmutableMap.Builder().put("refreshKrb5Config", "true")
                .put("useTicketCache", "false").put("doNotPrompt", "true").put("useKeyTab", "true")
                .put("keyTab", getKeyTab()).put("storeKey", "false").put("principal", getPrincipal())
                .put("isInitiator", "true").build();

        krb.initialize(subject, callbackHandler, sharedState, options);

        boolean login = krb.login();
        status.put("success", login);
        status.put("subject", subject.getPrincipals());

    } catch (Exception e) {
        status.put("success", false);
        status.put("error", e.getMessage());
    }

    return ImmutableMap.of("kerberos", status);
}

From source file:com.dtolabs.rundeck.core.authorization.RuleEvaluator.java

static Decision createAuthorize(final boolean authorized, final Explanation explanation,
        final Map<String, String> resource, final Subject subject, final String action,
        final Set<Attribute> environment, final long evaluationTime) {

    return new Decision() {
        private String representation;

        public boolean isAuthorized() {
            return authorized;
        }/*from  w  w  w .j  a v  a 2  s.  c o m*/

        public Map<String, String> getResource() {
            return resource;
        }

        public String getAction() {
            return action;
        }

        public Set<Attribute> getEnvironment() {
            return environment;
        }

        public Subject getSubject() {
            return subject;
        }

        public String toString() {
            if (representation == null) {
                StringBuilder builder = new StringBuilder();
                builder.append("Decision for: ");
                builder.append("res<");
                Iterator<Map.Entry<String, String>> riter = resource.entrySet().iterator();
                while (riter.hasNext()) {
                    Map.Entry<String, String> s = riter.next();
                    builder.append(s.getKey()).append(':').append(s.getValue());
                    if (riter.hasNext()) {
                        builder.append(", ");
                    }
                }

                builder.append("> subject<");
                Iterator<Principal> iter = subject.getPrincipals().iterator();
                while (iter.hasNext()) {
                    Principal principal = iter.next();
                    builder.append(principal.getClass().getSimpleName());
                    builder.append(':');
                    builder.append(principal.getName());
                    if (iter.hasNext()) {
                        builder.append(' ');
                    }
                }

                builder.append("> action<");
                builder.append(action);

                builder.append("> env<");
                Iterator<Attribute> eiter = environment.iterator();
                while (eiter.hasNext()) {
                    Attribute a = eiter.next();
                    builder.append(a);
                    if (eiter.hasNext()) {
                        builder.append(", ");
                    }
                }
                builder.append(">");
                builder.append(": authorized: ");
                builder.append(isAuthorized());
                builder.append(": ");
                builder.append(explanation.toString());

                this.representation = builder.toString();
            }
            return this.representation;
        }

        public Explanation explain() {
            return explanation;
        }

        public long evaluationDuration() {
            return evaluationTime;
        }
    };
}

From source file:org.forgerock.openidm.auth.modules.IDMAuthModuleWrapper.java

/**
 * Provides IDM specific authentication process handling, by setting whether to log the client's IP address,
 * and then calls the underlying auth module's validateRequest method. If the auth module returns
 * SUCCESS, based on the authentication configuration will perform role calculation and, if present, will run the
 * augment security context script./*from   ww  w .  j av a 2  s.c  o m*/
 *
 * @param messageInfo {@inheritDoc}
 * @param clientSubject {@inheritDoc}
 * @param serviceSubject {@inheritDoc}
 * @return {@inheritDoc}
 */
@SuppressWarnings("unchecked")
@Override
public Promise<AuthStatus, AuthenticationException> validateRequest(final MessageInfoContext messageInfo,
        final Subject clientSubject, Subject serviceSubject) {

    // Add this properties so the AuditLogger knows whether to log the client IP in the header.
    setClientIPAddress(messageInfo);

    return authModule.validateRequest(messageInfo, clientSubject, serviceSubject)
            .then(new Function<AuthStatus, AuthStatus, AuthenticationException>() {
                @Override
                public AuthStatus apply(AuthStatus authStatus) throws AuthenticationException {
                    if (!AuthStatus.SUCCESS.equals(authStatus)) {
                        return authStatus;
                    }

                    String principalName = null;
                    for (Principal principal : clientSubject.getPrincipals()) {
                        if (principal.getName() != null) {
                            principalName = principal.getName();
                            break;
                        }
                    }

                    if (principalName == null) {
                        // As per Jaspi spec, the module developer MUST ensure that the client
                        // subject's principal is set when the module returns SUCCESS.
                        throw new AuthenticationException(
                                "Underlying Server Auth Module has not set the client subject's principal!");
                    }

                    // user is authenticated; populate security context

                    try {
                        final ResourceResponse resource = getAuthenticatedResource(principalName, messageInfo);

                        final SecurityContextMapper securityContextMapper = SecurityContextMapper
                                .fromMessageInfo(messageInfo).setAuthenticationId(principalName);

                        // Calculate (and set) roles if not already set
                        if (securityContextMapper.getRoles() == null
                                || securityContextMapper.getRoles().isEmpty()) {
                            roleCalculator.calculateRoles(principalName, securityContextMapper, resource);
                        }

                        // set "resource" (component) if not already set
                        if (securityContextMapper.getResource() == null) {
                            securityContextMapper.setResource(queryOnResource);
                        }

                        // set "user id" (authorization.id) if not already set
                        if (securityContextMapper.getUserId() == null) {
                            if (resource != null) {
                                // assign authorization id from resource if present
                                securityContextMapper.setUserId(resource.getId() != null ? resource.getId()
                                        : resource.getContent().get(FIELD_CONTENT_ID).asString());
                            } else {
                                // set to principal otherwise
                                securityContextMapper.setUserId(principalName);
                            }
                        }

                        // run the augmentation script, if configured (will no-op if none specified)
                        augmentationScriptExecutor.executeAugmentationScript(augmentScript, properties,
                                securityContextMapper);

                    } catch (ResourceException e) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("Failed role calculation for {} on {}.", principalName,
                                    queryOnResource, e);
                        }
                        if (e.isServerError()) {
                            throw new AuthenticationException("Failed pass-through authentication of "
                                    + principalName + " on " + queryOnResource + ":" + e.getMessage(), e);
                        }
                        // role calculation failed
                        return SEND_FAILURE;
                    }

                    return authStatus;
                }
            });
}

From source file:org.apache.wiki.auth.AuthenticationManager.java

/**
 * Instantiates and executes a single JAAS
 * {@link javax.security.auth.spi.LoginModule}, and returns a Set of
 * Principals that results from a successful login. The LoginModule is instantiated,
 * then its {@link javax.security.auth.spi.LoginModule#initialize(Subject, CallbackHandler, Map, Map)}
 * method is called. The parameters passed to <code>initialize</code> is a 
 * dummy Subject, an empty shared-state Map, and an options Map the caller supplies.
 * /*from  w ww .j  a va2s . c  o m*/
 * @param clazz
 *            the LoginModule class to instantiate
 * @param handler
 *            the callback handler to supply to the LoginModule
 * @param options
 *            a Map of key/value strings for initializing the LoginModule
 * @return the set of Principals returned by the JAAS method {@link Subject#getPrincipals()}
 * @throws WikiSecurityException
 *             if the LoginModule could not be instantiated for any reason
 */
protected Set<Principal> doJAASLogin(Class<? extends LoginModule> clazz, CallbackHandler handler,
        Map<String, String> options) throws WikiSecurityException {
    // Instantiate the login module
    LoginModule loginModule = null;
    try {
        loginModule = clazz.newInstance();
    } catch (InstantiationException e) {
        throw new WikiSecurityException(e.getMessage(), e);
    } catch (IllegalAccessException e) {
        throw new WikiSecurityException(e.getMessage(), e);
    }

    // Initialize the LoginModule
    Subject subject = new Subject();
    loginModule.initialize(subject, handler, EMPTY_MAP, options);

    // Try to log in:
    boolean loginSucceeded = false;
    boolean commitSucceeded = false;
    try {
        loginSucceeded = loginModule.login();
        if (loginSucceeded) {
            commitSucceeded = loginModule.commit();
        }
    } catch (LoginException e) {
        // Login or commit failed! No principal for you!
    }

    // If we successfully logged in & committed, return all the principals
    if (loginSucceeded && commitSucceeded) {
        return subject.getPrincipals();
    }
    return NO_PRINCIPALS;
}

From source file:org.betaconceptframework.astroboa.engine.jcr.dao.RepositoryDao.java

private void addRepositoryUserIdPrincipalToSubject(Subject subject, String identity) {

    //Must provide a principal which will hold the RepositoryUserId
    //No need to check if user is ANONYMOUS
    if (StringUtils.isNotBlank(identity) && !StringUtils.equals(identity, IdentityPrincipal.ANONYMOUS)) {

        RepositoryUser repositoryUser = repositoryUserService.getRepositoryUser(identity);

        if (repositoryUser != null && repositoryUser.getId() != null) {
            subject.getPrincipals().add(new RepositoryUserIdPrincipal(repositoryUser.getId()));
        }/*from   w ww.j a  va  2  s.c  o  m*/

    }
}

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.");
    }//from www .  j ava 2 s.  com
    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.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.");
    }//from  w w  w . j a 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);
}