使用Apache Shiro进行身份认证-LDAP认证

Apache Shiro 支持LDAP做为数据源进行身份认证。我做了一个简单的实验来说明Shiro是如何支持LDAP的。

在本机安装了OpenLDAP,版本为2.4.23。手动建了一个用户,结构如下:

在Shiro.ini文件中配置LDAP:

[main]
ldapRealm = org.apache.shiro.realm.ldap.JndiLdapRealm
ldapRealm.userDnTemplate = cn={0},ou=产品研发部,ou=研发中心,dc=example,dc=com
ldapRealm.contextFactory.url = ldap://localhost:389

这样就可实现通过LDAP进行身份认证。


在Shiro中具体实现验证过程的是org.apache.shiro.realm.ldap.JndiLdapRealm类和org.apache.shiro.realm.ldap.JndiLdapContextFactory类。

protected AuthenticationInfo queryForAuthenticationInfo(AuthenticationToken token,
                                                            LdapContextFactory ldapContextFactory)
            throws NamingException {

        //从页面提交的用户名“lisi”
        Object principal = token.getPrincipal();
        //从页面提交的口令“123456”
        Object credentials = token.getCredentials();

        log.debug("Authenticating user '{}' through LDAP", principal);

        //将用户名拼成DN“cn=lisi,ou=产品研发部,ou=研发中心,dc=example,dc=com”
        principal = getLdapPrincipal(token);

        LdapContext ctx = null;
        try {
            //进行认证
            ctx = ldapContextFactory.getLdapContext(principal, credentials);
            //context was opened successfully, which means their credentials were valid.  Return the AuthenticationInfo:
            return createAuthenticationInfo(token, principal, credentials, ctx);
        } finally {
            LdapUtils.closeContext(ctx);
        }
    }

注,这里存在一个问题。如果输入不存在的用户或是错误的口令后currentUser.login(token);方法返回的异常是AuthenticationException,代表不确定的异常。

而不是UnknownAccountException或IncorrectCredentialsException。这样在前台表述时就不够准确。

原因应该是在做LDAP认证时没有区分错误情况,如果取不到context会抛出相同异常 throw new AuthenticationException("LDAP authentication failed.", e);


评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

peterwanghao

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值