项目使用shiro进行权限管理,Shiro国内目前资料极少,学习时完全就是根据张开涛的《跟我学Shiro》自己去摸索的,慢慢的开始入门。Shiro中有一个概念是principals,解释如下:
principals:身份,即主体的标识属性,可以是任何东西,如用户名、邮箱等,唯一即可。
一个主体可以有多个principals,但只有一个Primary principals,一般是用户名/密码/手机号。
可以看出,principals在我们开发时是非常有用的,但是对principals的讲解真是少的可怜。最近在完善代码的时候又过了一遍Shiro,竟然有了一点点小收获,好记性不如烂笔头,写下来记录一下。
一开始一直在想,principals包含什么信息是在那里定义的,如何如设置呢?
在整理自定义realm我有了一个小小的发现。在realm中,doGetAuthenticationInfo为身份验证过程中调用的函数,realm相当于一个安全数据源,shiro其实就是在realm中获取用户数据的(个人理解),获取完以后,如果使用shiro默认的密码匹配的话,通常会返回一个SimpleAuthenticationInfo的对象,查看SimpleAuthenticationInfo的构造方法:
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.shiro.authc;
import org.apache.shiro.subject.MutablePrincipalCollection;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.util.ByteSource;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
/**
* Simple implementation of the {@link org.apache.shiro.authc.MergableAuthenticationInfo} interface that holds the principals and
* credentials.
*
* @see org.apache.shiro.realm.AuthenticatingRealm
* @since 0.9
*/
public class SimpleAuthenticationInfo implements MergableAuthenticationInfo, SaltedAuthenticationInfo {
/**
* The principals identifying the account associated with this AuthenticationInfo instance.
*/
protected PrincipalCollection principals;
/**
* The credentials verifying the account principals.
*/
protected Object credentials;
/**
* Any salt used in hashing the credentials.
*
* @since 1.1
*/
protected ByteSource credentialsSalt;
/**
* Default no-argument constructor.
*/
public SimpleAuthenticationInfo() {
}
/**