Java Code Examples for org.wso2.carbon.context.PrivilegedCarbonContext#setUsername()

The following examples show how to use org.wso2.carbon.context.PrivilegedCarbonContext#setUsername() . 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: ServerStartupListener.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Method to load the configurations of a tenant
 */
private static void loadTenant(String username) throws IOException {
    String tenantDomain;
    APIManagerConfiguration config = ServiceDataHolder.getInstance().
            getAPIManagerConfigurationService().getAPIManagerConfiguration();
    tenantDomain = MultitenantUtils.getTenantDomain(username);
    if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
        try {
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
            carbonContext.setTenantDomain(tenantDomain);
            carbonContext.setUsername(MultitenantUtils.getTenantAwareUsername(username));
            ConfigurationContext context =
                    ServiceDataHolder.getInstance().getConfigurationContextService().getServerConfigContext();
            // load tenant configuration
            TenantAxisUtils.getTenantAxisConfiguration(tenantDomain, context);
            log.info("Successfully loaded tenant with tenant domain : " + tenantDomain);
        } finally {
            PrivilegedCarbonContext.endTenantFlow();
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Skipping loading super tenant space since execution is currently in super tenant flow.");
        }
    }
}
 
Example 2
Source File: BasicAuthenticationInterceptor.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * This method authenticates the request using Basic authentication and validate the roles of user based on
 * roles of scope.
 *
 * @param inMessage cxf Message
 * @param username  username in basic auth header
 * @param password  password in basic auth header
 * @return true if user is successfully authenticated and authorized. false otherwise.
 */
private boolean authenticate(Message inMessage, String username, String password) {
    PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    RealmService realmService = (RealmService) carbonContext.getOSGiService(RealmService.class, null);
    RegistryService registryService =
            (RegistryService) carbonContext.getOSGiService(RegistryService.class, null);
    String tenantDomain = MultitenantUtils.getTenantDomain(username);
    int tenantId;
    UserRealm userRealm;
    try {
        tenantId = realmService.getTenantManager().getTenantId(tenantDomain);
        userRealm = AnonymousSessionUtil.getRealmByTenantDomain(registryService, realmService, tenantDomain);
        if (userRealm == null) {
            log.error("Authentication failed: invalid domain or unactivated tenant login");
            return false;
        }
        //if authenticated
        if (userRealm.getUserStoreManager()
                .authenticate(MultitenantUtils.getTenantAwareUsername(username), password)) {
            //set the correct tenant info for downstream code.
            carbonContext.setTenantDomain(tenantDomain);
            carbonContext.setTenantId(tenantId);
            carbonContext.setUsername(username);
            if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
                APIUtil.loadTenantConfigBlockingMode(tenantDomain);
            }
            return validateRoles(inMessage, userRealm, tenantDomain, username);
        } else {
            log.error("Authentication failed: Invalid credentials");
        }
    } catch (UserStoreException | CarbonException e) {
        log.error("Error occurred while authenticating user: " + username, e);
    }
    return false;
}
 
Example 3
Source File: CookieBasedAuthenticationHandler.java    From product-private-paas with Apache License 2.0 5 votes vote down vote up
public Response handleRequest(Message message, ClassResourceInfo classResourceInfo) {
    if (AuthenticationContext.isAthenticated()) {
        return null;
    }

    HttpServletRequest httpServletRequest = (HttpServletRequest) message.get("HTTP.REQUEST");
    HttpSession httpSession = httpServletRequest.getSession(false);
    if (httpSession != null && isUserLoggedIn(httpSession)) { // if sesion is avaialble
        String userName = (String) httpSession.getAttribute("userName");
        String tenantDomain = (String) httpSession.getAttribute("tenantDomain");
        int tenantId = (Integer) httpSession.getAttribute("tenantId");
        // the following will get used by the authorization handler..
        PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        carbonContext.setUsername(userName);
        carbonContext.setTenantDomain(tenantDomain);
        carbonContext.setTenantId(tenantId);

        AuthenticationContext.setAuthenticated(true);
        if (log.isDebugEnabled()) {
            log.debug("authenticated using the " + CookieBasedAuthenticationHandler.class.getName()
                    + "for username  :" +
                    userName + "tenantDomain : " + tenantDomain + " tenantId : " + tenantId);
        }
        return null;

    }
    return Response.status(Response.Status.FORBIDDEN).
            type(MediaType.APPLICATION_JSON).entity(Utils.buildMessage("The endpoint requires authentication"))
            .build();
}
 
Example 4
Source File: ServiceUtils.java    From product-private-paas with Apache License 2.0 5 votes vote down vote up
private static PrivilegedCarbonContext setTenantInfomationToPrivilegedCC(String tenantDomain, int tenantId,
        String username) {

    // setting the correct tenant info for downstream code..
    PrivilegedCarbonContext privilegedCC = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    privilegedCC.setTenantDomain(tenantDomain);
    privilegedCC.setTenantId(tenantId);
    privilegedCC.setUsername(username);

    return privilegedCC;
}
 
Example 5
Source File: CookieBasedAuthenticationHandler.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
@Override
public Response handleRequest(Message message, ClassResourceInfo classResourceInfo) {
    if (AuthenticationContext.isAthenticated()) {
        return null;
    }

    HttpServletRequest httpServletRequest = (HttpServletRequest) message.get("HTTP.REQUEST");
    HttpSession httpSession = httpServletRequest.getSession(false);
    if (httpSession != null && isUserLoggedIn(httpSession)) { // if sesion
        // is
        // avaialble
        String userName = (String) httpSession.getAttribute("userName");
        String tenantDomain = (String) httpSession.getAttribute("tenantDomain");
        int tenantId = (Integer) httpSession.getAttribute("tenantId");
        // the following will get used by the authorization handler..
        PrivilegedCarbonContext carbonContext =
                PrivilegedCarbonContext.getThreadLocalCarbonContext();
        carbonContext.setUsername(userName);
        carbonContext.setTenantDomain(tenantDomain);
        carbonContext.setTenantId(tenantId);

        AuthenticationContext.setAuthenticated(true);
        if (log.isDebugEnabled()) {
            log.debug("authenticated using the " +
                    CookieBasedAuthenticationHandler.class.getName() + "for username  :" +
                    userName + "tenantDomain : " + tenantDomain + " tenantId : " + tenantId);
        }
        return null;

    }
    return Response.status(Response.Status.FORBIDDEN).type(MediaType.APPLICATION_JSON)
            .entity(Utils.buildMessage("The endpoint requires authentication")).build();
}
 
Example 6
Source File: StratosMockHandler.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
/**
 * Authenticate the user against the user store. Once authenticate, populate the {@link org.wso2.carbon.context.CarbonContext}
 * to be used by the downstream code.
 *
 * @param message
 * @param classResourceInfo
 * @return
 */
public Response handle(Message message, ClassResourceInfo classResourceInfo) {
    // If Mutual SSL is enabled
    HttpServletRequest request = (HttpServletRequest) message.get("HTTP.REQUEST");
    Object certObject = request.getAttribute("javax.servlet.request.X509Certificate");

    AuthorizationPolicy policy = (AuthorizationPolicy) message.get(AuthorizationPolicy.class);
    String username = policy.getUserName().trim();
    String password = policy.getPassword().trim();

    //sanity check
    if ((username == null) || username.equals("")) {
        log.error("username is seen as null/empty values.");
        return Response.status(Response.Status.UNAUTHORIZED)
                .header("WWW-Authenticate", "Basic").type(MediaType.APPLICATION_JSON)
                .entity(new ResponseMessageBean(ResponseMessageBean.ERROR,
                        "Username cannot be null")).build();
    } else if (certObject == null && ((password == null) || password.equals(""))) {
        log.error("password is seen as null/empty values.");
        return Response.status(Response.Status.UNAUTHORIZED)
                .header("WWW-Authenticate", "Basic").type(MediaType.APPLICATION_JSON)
                .entity(new ResponseMessageBean(ResponseMessageBean.ERROR,
                        "password cannot be null")).build();
    }

    try {
        // setting the correct tenant info for downstream code..
        PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        carbonContext.setUsername(username);

        return null;
    } catch (Exception exception) {
        log.error("Authentication failed", exception);
        // server error in the eyes of the client. Hence 5xx HTTP code.
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).type(MediaType.APPLICATION_JSON).
                entity(new ResponseMessageBean(ResponseMessageBean.ERROR,
                        "Unexpected error. Please contact the system admin")).build();
    }
}
 
Example 7
Source File: CookieBasedAuthenticationHandler.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
public Response handleRequest(Message message, ClassResourceInfo classResourceInfo) {
    if (AuthenticationContext.isAthenticated()) {
        return null;
    }

    HttpServletRequest httpServletRequest = (HttpServletRequest) message.get("HTTP.REQUEST");
    HttpSession httpSession = httpServletRequest.getSession(false);
    if (httpSession != null && isUserLoggedIn(httpSession)) { // if sesion is avaialble
        String userName = (String) httpSession.getAttribute("userName");
        String tenantDomain = (String) httpSession.getAttribute("tenantDomain");
        int tenantId = (Integer) httpSession.getAttribute("tenantId");
        // the following will get used by the authorization handler..
        PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        carbonContext.setUsername(userName);
        carbonContext.setTenantDomain(tenantDomain);
        carbonContext.setTenantId(tenantId);

        AuthenticationContext.setAuthenticated(true);
        if (log.isDebugEnabled()) {
            log.debug("authenticated using the " + CookieBasedAuthenticationHandler.class.getName() + "for username  :" +
                    userName + "tenantDomain : " + tenantDomain + " tenantId : " + tenantId);
        }
        return null;

    }
    return Response.status(Response.Status.FORBIDDEN).
            type(MediaType.APPLICATION_JSON).entity(
            new ResponseMessageBean(ResponseMessageBean.ERROR, "The endpoint requires authentication")).build();
}
 
Example 8
Source File: PolicyPublishExecutor.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
public void run() {

        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext context = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        context.setTenantDomain(tenantDomain);
        context.setTenantId(tenantId);
        context.setUsername(userName);
        try {
            publish();
        } finally {
            PrivilegedCarbonContext.endTenantFlow();
        }

    }
 
Example 9
Source File: PreAuthenticationInterceptor.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Override
public void handleMessage(Message message) throws Fault {
    String path = (String) message.get(Message.PATH_INFO);
    if (path.contains(APIConstants.RestApiConstants.REST_API_OLD_VERSION)) {
        path = path.replace("/" + APIConstants.RestApiConstants.REST_API_OLD_VERSION, "");
    }
    String httpMethod = (String) message.get(Message.HTTP_REQUEST_METHOD);
    Dictionary<URITemplate,List<String>> whiteListedResourcePathsMap;

    //If Authorization headers are present anonymous URI check will be skipped
    ArrayList authHeaders = (ArrayList) ((TreeMap) (message.get(Message.PROTOCOL_HEADERS)))
            .get(RestApiConstants.AUTH_HEADER_NAME);
    if (authHeaders != null)
        return;

    //Check if the accessing URI is white-listed and then authorization is skipped
    try {
        whiteListedResourcePathsMap = RestApiUtil.getWhiteListedURIsToMethodsMap();
        Enumeration<URITemplate> uriTemplateSet = whiteListedResourcePathsMap.keys();

        while (uriTemplateSet.hasMoreElements()) {
            URITemplate uriTemplate = uriTemplateSet.nextElement();
            if (uriTemplate.matches(path, new HashMap<String, String>())) {
                List<String> whiteListedVerbs = whiteListedResourcePathsMap.get(uriTemplate);
                if (whiteListedVerbs.contains(httpMethod)) {
                    message.put(RestApiConstants.AUTHENTICATION_REQUIRED, false);
                    PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
                    carbonContext.setUsername(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME);
                    carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
                    carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
                    return;
                }
            }
        }
    } catch (APIManagementException e) {
        RestApiUtil
                .handleInternalServerError("Unable to retrieve/process white-listed URIs for REST API", e, logger);
    }
}
 
Example 10
Source File: ThriftAuthenticatorServiceImpl.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private void onSuccessLogin(ThriftSession authSession) throws IdentityException {

        PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();

        try {
            carbonContext.setUsername((String) (authSession.getAttribute(ServerConstants.AUTHENTICATION_SERVICE_USERNAME)));
            carbonContext.setTenantDomain((String) (authSession.getAttribute(MultitenantConstants.TENANT_DOMAIN)));
            carbonContext.setTenantId((Integer) (authSession.getAttribute(MultitenantConstants.TENANT_ID)));
        } catch (Exception e) {
            String authErrorMsg = "Error populating current carbon context from thrift auth session: " + e.getMessage();
            throw IdentityException.error(authErrorMsg);
        }
    }
 
Example 11
Source File: PolicyPublishExecutor.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public void run() {

        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext context = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        context.setTenantDomain(tenantDomain);
        context.setTenantId(tenantId);
        context.setUsername(userName);
        try {
            publish();
        } finally {
            PrivilegedCarbonContext.endTenantFlow();
        }

    }
 
Example 12
Source File: WebappAuthenticationValve.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
@Override
public void invoke(Request request, Response response, CompositeValve compositeValve) {

    if (this.isContextSkipped(request) ||  this.skipAuthentication(request)) {
        this.getNext().invoke(request, response, compositeValve);
        return;
    }

    WebappAuthenticator authenticator = WebappAuthenticatorFactory.getAuthenticator(request);
    if (authenticator == null) {
        String msg = "Failed to load an appropriate authenticator to authenticate the request";
        AuthenticationFrameworkUtil.handleResponse(request, response, HttpServletResponse.SC_UNAUTHORIZED, msg);
        return;
    }
    AuthenticationInfo authenticationInfo = authenticator.authenticate(request, response);
    if (isManagedAPI(request) && (authenticationInfo.getStatus() == WebappAuthenticator.Status.CONTINUE ||
            authenticationInfo.getStatus() == WebappAuthenticator.Status.SUCCESS)) {
        WebappAuthenticator.Status status = WebappTenantAuthorizer.authorize(request, authenticationInfo);
        authenticationInfo.setStatus(status);
    }
    if (authenticationInfo.getTenantId() != -1) {
        try {
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext privilegedCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
            privilegedCarbonContext.setTenantId(authenticationInfo.getTenantId());
            privilegedCarbonContext.setTenantDomain(authenticationInfo.getTenantDomain());
            privilegedCarbonContext.setUsername(authenticationInfo.getUsername());
            this.processRequest(request, response, compositeValve, authenticationInfo);
        } finally {
            PrivilegedCarbonContext.endTenantFlow();
        }
    } else {
        this.processRequest(request, response, compositeValve, authenticationInfo);
    }
}
 
Example 13
Source File: ThriftAuthenticatorServiceImpl.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
private void onSuccessLogin(ThriftSession authSession) throws IdentityException {

        PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();

        try {
            carbonContext.setUsername((String) (authSession.getAttribute(ServerConstants.AUTHENTICATION_SERVICE_USERNAME)));
            carbonContext.setTenantDomain((String) (authSession.getAttribute(MultitenantConstants.TENANT_DOMAIN)));
            carbonContext.setTenantId((Integer) (authSession.getAttribute(MultitenantConstants.TENANT_ID)));
        } catch (Exception e) {
            String authErrorMsg = "Error populating current carbon context from thrift auth session: " + e.getMessage();
            throw IdentityException.error(authErrorMsg);
        }
    }
 
Example 14
Source File: StratosAuthenticationHandler.java    From attic-stratos with Apache License 2.0 4 votes vote down vote up
/**
 * Authenticate the user against the user store. Once authenticate, populate the {@link org.wso2.carbon.context.CarbonContext}
 * to be used by the downstream code.
 *
 * @param message
 * @param classResourceInfo
 * @return
 */
public Response handle(Message message, ClassResourceInfo classResourceInfo) {
    if (log.isDebugEnabled()) {
        log.debug(String.format("Authenticating request: [message-id] %s", message.getId()));
    }

    // If Mutual SSL is enabled
    HttpServletRequest request = (HttpServletRequest) message.get("HTTP.REQUEST");
    Object certObject = request.getAttribute("javax.servlet.request.X509Certificate");

    AuthorizationPolicy policy = message.get(AuthorizationPolicy.class);
    String username = policy.getUserName().trim();
    String password = policy.getPassword().trim();

    //sanity check
    if (StringUtils.isEmpty(username)) {
        log.error("username is seen as null/empty values");
        return Response.status(Response.Status.UNAUTHORIZED)
                .header("WWW-Authenticate", "Basic").type(MediaType.APPLICATION_JSON)
                .entity(new ResponseMessageBean(ResponseMessageBean.ERROR, "Username cannot be null")).build();
    } else if (certObject == null && (StringUtils.isEmpty(password))) {
        log.error("password is seen as null/empty values");
        return Response.status(Response.Status.UNAUTHORIZED)
                .header("WWW-Authenticate", "Basic").type(MediaType.APPLICATION_JSON)
                .entity(new ResponseMessageBean(ResponseMessageBean.ERROR, "password cannot be null")).build();
    }

    try {
        RealmService realmService = ServiceHolder.getRealmService();
        RegistryService registryService = ServiceHolder.getRegistryService();
        String tenantDomain = MultitenantUtils.getTenantDomain(username);
        int tenantId = realmService.getTenantManager().getTenantId(tenantDomain);

        UserRealm userRealm = null;
        if (certObject == null) {
            userRealm = AnonymousSessionUtil.getRealmByTenantDomain(registryService, realmService, tenantDomain);
            if (userRealm == null) {
                log.error("Invalid domain or unactivated tenant login");
                // is this the correct HTTP code for this scenario ? (401)
                return Response.status(Response.Status.UNAUTHORIZED).header("WWW-Authenticate", "Basic").
                        type(MediaType.APPLICATION_JSON).entity(
                        new ResponseMessageBean(ResponseMessageBean.ERROR, "Tenant not found")).build();
            }
        }
        username = MultitenantUtils.getTenantAwareUsername(username);
        if (certObject != null || userRealm.getUserStoreManager().authenticate(username, password)) {  // if authenticated

            // setting the correct tenant info for downstream code..
            PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
            carbonContext.setTenantDomain(tenantDomain);
            carbonContext.setTenantId(tenantId);
            carbonContext.setUsername(username);
            //populate the secuirtyContext of authenticated user
            SecurityContext securityContext = new StratosSecurityContext(username);
            message.put(SecurityContext.class, securityContext);

            // set the authenticated flag and let the request to continue
            AuthenticationContext.setAuthenticated(true);
            if (log.isDebugEnabled()) {
                log.debug("Authenticated using the " + CookieBasedAuthenticationHandler.class.getName() + "for username  :" +
                        username + "tenantDomain : " + tenantDomain + " tenantId : " + tenantId);
            }
            return null;
        } else {
            log.warn(String.format("Unable to authenticate the request: [message-id] %s", message.getId()));
            // authentication failed, request the authetication, add the realm name if needed to the value of WWW-Authenticate
            return Response.status(Response.Status.UNAUTHORIZED).header("WWW-Authenticate", "Basic").
                    type(MediaType.APPLICATION_JSON).entity(new ResponseMessageBean(ResponseMessageBean.ERROR,
                    "Authentication failed. Please check your username/password")).build();
        }
    } catch (Exception exception) {
        log.error(String.format("Authentication failed: [message-id] %s", message.getId()), exception);
        // server error in the eyes of the client. Hence 5xx HTTP code.
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).type(MediaType.APPLICATION_JSON).
                entity(new ResponseMessageBean(ResponseMessageBean.ERROR,
                        "Unexpected error. Please contact the system admin")).build();
    }
}
 
Example 15
Source File: OAuthHandler.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
public boolean isAuthenticated(Message message, ClassResourceInfo classResourceInfo) {
    // get the map of protocol headers
    Map protocolHeaders = (TreeMap) message.get(Message.PROTOCOL_HEADERS);
    // get the value for Authorization Header
    List authzHeaders = (ArrayList) protocolHeaders
            .get(SCIMConstants.AUTHORIZATION_HEADER);
    if (authzHeaders != null) {
        // get the authorization header value, if provided
        String authzHeader = (String) authzHeaders.get(0);

        // extract access token
        String accessToken = authzHeader.trim().substring(7).trim();
        // validate access token
        try {
            OAuth2ClientApplicationDTO validationApp = this.validateAccessToken(accessToken);
            OAuth2TokenValidationResponseDTO validationResponse = null;

            if (validationApp != null) {
                validationResponse = validationApp.getAccessTokenValidationResponse();
            }

            if (validationResponse != null && validationResponse.isValid()) {
                String userName = validationResponse.getAuthorizedUser();
                authzHeaders.set(0, userName);

                // setup thread local variable to be consumed by the provisioning framework.
                RealmService realmService = (RealmService) PrivilegedCarbonContext
                        .getThreadLocalCarbonContext().getOSGiService(RealmService.class);
                ThreadLocalProvisioningServiceProvider serviceProvider = new ThreadLocalProvisioningServiceProvider();
                serviceProvider.setServiceProviderName(validationApp.getConsumerKey());
                serviceProvider
                        .setServiceProviderType(ProvisioningServiceProviderType.OAUTH);
                serviceProvider.setClaimDialect(SCIMProviderConstants.DEFAULT_SCIM_DIALECT);
                serviceProvider.setTenantDomain(MultitenantUtils.getTenantDomain(userName));
                IdentityApplicationManagementUtil
                        .setThreadLocalProvisioningServiceProvider(serviceProvider);
                PrivilegedCarbonContext.startTenantFlow();
                PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
                String tenantDomain = MultitenantUtils.getTenantDomain(userName);
                carbonContext.setUsername(MultitenantUtils.getTenantAwareUsername(userName));
                carbonContext.setTenantId(realmService.getTenantManager().getTenantId(tenantDomain));
                carbonContext.setTenantDomain(tenantDomain);
                return true;
            }
        } catch (Exception e) {
            String error = "Error in validating OAuth access token.";
            log.error(error, e);
        }
    }
    return false;
}
 
Example 16
Source File: StratosAuthenticationHandler.java    From attic-stratos with Apache License 2.0 4 votes vote down vote up
/**
 * Authenticate the user against the user store. Once authenticate, populate
 * the {@link org.wso2.carbon.context.CarbonContext} to be used by the
 * downstream code.
 *
 * @param message
 * @param classResourceInfo
 * @return
 */
@Override
public Response handle(Message message, ClassResourceInfo classResourceInfo) {
    // If Mutual SSL is enabled
    HttpServletRequest request = (HttpServletRequest) message.get("HTTP.REQUEST");
    Object certObject = request.getAttribute("javax.servlet.request.X509Certificate");

    AuthorizationPolicy policy = message.get(AuthorizationPolicy.class);
    String username = policy.getUserName().trim();
    String password = policy.getPassword().trim();

    // sanity check
    if ((username == null) || username.equals("")) {
        log.error("username is seen as null/empty values.");
        return Response.status(Response.Status.UNAUTHORIZED)
                .header("WWW-Authenticate", "Basic").type(MediaType.APPLICATION_JSON)
                .entity(Utils.buildMessage("Username cannot be null")).build();
    } else if (certObject == null && ((password == null) || password.equals(""))) {
        log.error("password is seen as null/empty values.");
        return Response.status(Response.Status.UNAUTHORIZED)
                .header("WWW-Authenticate", "Basic").type(MediaType.APPLICATION_JSON)
                .entity(Utils.buildMessage("password cannot be null")).build();
    }

    try {
        RealmService realmService = ServiceHolder.getRealmService();
        RegistryService registryService = ServiceHolder.getRegistryService();
        String tenantDomain = MultitenantUtils.getTenantDomain(username);
        int tenantId = realmService.getTenantManager().getTenantId(tenantDomain);

        UserRealm userRealm = null;
        if (certObject == null) {
            userRealm =
                    AnonymousSessionUtil.getRealmByTenantDomain(registryService,
                            realmService, tenantDomain);
            if (userRealm == null) {
                log.error("Invalid domain or unactivated tenant login");
                // is this the correct HTTP code for this scenario ? (401)
                return Response.status(Response.Status.UNAUTHORIZED)
                        .header("WWW-Authenticate", "Basic")
                        .type(MediaType.APPLICATION_JSON)
                        .entity(Utils.buildMessage("Tenant not found")).build();
            }
        }
        username = MultitenantUtils.getTenantAwareUsername(username);
        if (certObject != null ||
                userRealm.getUserStoreManager().authenticate(username, password)) { // if
            // authenticated

            // setting the correct tenant info for downstream code..
            PrivilegedCarbonContext carbonContext =
                    PrivilegedCarbonContext.getThreadLocalCarbonContext();
            carbonContext.setTenantDomain(tenantDomain);
            carbonContext.setTenantId(tenantId);
            carbonContext.setUsername(username);
            // populate the secuirtyContext of authenticated user
            SecurityContext securityContext = new StratosSecurityContext(username);
            message.put(SecurityContext.class, securityContext);

            // set the authenticated flag and let the request to continue
            AuthenticationContext.setAuthenticated(true);
            if (log.isDebugEnabled()) {
                log.debug("authenticated using the " +
                        CookieBasedAuthenticationHandler.class.getName() + "for username  :" +
                        username + "tenantDomain : " + tenantDomain + " tenantId : " +
                        tenantId);
            }
            return null;
        } else {
            log.warn("unable to authenticate the request");
            // authentication failed, request the authetication, add the
            // realm name if needed to the value of WWW-Authenticate
            return Response.status(Response.Status.UNAUTHORIZED)
                    .header("WWW-Authenticate", "Basic")
                    .type(MediaType.APPLICATION_JSON)
                    .entity(Utils.buildMessage("Authentication failed. Please "
                            + "check your username/password"))
                    .build();
        }
    } catch (Exception exception) {
        log.error("Authentication failed", exception);
        // server error in the eyes of the client. Hence 5xx HTTP code.
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                .type(MediaType.APPLICATION_JSON)
                .entity(Utils.buildMessage("Unexpected error. Please contact the system admin"))
                .build();
    }

}
 
Example 17
Source File: StratosAuthenticationHandler.java    From product-private-paas with Apache License 2.0 4 votes vote down vote up
/**
 * Authenticate the user against the user store. Once authenticate, populate the {@link org.wso2.carbon.context.CarbonContext}
 * to be used by the downstream code.
 *
 * @param message
 * @param classResourceInfo
 * @return
 */
public Response handle(Message message, ClassResourceInfo classResourceInfo) {
    // If Mutual SSL is enabled
    HttpServletRequest request = (HttpServletRequest) message.get("HTTP.REQUEST");
    Object certObject = request.getAttribute("javax.servlet.request.X509Certificate");

    AuthorizationPolicy policy = (AuthorizationPolicy) message.get(AuthorizationPolicy.class);
    String username = policy.getUserName().trim();
    String password = policy.getPassword().trim();

    //sanity check
    if ((username == null) || username.equals("")) {
        log.error("username is seen as null/empty values.");
        return Response.status(Response.Status.UNAUTHORIZED).header("WWW-Authenticate", "Basic")
                .type(MediaType.APPLICATION_JSON).entity(Utils.buildMessage("Username cannot be null")).build();
    } else if (certObject == null && ((password == null) || password.equals(""))) {
        log.error("password is seen as null/empty values.");
        return Response.status(Response.Status.UNAUTHORIZED).header("WWW-Authenticate", "Basic")
                .type(MediaType.APPLICATION_JSON).entity(Utils.buildMessage("password cannot be null")).build();
    }

    try {
        RealmService realmService = ServiceHolder.getRealmService();
        RegistryService registryService = ServiceHolder.getRegistryService();
        String tenantDomain = MultitenantUtils.getTenantDomain(username);
        int tenantId = realmService.getTenantManager().getTenantId(tenantDomain);

        UserRealm userRealm = null;
        if (certObject == null) {
            userRealm = AnonymousSessionUtil.getRealmByTenantDomain(registryService, realmService, tenantDomain);
            if (userRealm == null) {
                log.error("Invalid domain or unactivated tenant login");
                // is this the correct HTTP code for this scenario ? (401)
                return Response.status(Response.Status.UNAUTHORIZED).header("WWW-Authenticate", "Basic").
                        type(MediaType.APPLICATION_JSON).entity(Utils.buildMessage("Tenant not found")).build();
            }
        }
        username = MultitenantUtils.getTenantAwareUsername(username);
        if (certObject != null || userRealm.getUserStoreManager()
                .authenticate(username, password)) {  // if authenticated

            // setting the correct tenant info for downstream code..
            PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
            carbonContext.setTenantDomain(tenantDomain);
            carbonContext.setTenantId(tenantId);
            carbonContext.setUsername(username);
            //populate the secuirtyContext of authenticated user
            SecurityContext securityContext = new StratosSecurityContext(username);
            message.put(SecurityContext.class, securityContext);

            // set the authenticated flag and let the request to continue
            AuthenticationContext.setAuthenticated(true);
            if (log.isDebugEnabled()) {
                log.debug("authenticated using the " + CookieBasedAuthenticationHandler.class.getName()
                        + "for username  :" +
                        username + "tenantDomain : " + tenantDomain + " tenantId : " + tenantId);
            }
            return null;
        } else {
            log.warn("unable to authenticate the request");
            // authentication failed, request the authetication, add the realm name if needed to the value of WWW-Authenticate
            return Response.status(Response.Status.UNAUTHORIZED).header("WWW-Authenticate", "Basic").
                    type(MediaType.APPLICATION_JSON)
                    .entity(Utils.buildMessage("Authentication failed. Please " + "check your username/password"))
                    .build();
        }
    } catch (Exception exception) {
        log.error("Authentication failed", exception);
        // server error in the eyes of the client. Hence 5xx HTTP code.
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).type(MediaType.APPLICATION_JSON).
                entity(Utils.buildMessage("Unexpected error. Please contact the system admin")).build();
    }

}