Java 后端面试题库 / 全部题解免费阅读理解原理,有条理地回答

一次登录、权限检查和退出怎样写?

先说出你的答案

定义边界、关键机制、一个反例;P8题再补容量、失败与验证。

查看完整题解

参考回答

直接回答

先取得或构建Subject,再提交认证Token;成功后仍按资源检查权限,结束时调用logout。下面用内存演示Realm说明完整顺序,生产环境的账户查询与密码来源需要另外接入。

讲清原理

示例使用Shiro3.0.2与Java21,PasswordService生成派生值,PasswordMatcher验证提交密码。授权仅允许读取文档42,不意味着相邻文档或写操作也获准。

登录信息怎样交给验证组件
登录信息怎样交给验证组件

例子与易错点

需在类路径中加入同版本shiro-core及其运行依赖。演示密码仅用于本地内存样本,生产密码不硬编码。

import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.*;
import org.apache.shiro.authz.*;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.*;
public class DemoLogin {
    static final class DemoRealm extends AuthorizingRealm {
        private final String encoded;
        DemoRealm(String encoded) {
            this.encoded = encoded;
            setCredentialsMatcher(new PasswordMatcher());
        }
        protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {
            if (!"alice".equals(token.getPrincipal())) throw new UnknownAccountException();
            return new SimpleAuthenticationInfo("alice", encoded, getName());
        }
        protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            info.addStringPermission("doc:read:42");
            return info;
        }
    }
    public static void main(String[] args) {
        String hash = new DefaultPasswordService().encryptPassword("demo-only-password");
        DefaultSecurityManager manager = new DefaultSecurityManager(new DemoRealm(hash));
        Subject subject = new Subject.Builder(manager).buildSubject();
        UsernamePasswordToken token = new UsernamePasswordToken("alice", "demo-only-password");
        try {
            subject.login(token);
            System.out.println(subject.isAuthenticated());
            System.out.println(subject.isPermitted("doc:read:42"));
            System.out.println(subject.isPermitted("doc:read:43"));
            subject.logout();
            System.out.println(subject.isAuthenticated());
        } finally {
            token.clear();
            manager.destroy();
        }
    }
}

输出依次为true、true、false、false,对应已认证、能读42、不能读43、退出后未认证。不要用只判断“登录成功”的测试替代权限拒绝测试。

相关题 第 20 题、第 22 题。

这道题,你掌握得怎么样?

掌握程度由你主动标记,阅读和收藏不会自动改变状态。