,好记性不如烂笔头


身份验证,即在应用中谁能证明他就是他本人,应用系统中一般通过用户名/密码来证明。

在 shiro 中,用户需要提供principals(身份)和credentials(证明)给shiro,从而应用能验证用户身份:
    principals:身份,即主体的标识属性,可以是任何东西,如用户名、邮箱等,唯一即可。一个主体可以有多个principals,但只有一个Primary principals,一般是用户名/密码/手机号。
    credentials:证明/凭证,即只有主体知道的安全值,如密码/数字证书等。
最常见的principals和credentials组合就是用户名/密码了。   

Authenticator:认证器,负责主体认证的,这是一个扩展点,如果用户觉得Shiro 默认的不好,可以自定义实现;其需要认证策略(Authentication Strategy),即什么情况下算用户认证通过了;

package org.apache.shiro.authc;public interface Authenticator {    /**     * Authenticates a user based on the submitted {@code AuthenticationToken}.      */    public AuthenticationInfo authenticate(AuthenticationToken authenticationToken)            throws AuthenticationException;}

Realm:可以有1个或多个Realm,可以认为是安全实体数据源,即用于获取安全实体的;可以是JDBC 实现,也可以是LDAP 实现,或者内存实现等等;由用户提供;

package org.apache.shiro.realm;import org.apache.shiro.authc.AuthenticationException;import org.apache.shiro.authc.AuthenticationInfo;import org.apache.shiro.authc.AuthenticationToken;/** * A Realm is a security component that can access application-specific security entities * such as users, roles, and permissions to determine authentication and authorization operations. * * @see org.apache.shiro.realm.CachingRealm CachingRealm * @see org.apache.shiro.realm.AuthenticatingRealm AuthenticatingRealm * @see org.apache.shiro.realm.AuthorizingRealm AuthorizingRealm * @see org.apache.shiro.authc.pam.ModularRealmAuthenticator ModularRealmAuthenticator * @since 0.1 */public interface Realm {    /**     * Returns the (application-unique) name assigned to this Realm.      * All realms configured for a single application must have a unique name.     * 返回一个唯一的Realm名字     * @return the (application-unique) name assigned to this Realm.     */    String getName();    /**     * Returns true if this realm wishes to authenticate the Subject represented by the given     * {@link org.apache.shiro.authc.AuthenticationToken AuthenticationToken} instance, false otherwise.     * 判断此Realm是否支持此Token     */    boolean supports(AuthenticationToken token);    /**     * Returns an account's authentication-specific information for the specified token,     * or null if no account could be found based on the token.     * 根据Token获取认证信息     */    AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException;}

注意:Shiro不知道你的用户/权限存储在哪及以何种格式存储;所以我们一般在应用中都需要实现自己的Realm;

单Realm配置

1、自定义Realm实现

package com.invicme.apps.shiro.realm.single;import org.apache.shiro.authc.AuthenticationException;import org.apache.shiro.authc.AuthenticationInfo;import org.apache.shiro.authc.AuthenticationToken;import org.apache.shiro.authc.IncorrectCredentialsException;import org.apache.shiro.authc.SimpleAuthenticationInfo;import org.apache.shiro.authc.UnknownAccountException;import org.apache.shiro.authc.UsernamePasswordToken;import org.apache.shiro.realm.Realm;/** *  * @author lucl *  */public class MyRealmOne implements Realm {    @Override    public String getName() {        return this.getClass().getName();    }    @Override    public boolean supports(AuthenticationToken token) {        // 仅支持UsernamePasswordToken 类型的Token        return token instanceof UsernamePasswordToken;    }    @Override    public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token)            throws AuthenticationException {        String principal = String.valueOf(token.getPrincipal());            // 得到身份(用户名)        String credentials = new String((char[])token.getCredentials());    // 得到认证/凭证(密码)                if(!"lucl".equals(principal)) {            throw new UnknownAccountException("用户名/密码错误"); // 如果用户名错误        }        if(!"123".equals(credentials)) {            throw new IncorrectCredentialsException("用户凭证错误"); // 如果密码错误        }        // 如果身份认证验证成功,返回一个AuthenticationInfo实现;        return new SimpleAuthenticationInfo(String.valueOf(principal), String.valueOf(credentials), this.getName());    }    }

2、ini配置文件指定自定义Realm实现

[main]# 声明自定义的RealmmyRealm=com.invicme.apps.shiro.realm.single.MyRealmOne# 指定securityManager的realms实现securityManager.realms=$myRealm# 变量名=全限定类名会自动创建一个类实例# 变量名.属性=值自动调用相应的setter方法进行赋值# $变量名引用之前的一个对象实例

3、测试用例

@Testpublic void testAuthenticatorSingleRealm () {    // 1、获取SecurityManager工厂,此处使用Ini配置文件初始化SecurityManager    Factory
 factory = new IniSecurityManagerFactory("classpath:shiro/shiro-authenticator-single-realm.ini");        // 2、得到SecurityManager实例并绑定给SecurityUtils    org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance();    SecurityUtils.setSecurityManager(securityManager);        // 3、得到Subject及创建用户名/密码身份验证Token(即用户身份/凭证)    Subject subject = SecurityUtils.getSubject();    UsernamePasswordToken token = new UsernamePasswordToken("lucl", "123");        try{        // 4、登录,即身份验证        subject.login(token);    } catch (AuthenticationException e) {        // 5、身份验证失败        logger.info("用户身份验证失败");        e.printStackTrace();    }        if (subject.isAuthenticated()) {        logger.info("用户登录成功。");    } else {        logger.info("用户登录失败。");    }    // 6、退出    subject.logout();}

多Realm配置

在用户身份验证的时候,可能会使用登录ID、手机号或者邮箱作为登录身份。

1、自定义Realm实现

com.invicme.apps.shiro.realm.multi.MyRealmOne

package com.invicme.apps.shiro.realm.multi;import org.apache.shiro.authc.AuthenticationException;import org.apache.shiro.authc.AuthenticationInfo;import org.apache.shiro.authc.AuthenticationToken;import org.apache.shiro.authc.IncorrectCredentialsException;import org.apache.shiro.authc.SimpleAuthenticationInfo;import org.apache.shiro.authc.UnknownAccountException;import org.apache.shiro.authc.UsernamePasswordToken;import org.apache.shiro.realm.Realm;/** *  * @author lucl *  */public class MyRealmOne implements Realm {    @Override    public String getName() {        return this.getClass().getName();    }    @Override    public boolean supports(AuthenticationToken token) {        // 仅支持UsernamePasswordToken 类型的Token        return token instanceof UsernamePasswordToken;    }    @Override    public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token)            throws AuthenticationException {        String principal = String.valueOf(token.getPrincipal());            // 得到身份(用户名)        String credentials = new String((char[])token.getCredentials());    // 得到认证/凭证(密码)        System.out.println("【principal : " + principal + ", credentials : " + credentials + "】");        if(!"lucl".equals(principal)) {            System.out.println(" principal : " + principal + " not match 'lucl'.");            throw new UnknownAccountException("用户名/密码错误"); // 如果用户名错误        }        if(!"123".equals(credentials)) {            System.out.println(" credentials : " + credentials + " not match '123'.");            throw new IncorrectCredentialsException("用户凭证错误"); // 如果密码错误        }        //如果身份认证验证成功,返回一个AuthenticationInfo实现;        return new SimpleAuthenticationInfo(String.valueOf(principal), String.valueOf(credentials), this.getName());    }    }

com.invicme.apps.shiro.realm.multi.MyRealmTwo

package com.invicme.apps.shiro.realm.multi;import org.apache.shiro.authc.AuthenticationException;import org.apache.shiro.authc.AuthenticationInfo;import org.apache.shiro.authc.AuthenticationToken;import org.apache.shiro.authc.IncorrectCredentialsException;import org.apache.shiro.authc.SimpleAuthenticationInfo;import org.apache.shiro.authc.UnknownAccountException;import org.apache.shiro.authc.UsernamePasswordToken;import org.apache.shiro.realm.Realm;/** *  * @author lucl *  */public class MyRealmTwo implements Realm {    @Override    public String getName() {        return this.getClass().getName();    }    @Override    public boolean supports(AuthenticationToken token) {        // 仅支持UsernamePasswordToken 类型的Token        return token instanceof UsernamePasswordToken;    }    @Override    public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token)            throws AuthenticationException {        String principal = String.valueOf(token.getPrincipal());            // 得到身份(用户名)        String credentials = new String((char[])token.getCredentials());    // 得到认证/凭证(密码)        System.out.println("【principal : " + principal + ", credentials : " + credentials + "】");        if(!"imlucl@163.com".equals(principal)) {            System.out.println(" principal : " + principal + " not match 'imlucl@163.com'.");            throw new UnknownAccountException("用户名/密码错误");     // 如果用户名错误        }        if(!"123".equals(credentials)) {            System.out.println(" credentials : " + credentials + " not match '123'.");            throw new IncorrectCredentialsException("用户凭证错误"); // 如果密码错误        }        // 如果身份认证验证成功,返回一个AuthenticationInfo实现;        return new SimpleAuthenticationInfo(String.valueOf(principal), String.valueOf(credentials), this.getName());    }    }

2、ini配置文件指定自定义Realm实现

[main]# 声明自定义的RealmmyRealmA=com.invicme.apps.shiro.realm.multi.MyRealmOnemyRealmB=com.invicme.apps.shiro.realm.multi.MyRealmTwo# 指定securityManager的realms实现securityManager.realms=$myRealmA,$myRealmB# securityManager会按照realms指定的顺序进行身份认证;# 如果删除“securityManager.realms=$myRealmA,$myRealmB”,securityManager会按照realm声明的顺序进行使用;# 当我们显示指定realm 后, 其他没有指定的realm 将被忽略,如“securityManager.realms=$myRealmA”,那么myRealmB 不会被自动设置进去。

3、测试用例

@Testpublic void testAuthenticatorMultiRealm () {    // 1、获取SecurityManager工厂,此处使用Ini配置文件初始化SecurityManager    Factory
 factory = new IniSecurityManagerFactory("classpath:shiro/shiro-authenticator-multi-realm.ini");        // 2、得到SecurityManager实例并绑定给SecurityUtils    org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance();    SecurityUtils.setSecurityManager(securityManager);        // 3、得到Subject及创建用户名/密码身份验证Token(即用户身份/凭证)    Subject subject = SecurityUtils.getSubject();    /*      * 用户身份Token 可能不仅仅是用户名/密码,也可能还有其他的,如登录时允许用户名/邮箱/手机号同时登录。     */    UsernamePasswordToken token = new UsernamePasswordToken("imlucl@163.com", "123");        try{        // 4、登录,即身份验证        subject.login(token);    } catch (AuthenticationException e) {        // 5、身份验证失败        logger.info("用户身份验证失败");        e.printStackTrace();    }        if (subject.isAuthenticated()) {        logger.info("用户登录成功。");    } else {        logger.info("用户登录失败。");    }    // 6、退出    subject.logout();}