关于weblogic:全网最全weblogic自定义Provider开发教程

52次阅读

共计 19538 个字符,预计需要花费 49 分钟才能阅读完成。

weblogic Provider

做过 OAM,OID 我的项目的同学应该都晓得,要集成 OAM 和 OID 须要在 weblogic 的 Security Realms 中配置 Provider,那什么是 Provider?在业务零碎中,认证和受权始终是最简单的一块,体现在

  • 认证协定多样性,比方 OAuth2,SAML 等
  • 认证形式多样性,比方二次认证,验证码认证等
  • 认证策略多样性,比方有多个认证源,策略能够多样性,能够是一个不通过就不通过,也能够是只有有一个通过就全副通过
  • 自定义认证的需要,这个在企业外面还是挺多的,一些零碎上线时还没有相应的规范进去,所以都是自开发
  • 明码认证策略多样性,大部分零碎明码存储是不可逆的,如果一开始没有将明码存储在 LDAP 之类的服务里,后续如果要做降级,就无奈拿到原始明码,那么就须要自定义明码认证策略。

总之,认证并不是用户名明码验证这么简略,所以 weblogic 针对不同的认证场景提供不同的 Provider,weblogic 作为成熟的商业服务器,天然蕴含大部分认证场景,以 weblogic 11g 为例,蕴含了以下 Provider

  • SAML2IdentityAsserter
  • X3gppAssertedIdentityAsserter
  • X3gppAssertedIdentityStrictAsserter
  • DBMSDigestIdentityAsserter
  • IdentityAssertionAuthenticator
  • IdentityHeaderAsserter
  • LdapDigestIdentityAsserter
  • PAssertedIdentityAsserter
  • PAssertedIdentityStrictAsserter
  • CrossTenantAuthenticator
  • TrustServiceIdentityAsserter
  • OSSOIdentityAsserter
  • OAMIdentityAsserter
  • OAMAuthenticator
  • ActiveDirectoryAuthenticator
  • CustomDBMSAuthenticator
  • DefaultAuthenticator
  • DefaultIdentityAsserter
  • IPlanetAuthenticator
  • LDAPAuthenticator
  • LDAPX509IdentityAsserter
  • NegotiateIdentityAsserter
  • NovellAuthenticator
  • OpenLDAPAuthenticator
  • OracleInternetDirectoryAuthenticator
  • OracleVirtualDirectoryAuthenticator
  • ReadOnlySQLAuthenticator
  • SQLAuthenticator
  • WindowsNTAuthenticator
  • SAMLAuthenticator
  • SAMLIdentityAsserter
  • SAMLIdentityAsserterV2

通过观察下面的列表,咱们发现有两类 Provider

  • xxxAsserter
  • xxxAuthenticator

那么这两个有什么区别,搞清楚这两个的区别十分重要,你进小区,如果你有带房卡就能够间接进,如果没有,你就得证实你是小区的户主,可能就须要你提供身份证,电话之类的信息,同理,如果带着 token 或者 cookie 拜访零碎那么就须要 Asserter 进行认证受权,如果带着用户名明码登录零碎就须要 Authenticator 进行认证,总之,Asserter 看 token,Authenticator 看明码,那配过 OAM 单点登录的同学应该晓得,要实现 OAM 单点登录须要配置两个货色

  • 配置 OAMIdentityAsserter
  • 配置 OracleInternetDirectoryAuthenticator

那问题来了,为什么有了 OAMIdentityAsserter 还须要 OracleInternetDirectoryAuthenticator?用户在登录页登录后,后续所有的申请都是通过 OAMIdentityAsserter 解析 OAM 信息进行认证受权,那么还须要 Authenticator 干嘛?Asserter 获取的用户信息无限,只能从 token 外面解析出无限的用户信息,个别就是用户 ID,那么须要判断用户存不存在或者须要更多的用户信息就须要借助 Authenticator

JAAS

JAAS(Java Authentication and Authorization Service)是 Java 提供集成在 JDK 中(在 javax.security.auth 门路下)规范用户认证与受权模型,简略来说,JAAS 提供了一系列的接口,不同认证形式通过实现接口从而能够以插件的模式集成到 java 应用程序中,JAAS 架构图下

在 JAAS 中有几个重要的概念须要理解

  • Subject

Subject 示意请求者,可能是一个人也可能是一个设施

  • Principal

Principal 是关联在 Subject 下,后面提到 Subject 示意的是请求者,咱们用登录用户会更好了解点,那么 Principal 就是用户的账号,可能是用手机号登录的,也可能是用邮箱登录的,Subject 能够有多个 Principal

  • LoginContext

LoginContext 认证上下文,提供一系列认证办法,负责调用具体的认证实现(LoginModule),并且认证胜利后返回 Subject

  • LoginModule

认证的具体实现,其中 login 办法实现登录逻辑,存储后果,commit 办法最终将 Subject 提交到上下文

  • CallbackHandler

当 LoginModule 须要拿到用户名和明码等认证信息时,就须要调用 CallbackHandler 返回这些信息,在 gui 利用中,CallbackHandler 可能会弹出一个窗口让用户输出用户名和明码

  • Callback

LoginModule 须要获取的用户信息成为 Callback,比方须要向 CallbackHandler 获取用户名,那么就会创立一个 NameCallback,须要获取明码就会创立一个 PasswordCallback,CallbackHandler 依据 Callback 的类型返回用户信息

我的项目背景

某我的项目须要将 OAM 替换成其余产品,要求不能批改利用,做到无缝切换,利用部署在 webogic 上,通过 OAMIdentityAsserter 和 OracleInternetDirectoryAuthenticator 集成 OAM 和 OID 实现单点登录,利用局部配置如下

  • web.xml
   <security-constraint>
    <web-resource-collection>
        <web-resource-name>SecurePages</web-resource-name>
        <description>These pages are only accessible by authorized users.</description>
        <url-pattern>/*</url-pattern>
        <http-method>GET</http-method>
    </web-resource-collection>
    <auth-constraint>
        <description>These are the roles who have access.</description>
        <role-name>ValidUser</role-name>
    </auth-constraint>
    <user-data-constraint>
        <description>This is how the user data must be transmitted.</description>
        <transport-guarantee>NONE</transport-guarantee>
    </user-data-constraint>
</security-constraint>
<login-config>
    <auth-method>CLIENT-CERT</auth-method>
    <realm-name>myrealm</realm-name>
</login-config>
<security-role>
    <description>These are the roles who have access.</description>
    <role-name>ValidUser</role-name>
</security-role>
  • weblogic.xml
  <wls:security-role-assignment>
      <wls:role-name>ValidUser</wls:role-name>
      <wls:principal-name>users</wls:principal-name>
  </wls:security-role-assignment>

留神到 web.xml 中 login-config 的配置<auth-method>CLIENT-CERT</auth-method>,这个配置示意利用从上下文获取用户信息,也就是从 HttpServletRequest 的 getUserPrincipal 办法获取用户信息

实现计划

如果要做到不动利用代码的状况下实现切换,就得实现相似 OAMIdentityAsserter 的性能,也就是开发自定义 Asserter,这样对利用来说只有 Asserter 认证过仍然能够从上下文拿到用户信息。

开发自定义 Provider

接下来咱们须要自开发一个 Provider 来实现以下需要,在 http header 中如果蕴含 YUFU_REMOTE_USER,那么 value 就是用户 id,该申请视为曾经过认证,就跟 OAM 的 OAM_REMOTE_USER 实现机制一样

大家可能感觉这种认证机制太弱智了,很容易有平安问题,所以这个计划的前提条件是,后面须要有认证核心的反向代理,不能让用户绕过认证核心进行拜访,能够在防火墙层面将申请隔离

Provider 是通过 weblogic MBean 实现,所以开发流程和和 MBean 根本一样

  • 创立 MBean 形容文件

YufuSSOIdentityAsserter.xml

<?xml version="1.0" ?>
<!DOCTYPE MBeanType SYSTEM "commo.dtd">

<MBeanType
        Name="YufuSSOIdentityAsserter"
        DisplayName="YufuSSOIdentityAsserter"
        Package="com.yufu.plugin.weblogic"
        Extends="weblogic.management.security.authentication.IdentityAsserter"
        PersistPolicy="OnUpdate"
>
    <MBeanAttribute
            Name="ProviderClassName"
            Type="java.lang.String"
            Writeable="false"
            Preprocessor="weblogic.management.configuration.LegalHelper.checkClassName(value)"
            Default="&quot;com.yufu.plugin.weblogic.YufuSSOIdentityAsserterProviderImpl&quot;"
    />

    <MBeanAttribute
            Name="Description"
            Type="java.lang.String"
            Writeable="false"
            Default="&quot; 得帆云 weblogic 认证插件 &quot;"
    />

    <MBeanAttribute
            Name="Version"
            Type="java.lang.String"
            Writeable="false"
            Default="&quot;1.0&quot;"
    />

    <MBeanAttribute
            Name="SupportedTypes"
            Type="java.lang.String[]"
            Writeable="false"
            Default="new String[] { &quot;YUFU_REMOTE_USER&quot;}"
    />

    <MBeanAttribute
            Name="ActiveTypes"
            Type="java.lang.String[]"
            Default="new String[] { &quot;YUFU_REMOTE_USER&quot;}"
    />


    <MBeanAttribute
            Name="Base64DecodingRequired"
            Type="boolean"
            Writeable="false"
            Default="false"
            Description="See MyIdentityAsserter-doc.xml."
    />

</MBeanType>

该文件次要定义 Provider 的实现类和相干配置,定义在这里的属性在 weblogic 创立 Provider 时会显示在界面上,SupportedTypes 示意反对的 token 类型,这里就是指 token 名称也就是 http header 名称,ActiveTypes 示意默认抉择的 token 类型。

  • 筹备以下三个 java 文件

YufuSSOIdentityAsserterProviderImpl.java

package com.yufu.plugin.weblogic;

import java.util.HashMap;

import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.login.AppConfigurationEntry;
import javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag;

import weblogic.management.security.ProviderMBean;
import weblogic.security.provider.PrincipalValidatorImpl;
import weblogic.security.service.ContextHandler;
import weblogic.security.spi.*;

public final class YufuSSOIdentityAsserterProviderImpl implements AuthenticationProviderV2, IdentityAsserterV2 {
    final static private String TOKEN_TYPE = "YUFU_REMOTE_USER";

    private String description;
    private LoginModuleControlFlag controlFlag;


    public void initialize(ProviderMBean mbean, SecurityServices services) {System.out.println("插件初始化");
        YufuSSOIdentityAsserterMBean asserterBean = (YufuSSOIdentityAsserterMBean) mbean;
        description = asserterBean.getDescription() + "\n" + asserterBean.getVersion();
        controlFlag = LoginModuleControlFlag.SUFFICIENT;
    }

    /**
     * 外围认证逻辑
     *
     * @param type    token 名称
     * @param token   token 值(byte[]类型)* @param context
     * @return
     * @throws IdentityAssertionException
     */
    public CallbackHandler assertIdentity(String type, Object token, ContextHandler context) throws IdentityAssertionException {System.out.println("\tType\t\t=" + type);
        System.out.println("\tToken\t\t=" + token);
        this.validate(type, token);
        byte[] tokenBytes = (byte[]) token;
        if (tokenBytes == null || tokenBytes.length < 1) {
            String error = "received empty token byte array";
            throw new IdentityAssertionException(error);
        }
        String userName = new String(tokenBytes);
        return new YufuSSOCallbackHandlerImpl(userName);
    }

    private void validate(String type, Object token) throws IdentityAssertionException {if (!(TOKEN_TYPE.equals(type))) {
            String error = "unknown token type \"" + type + "\"."+" Expected " + TOKEN_TYPE;
            throw new IdentityAssertionException(error);
        }

        if (!(token instanceof byte[])) {String error = "received unknown token class \"" + token.getClass() + "\"."+" Expected a byte[].";
            System.out.println("\tError:" + error);
            throw new IdentityAssertionException(error);
        }
    }


    public AppConfigurationEntry getLoginModuleConfiguration() {HashMap options = new HashMap();
        return getConfiguration(options);
    }

    /**
     * 定义 LoginModule 实现类
     *
     * @param options
     * @return
     */
    private AppConfigurationEntry getConfiguration(HashMap options) {
        return new
                AppConfigurationEntry(
                "com.yufu.plugin.weblogic.YufuSSOLoginModuleImpl",
                controlFlag,
                options
        );
    }

    public AppConfigurationEntry getAssertionModuleConfiguration() {HashMap options = new HashMap();
        options.put("IdentityAssertion", "true");
        return getConfiguration(options);
    }

    public PrincipalValidator getPrincipalValidator() {return new PrincipalValidatorImpl();
    }

    public String getDescription() {return description;}

    public void shutdown() {}

    public IdentityAsserterV2 getIdentityAsserter() {return this;}

}

YufuSSOLoginModuleImpl.java

package com.yufu.plugin.weblogic;
import java.io.IOException;
import java.util.Map;
import java.util.Vector;
import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.login.LoginException;
import javax.security.auth.spi.LoginModule;
import weblogic.security.principal.WLSGroupImpl;
import weblogic.security.principal.WLSUserImpl;
final public class YufuSSOLoginModuleImpl implements LoginModule {
    private Subject subject;
    private CallbackHandler callbackHandler;
    private boolean loginSucceeded;
    private boolean principalsInSubject;
    private Vector principalsForSubject = new Vector();

    public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) {System.out.println("YufuSSOLoginModuleImpl.initialize");
        this.subject = subject;
        this.callbackHandler = callbackHandler;
    }

    /**
     * 登录逻辑
     * @return
     * @throws LoginException
     */
    public boolean login() throws LoginException {System.out.println("插件校验登录");
        Callback[] callbacks = getCallbacks();
        String userName = getUserName(callbacks);
        loginSucceeded = true;
        principalsForSubject.add(new WLSUserImpl(userName));
        addGroupsForSubject(userName);
        return loginSucceeded;
    }

    /**
     * 确认登录胜利
     *
     * @return
     * @throws LoginException
     */
    public boolean commit() throws LoginException {if (loginSucceeded) {subject.getPrincipals().addAll(principalsForSubject);
            principalsInSubject = true;
            return true;
        } else {return false;}
    }
    public boolean abort() throws LoginException {if (principalsInSubject) {subject.getPrincipals().removeAll(principalsForSubject);
            principalsInSubject = false;
        }
        return true;
    }
    public boolean logout() throws LoginException {return true;}
    private void throwLoginException(String msg) throws LoginException {throw new LoginException(msg);
    }
    private Callback[] getCallbacks() throws LoginException {if (callbackHandler == null) {throwLoginException("短少 callback 处理器");
        }
        Callback[] callbacks = new Callback[1];
        try {callbackHandler.handle(callbacks);
        } catch (IOException e) {throw new LoginException(e.toString());
        } catch (UnsupportedCallbackException e) {throwLoginException(e.toString() + " " + e.getCallback().toString());
        }
        return callbacks;
    }
    private String getUserName(Callback[] callbacks) throws LoginException {String userName = ((NameCallback) callbacks[0]).getName();
        if (userName == null) {throwLoginException("Username 为空.");
        }
        return userName;
    }
    private void addGroupsForSubject(String userName) {
        String groupName = "YufuPerimeterAtnUsers";
        System.out.println("\tgroupName\t=" + groupName);
        principalsForSubject.add(new WLSGroupImpl(groupName));
    }
}

YufuSSOCallbackHandlerImpl.java

package com.yufu.plugin.weblogic;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
class YufuSSOCallbackHandlerImpl implements CallbackHandler {
    private String userName;

    YufuSSOCallbackHandlerImpl(String user) {userName = user;}

    public void handle(Callback[] callbacks) throws UnsupportedCallbackException {for (int i = 0; i < callbacks.length; i++) {Callback callback = callbacks[i];
            if (!(callback instanceof NameCallback)) {throw new UnsupportedCallbackException(callback, "Unrecognized Callback");
            }
            NameCallback nameCallback = (NameCallback) callback;
            nameCallback.setName(userName);
        }
    }
}
  • 筹备 ant 构建文件

build.xml

<project name="Expenselink Build" default="all" basedir=".">
<property name="fileDir" value="test" />

<target name="all" depends="build"/>

<target name="build" depends="clean,build.mdf,build.mjf"/>

<target name="clean">
<delete dir="${fileDir}" failonerror="false"/>
<delete file="YufuSSOIdentityAsserter.jar" failonerror="false"/>
<echo message="Clean finish" />
</target>

<!-- helper to build an MDF (mbean definition file) -->
<target name="build.mdf">
<java dir="${basedir}" fork="false" classname="weblogic.management.commo.WebLogicMBeanMaker">
<arg line="-files ${fileDir}" />
<arg value="-createStubs" />
<arg line="-MDF YufuSSOIdentityAsserter.xml" />
</java>
<echo message="Created Supporting Classes" />
</target>

<target name="build.mjf">

<copy todir="${fileDir}" flatten="true">
<fileset dir=".">
<include name="*.java" />
</fileset>
</copy>

<java dir="${basedir}" fork="false" classname="weblogic.management.commo.WebLogicMBeanMaker">
<arg line="-MJF YufuSSOIdentityAsserter.jar" />
<arg line="-files ${fileDir}" />
</java>
<echo message="Created Mbean Jar" />
</target>

</project>

将这些文件上传到 weblogic 服务器

$ ll
-rw-r--r-- 1 oracle oinstall  1102 May 11 10:03 build.xml
-rw-r--r-- 1 oracle oinstall   890 May 11 09:58 YufuSSOCallbackHandlerImpl.java
-rw-r--r-- 1 oracle oinstall  3194 May 11 10:34 YufuSSOIdentityAsserterProviderImpl.java
-rw-r--r-- 1 oracle oinstall  1576 May 11 09:58 YufuSSOIdentityAsserter.xml
-rw-r--r-- 1 oracle oinstall  4585 May 11 09:58 YufuSSOLoginModuleImpl.java

$MIDDLEWARE_HOME/wlserver_10.3/server/lib/mbeantypes/commo.dtd 文件复制到当前目录下

$ ll
-rw-r--r-- 1 oracle oinstall  1102 May 11 10:03 build.xml
-rw-r--r-- 1 oracle oinstall  7993 May 11 09:58 commo.dtd
-rw-r--r-- 1 oracle oinstall   890 May 11 09:58 YufuSSOCallbackHandlerImpl.java
-rw-r--r-- 1 oracle oinstall  3194 May 11 10:34 YufuSSOIdentityAsserterProviderImpl.java
-rw-r--r-- 1 oracle oinstall  1576 May 11 09:58 YufuSSOIdentityAsserter.xml
-rw-r--r-- 1 oracle oinstall  4585 May 11 09:58 YufuSSOLoginModuleImpl.java
  • 设置 weblogic 上下文环境
cd $MIDDLEWARE_HOME/user_projects/domains/portal_domain/bin/
. ./setDomainEnv.sh

执行 setDomainEnv.sh 的目标是设置 weblogic 上下文环境,这样在后续的脚本执行过程中能够找到 weblogic 相干依赖 jar 包

MIDDLEWARE_HOME:中间件目录,比方 /u01/Middleware

命令的第二行第一个是有个点.,这个不能疏忽

  • 在 build.xml 目录下执行 ant 命令
$ ll
total 36
-rw-r--r-- 1 oracle oinstall 1102 May 11 10:03 build.xml
-rw-r--r-- 1 oracle oinstall 7993 May 11 09:58 commo.dtd
drwxr-xr-x 2 oracle oinstall 4096 May 11 13:00 src
-rw-r--r-- 1 oracle oinstall  890 May 11 09:58 YufuSSOCallbackHandlerImpl.java
-rw-r--r-- 1 oracle oinstall 3194 May 11 10:34 YufuSSOIdentityAsserterProviderImpl.java
-rw-r--r-- 1 oracle oinstall 1576 May 11 09:58 YufuSSOIdentityAsserter.xml
-rw-r--r-- 1 oracle oinstall 4585 May 11 09:58 YufuSSOLoginModuleImpl.java


$ ant
Buildfile: build.xml

clean:
   [delete] Deleting directory /data/Middleware/user_projects/domains/portal_domain/assert/yufu/src
     [echo] Clean finish

build.mdf:
      Working directory ignored when same JVM is used.
      Parsing the MBean definition file: YufuSSOIdentityAsserter.xml
     [echo] Created Supporting Classes

build.mjf:
     [copy] Copying 3 files to /data/Middleware/user_projects/domains/portal_domain/assert/yufu/src
      Working directory ignored when same JVM is used.
      Creating an MJF from the contents of directory src...
      Compiling the files...
      Creating the list.
      Doing the compile.
    .....
build:

all:

BUILD SUCCESSFUL
Total time: 5 seconds

构建胜利后会在本地生成一个 jar 文件,将该文件拷本到以下目录

cp YufuSSOIdentityAsserter.jar $MIDDLEWARE_HOME/wlserver_10.3/server/lib/mbeantypes/

weblogic 自身自带了 ant 工具,门路位于 $MIDDLEWARE_HOME/modules/org.apache.ant_1.7.1 目录下,你能够在用户的.bash_profile 外面退出以下配置

ANT_HOME=/data/Middleware/modules/org.apache.ant_1.7.1

PATH=$ANT_HOME/bin:$PATH

这样就能够间接应用 ant 命令

  • 重启所有服务器(AdminServer 和 ManagerServer)

配置 Provider

登录 console,进入 myrealm >Providers 就能够看到自开发的 Asserter

点击 Save 保留,点击激活更改利用所有更改

  • 碰到的问题

在激活的时候可能会碰到一下谬误

后盾报错如下:

<May 10, 2021 4:54:50 PM CST> <Error> <Console> <BEA-240003> <Console encountered the following error weblogic.management.provider.UpdateException: [Management:141191]The prepare phase of the configuration update failed with an exception:
 at weblogic.management.provider.internal.RuntimeAccessDeploymentReceiverService.updateDeploymentContext

 ...

Caused by: java.io.IOException: [Management:141245]Schema Validation Error in config/config.xml see log for details. Schema validation can be disabled by starting the server with the command line option: -Dweblogic.configuration.schemaValidationEnabled=false
 at weblogic.management.provider.internal.EditAccessImpl.checkErrors(EditAccessImpl.java:2340)
 at weblogic.management.provider.internal.RuntimeAccessDeploymentReceiverService.handleConfigTreeLoad(RuntimeAccessDeploymentReceiverService.java:968)
 at weblogic.management.provider.internal.RuntimeAccessDeploymentReceiverService.updateDeploymentContext(RuntimeAccessDeploymentReceiverService.java:599)
>

这个谬误是配置完 provider 后,weblogic 会将信息写入 config/config.xml 文件中,而该文件在 Schema validation(模式验证)中验证不通过,这应该是 weblogic 的 bug 导致,解决办法是在 setDomainEnv.sh 中找到这段(大略在 530 行左右)

JAVA_OPTIONS="${JAVA_OPTIONS}"
export JAVA_OPTIONS

将其改为

JAVA_OPTIONS="${JAVA_OPTIONS} -Dweblogic.configuration.schemaValidationEnabled=false"
export JAVA_OPTIONS

而后重启所有的服务器

验证

  • 筹备一个 servlet,代码如下
public class SecurityServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {StringBuffer str = new StringBuffer();
        str.append("remoteUser:" + req.getRemoteUser() + "\r\n<br/>");
        String name = (req.getUserPrincipal() == null) ? null : req
                .getUserPrincipal().getName();
        str.append("Principal Name:" + name + "\r\n<br/>");
        str.append("Authentication Type:" + req.getAuthType() + "\n<br/>");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html; charset=UTF-8");
        resp.getOutputStream().write(str.toString().getBytes("utf-8"));
        resp.getOutputStream().flush();
    }
}
  • web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5" xmlns="http://java.sun.com/xml/ns/javaee">
    <servlet>
        <servlet-name>security</servlet-name>
        <servlet-class>com.demo.service.SecurityServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>security</servlet-name>
        <url-pattern>/security</url-pattern>
    </servlet-mapping>
   
    <security-constraint>
        <web-resource-collection>
            <web-resource-name>SecurePages</web-resource-name>
            <url-pattern>/*</url-pattern>
            <http-method>GET</http-method>
        </web-resource-collection>
        <auth-constraint>
            <role-name>ValidUser</role-name>
        </auth-constraint>
        <user-data-constraint>
            <transport-guarantee>NONE</transport-guarantee>
        </user-data-constraint>
    </security-constraint>
    <login-config>
        <auth-method>CLIENT-CERT</auth-method>
        <realm-name>myrealm</realm-name>
    </login-config>
    <security-role>
        <role-name>ValidUser</role-name>
    </security-role>
</web-app>
  • weblogi.xml
<?xml version='1.0' encoding='UTF-8'?>
<wls:weblogic-web-app
        xmlns:wls="http://xmlns.oracle.com/weblogic/weblogic-web-app"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
        http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd
        http://xmlns.oracle.com/weblogic/weblogic-web-app
        http://xmlns.oracle.com/weblogic/weblogic-web-app/1.4/weblogic-web-app.xsd">
    <wls:security-role-assignment>
        <wls:role-name>ValidUser</wls:role-name>
        <wls:principal-name>users</wls:principal-name>
    </wls:security-role-assignment>
    <wls:context-root>/definetool</wls:context-root>
</wls:weblogic-web-app>
  • 部署

将利用打包 war 部署 weblogic

  • 测试
➜  curl -v http://192.168.1.23:7001/definetool/security

*   Trying 192.168.1.23...
* TCP_NODELAY set
* Connected to 192.168.1.23 (192.168.1.23) port 7001 (#0)
> GET /definetool/security HTTP/1.1
> Host: 192.168.1.23:7001
> User-Agent: curl/7.54.0
> Accept: */*
> 
< HTTP/1.1 401 Unauthorized
< Date: Tue, 11 May 2021 11:57:20 GMT
< Content-Length: 1468
< Content-Type: text/html; charset=UTF-8
< 

加上 token(token 名称为 YUFU_REMOTE_USER)定义在配置文件里

➜ curl -v http://192.168.1.23:7001/definetool/security -H 'YUFU_REMOTE_USER:helen'

*   Trying 192.168.1.23...
* TCP_NODELAY set
* Connected to 192.168.1.23 (192.168.1.23) port 7001 (#0)
> GET /definetool/security HTTP/1.1
> Host: 192.168.1.23:7001
> User-Agent: curl/7.54.0
> Accept: */*
> YUFU_REMOTE_USER:helen
> 
< HTTP/1.1 200 OK
< Date: Tue, 11 May 2021 11:59:31 GMT
< Transfer-Encoding: chunked
< Content-Type: text/html; charset=UTF-8
< X-ORACLE-DMS-ECID: c813593f0a2fd3cb:70daab41:17959480e1c:-8000-0000000000000034
< Set-Cookie: JSESSIONID=JNNbS-fvPiFe2u2upP13qyykiOvQ8IlLLLxd7m2_GSWEhlwUQlrd!686904248; path=/; HttpOnly
< 
remoteUser:helen
<br/>Principal Name: helen
<br/>Authentication Type: CLIENT_CERT
* Connection #0 to host 192.168.1.23 left intact
<br/>%                                                      

验证通过

源码

所有代码都已提交至 gitlab 欢送 star

正文完
 0