Refer the code segment (jsp) below.
In the UI I have two text boxes to provide username and password.
If domain name is not specified in the username, it assumes a login of a super tenant or a super tenant user (hence domain is set to carbon.super). For tenant admins and users, relevant domain needs to be specified, and relevant tenant's UserRealm is loaded using the method AnonymousSessionUtil.getRealmByTenantDomain
For more about PrivilegedCarbonContext, refer here
<%@ page import="org.wso2.carbon.context.CarbonContext" %> <%@ page import="org.wso2.carbon.context.PrivilegedCarbonContext" %> <%@ page import="org.wso2.carbon.user.api.UserRealm" %> <%@ page import="org.wso2.carbon.user.core.service.RealmService" %> <%@ page import="org.wso2.carbon.user.api.UserRealmService" %> <%@ page import="org.wso2.carbon.user.api.UserStoreException" %> <%@ page import="org.wso2.carbon.user.api.UserStoreManager" %> <%@ page import="org.wso2.carbon.core.util.AnonymousSessionUtil" %> <%@ page import="org.wso2.carbon.registry.core.service.RegistryService" %> <%! String removeTenantDomain(String userName) { if(userName.contains("@")) { String[] arr = userName.split("@"); return arr[0]; } return userName; } %> <% String username = request.getParameter("username"); String password = request.getParameter("password"); String tenantDomain = "carbon.super"; boolean status = false; if (username != null && username.trim().length() > 0) { try { PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); RealmService realmService = (RealmService) carbonContext.getOSGiService(RealmService.class); RegistryService registryService = (RegistryService) carbonContext.getOSGiService(RegistryService.class); // If domain is specified if(username.contains("@")) { String[] arr = username.split("@"); tenantDomain = arr[1]; } UserRealm realm = AnonymousSessionUtil.getRealmByTenantDomain(registryService,realmService,tenantDomain); status = realm.getUserStoreManager().authenticate(removeTenantDomain(username), password); } catch (Exception e) { e.printStackTrace(); } } if (status) { session.setAttribute("logged-in", "true"); session.setAttribute("username", username); response.sendRedirect("login.jsp"); } else { session.invalidate(); response.sendRedirect("login.jsp?failed=true"); } %>