如何在web.xml OSGI WAB自由角色映射中映射admin auth约束

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在web.xml OSGI WAB自由角色映射中映射admin auth约束相关的知识,希望对你有一定的参考价值。

我正在构建一个单独的admincenter工具,需要管理员角色才能访问。如何在web.xml的auth-constraint中指定它。

我试过下面,它不起作用

<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>

server.xml

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

登录后,如果我尝试访问此URL,则表示我无权访问它。我需要在某处做绑定吗?

IBM-Authorization-Roles: com.ibm.ws.management添加到MANIFEST.MF后,我可以使用admin角色访问它,但不能使用test角色访问它。配置有什么问题。如何在osgi包中进行角色映射?

答案

web.xml添加额外的角色allAuthenticatedUsers允许他们与管理员用户。在关于OSGI捆绑安全性的ibm文档中没有找到太多内容。但它奏效了。

   <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>

我想我不需要<role-name>Administrator</role-name>。但request.isUserInRole('Administrator')无论如何都是真的。

更新任何一种情况我无法识别管理员,测试用户在应用程序中具有上述配置。使用IBM-Authorization-Roles: com.ibm.ws.management只能识别管理员 - request.isUserInRole('Administrator')将起作用。但即使用户使用该测试角色登录并且能够访问该URL,request.isUserInRole('test')也不是。

这很奇怪 - 它允许访问但是当我检查角色是什么时,它不起作用。看起来IBM中存在一个问题 - Liberty代码(17.0.0.4)。但不确定。

另一答案

我使用spring security实现了相同的功能。假设您有应用程序,并且您拥有不同角色的不同用户,因此您可以通过spring安全性来实现。使用Spring安全性是保护应用程序安全的最佳方式。

1.在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.然后通过用户在Spring-security.xml中添加条目,将admin / framework / something / doAction添加到用户/例如/ framework / something / do中添加要限制的URL

<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将按角色过滤用户。您可以在此处进行验证。

@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");
        // ((HttpServle

以上是关于如何在web.xml OSGI WAB自由角色映射中映射admin auth约束的主要内容,如果未能解决你的问题,请参考以下文章

Tomcat 安全角色映射

如何在 Tomcat 的 web.xml 中为欢迎文件映射过滤器?

如何设置 web.xml 和 dispatcher-servlet.xml 进行映射?

如何用 web.xml 映射 Html 文件?

我应该如何从我的 web.xml 文件中的不同文件夹映射相同命名的 jsp 文件?

web.xml 过滤器如何工作?您可以将两个过滤器映射到所有页面(/ *)并指定顺序吗?