5

I am building a separate admincenter tool which required admin role to access. How can I specify it in auth-constraint of web.xml.

I tried below, it is not working

<security-constraint>
    <web-resource-collection>
        <web-resource-name>commonlogin-secure-resources</web-resource-name>
        <url-pattern>/rest/readyToLand</url-pattern>
    </web-resource-collection>
    <auth-constraint>
        <role-name>test</role-name>
        <role-name>Administrator</role-name>
    </auth-constraint>
    <user-data-constraint>
        <transport-guarantee>CONFIDENTIAL</transport-guarantee>
    </user-data-constraint>
</security-constraint>

In server.xml

<basicRegistry>
    <user name="admin" password="adminPassword"/>
</basicRegistry>    
<administrator-role>
    <user>admin</user>
</administrator-role>

After login if I try to access this url it is saying i do not have permission to access it. Do i need to do binding somewhere??

After adding IBM-Authorization-Roles: com.ibm.ws.management to MANIFEST.MF I am able to access it with admin role, but not with test role. What's wrong with the configuration. How can I do role mapping in osgi bundle?

Dyapa Srikanth
  • 1,231
  • 2
  • 22
  • 60

2 Answers2

1

In web.xml added extra role allAuthenticatedUsers to allow them along with admin user. Didn't find much in ibm documentation about OSGI bundle security. But it worked.

   <security-constraint>
        <web-resource-collection>
            <url-pattern>/rest/readyToLand</url-pattern>
            <url-pattern>/LoginSuccess.jsp</url-pattern>
            <http-method>GET</http-method>
            <http-method>POST</http-method>
        </web-resource-collection>
        <auth-constraint>
            <role-name>Administrator</role-name>
            <role-name>allAuthenticatedUsers</role-name>
        </auth-constraint>
    </security-constraint>
    <security-role id="SecurityRole_1">
        <description>Administrator role</description>
        <role-name>Administrator</role-name>
    </security-role>
    <security-role id="SecurityRole_2">
        <description>Any Role</description>
        <role-name>allAuthenticatedUsers</role-name>
    </security-role>

I think I don't require <role-name>Administrator</role-name>. But request.isUserInRole('Administrator') is giving true at any case.

Updated Any of the case i am unable to identify both admin, test users in application with above configurations. With IBM-Authorization-Roles: com.ibm.ws.management only admin can be identified - request.isUserInRole('Administrator') will work. But not request.isUserInRole('test') even though user logged in with that test role & able to access that URL.

It is just weird - it is allowing access but when i check what is the role, it is not working. Looks like there is an issue in IBM - Liberty code (17.0.0.4). But not sure.

Dyapa Srikanth
  • 1,231
  • 2
  • 22
  • 60
1

I have implemented same using spring security. Suppose that you have application and you have different users with different roles so you can achieve by spring security. Using spring security is the best way to secure your application.

1.Add Entries in Web.xml

<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

2. Then add urls you want to restrict to user like /framework/something/do by admin /framework/something/doAction by user Add Entries in Spring-security.xml

<security:http use-expressions="true" auto-config="false"
    entry-point-ref="http403EntryPoint" pattern="/framework/something/doAction"
    create-session="stateless">
    <security:csrf disabled="true" />
    <security:custom-filter position="PRE_AUTH_FILTER"
        ref="authorizationGlobalFilterBean" />
</security:http>

3.AuthorizationGlobalFilterBean will filter user by role.. You can put your validation here.

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

    logger.debug("Authorization  Filter Called#########################################################");
    // logger.debug("sessionServiceImpl..."+sessionServiceImpl);
    // logger.debug("iUserDao..."+iUserDao);

    HttpServletRequest httpReq = (HttpServletRequest) request;
    // logger.debug("http Request URL.."+httpReq.getRequestURL());

    HttpServletRequest r = (HttpServletRequest) request;
    String sessionObjId = getSessionIdFromHeader(r);

    // check session
    boolean isSessionExpired = checkSessionExpired(sessionObjId);

    if (isSessionExpired) {
        HttpServletResponse resp = (HttpServletResponse) response;
        resp.addHeader("sessionId", "");
        resp.addHeader("status", "false");
        resp.addHeader("message", "Session Expired");
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Session Expired");
        return;
    }

    // CustomUserDetailsService cs = new CustomUserDetailsService();
    UserDetails user = loadUserByUsername(sessionObjId);

    if (user == null) {
        HttpServletResponse resp = (HttpServletResponse) response;
        resp.addHeader("sessionId", "");
        resp.addHeader("status", "false");
        resp.addHeader("message", "User Not Found");
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "User Not Found");
        return;
    }
    // logger.debug("user..."+user);
    logger.debug("user name.." + user.getUsername());
    logger.debug("user name.." + user.getUsername());

    List<String> ltUserPrivileges = userServiceImpl.findUserPrivilege(user.getUsername());
    logger.debug("ltUserPrivileges..." + ltUserPrivileges);

    String requestURI = httpReq.getRequestURI();
    // String requestURL = httpReq.getRequestURL().toString();
    String contextPath = httpReq.getContextPath();
    String queryString = httpReq.getQueryString();
    // String port = httpReq.getServerPort()+"";
    // logger.debug("request URL..."+httpReq.getRequestURL());
    // logger.debug("requestURI..."+requestURI);
    // logger.debug("contextPath..."+contextPath);
    // logger.debug("queryString..."+queryString);
    int i = 0;
    if ((i = requestURI.indexOf(contextPath)) >= 0) {
        // logger.debug("removing context from path.."+i);
        requestURI = requestURI.substring(i + contextPath.length());
        // logger.debug("new requestURI.."+requestURI);
    }
    if (queryString != null && queryString.trim().length() > 0) {
        requestURI = requestURI + "?" + queryString;
    }
    logger.debug("Final requestURI.." + requestURI);

    /*
     * if( (i=requestURL.indexOf(port))>=0){
     * logger.debug("removing port from path.."+i);
     * requestURL = requestURL.substring(i+port.length());
     * logger.debug("new requestURL.."+requestURL);
     * }
     */

    List<String> ltPrev = getMatchingUrlPrivileges(requestURI,request);
    boolean allowed = false;
    if (ltPrev != null && ltPrev.size() > 0) {
        for (String expectedPrev : ltPrev) {
            logger.debug("Expected Previleges.." + expectedPrev);
            if (ltUserPrivileges != null && ltUserPrivileges.contains(expectedPrev)) {
                logger.debug("Previlege Available.....................................................");
                allowed = true;
                break;
            }
        }
        Authentication authentication;
        try { // If the credentials to not match then an AuthenticationException is thrown.
            authentication = attemptAuthentication(user);

            // If successfully authenticated then pass the request to the success handler
            if (authentication.isAuthenticated())
                SecurityContextHolder.getContext().setAuthentication(authentication);

            logger.debug("successfull authentiation");
        } catch (AuthenticationException exception) {
            // Pass the request to authentication failure handler.
            logger.error("unsuccessfull authentication", exception);
            return;
        }

    } else {

        logger.debug("There is no user previleges  required for the URL , so 
      allow it");
        allowed = true;
        Authentication authentication;
        try { // If the credentials to not match then an 
            // AuthenticationException is thrown.
            authentication = attemptAuthentication(user);

            // If successfully authenticated then pass the request to the success handler
            if (authentication.isAuthenticated())
                SecurityContextHolder.getContext().setAuthentication(authentication);

            logger.debug("successfull authentiation");
        } catch (AuthenticationException exception) {
            // Pass the request to authentication failure handler.
            logger.error("unsuccessfull authentication", exception);
            return;
        }
    }

    if (!allowed) {
        logger.debug("*****************************User 
         AccessDenied******************************");
        // throw new PreAuthenticationUserNotFound("User Access Denied");
        // ((HttpServletResponse) 
        response).sendError(HttpServletResponse.SC_FORBIDDEN, "User Access 
       Denied");
        ((HttpServletResponse) response).setContentType("application/json");
        ((HttpServletResponse) response).setStatus(HttpServletResponse.SC_FORBIDDEN);
        try {
            JSONObject json  = new JSONObject();
            json.put("msg", "User Access Denied");
            json.put("url", requestURI);
            ((HttpServletResponse) response).getOutputStream().println(json.toString());
        } catch (JSONException e) {
            logger.error("Error: ", e);
        }
        return;
    }

    /**
     * if(user.getUsername().equalsIgnoreCase("ypalrecha") &&
     * httpReq.getRequestURL().indexOf("framework/dag/dagWithParams")>=0){
     * logger.debug("*****************************User Access Denied******************************");
     * throw new PreAuthenticationUserNotFound("User Access Denied");
     * }
     **/
    /*
     * if(user){
     * throw new PreAuthenticationUserNotFound("Session not valid or expired");
     * }
     */

    // logger.debug("Request Session..."+r.getHeader("sessionId"));
    // logger.debug("Request Status..."+r.getHeader("status"));

    chain.doFilter(request, response);
}

Authentication attemptAuthentication(UserDetails user) throws AuthenticationException, IOException, ServletException {

    String username = user.getUsername();
    String password = user.getPassword();

    Authentication authentication = new UsernamePasswordAuthenticationToken(username, password, getAuthorities("Admin"));
    return authentication;
}

You have Roles for user Further ..

public List<String> getRoles(String role) {

    List<String> roles = new ArrayList<String>();
    if (role.trim().equalsIgnoreCase("Admin".trim())) {
        roles.add("ROLE_ADMIN");
    }

    if (role.trim().equalsIgnoreCase("User".trim())) {
        roles.add("ROLE_USER");
    }
    return roles;
}
Sheel
  • 847
  • 2
  • 8
  • 20
  • Currently i am expecting container to secure OSGI WAB, web application with admin & normal user roles. I don't think spring security will do anything here. Admin role is at server level, which will some special operations throw IBM admin center. I am unable to identify this user role in my application. – Dyapa Srikanth Mar 13 '18 at 11:28