首页 > 学院 > 开发设计 > 正文

Shiro自定义Ream

2019-11-06 08:00:24
字体:
来源:转载
供稿:网友
项目目录结构 这里写图片描述 2.代码:package com.sun.shiro;import org.apache.commons.lang3.StringUtils;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;import org.slf4j.Logger;import org.slf4j.LoggerFactory;/** * 自定义realm的实现 * @author suntan * @dade 2017年3月3日下午7:27:42 * @version v1.0 */public class MyRealmDemo1 implements Realm{ /** * 日志 */ PRivate Logger logger = LoggerFactory.getLogger(MyRealmDemo1.class); public String getName() { return "myReamDemo1"; } public boolean supports(AuthenticationToken token) { return token instanceof UsernamePasswordToken; } public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { //获取用户名和密码 String userName = (String) token.getPrincipal(); //String passWord = (String) token.getCredentials(); String passWord = new String((char[])token.getCredentials()); if(!StringUtils.equals(userName, "sunny")) { logger.info("=======>用户名错误"); throw new UnknownAccountException(); } if(!StringUtils.equals(passWord, "1127")) { logger.info("====>密码错误"); throw new IncorrectCredentialsException(); } //用户名密码都对 return new SimpleAuthenticationInfo(userName, passWord, getName()); }}

3.测试代码

package com.sun.shiro;import org.apache.shiro.SecurityUtils;import org.apache.shiro.authc.UsernamePasswordToken;import org.apache.shiro.config.IniSecurityManagerFactory;import org.apache.shiro.mgt.SecurityManager;import org.apache.shiro.subject.Subject;import org.apache.shiro.util.Factory;import org.junit.Test;import org.slf4j.Logger;import org.slf4j.LoggerFactory;public class MyRealmDemo1Test { /** * 日志 */ private Logger logger = LoggerFactory.getLogger(MyRealmDemo1Test.class); @Test public void testGetAuthenticationInfo() { //1.加载配置文件 Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro_realm.ini"); //2.实例化对象 SecurityManager securityManager = factory.getInstance(); //绑定 SecurityUtils.setSecurityManager(securityManager); //的到当前用户 Subject subject = SecurityUtils.getSubject(); //根据用户名密码登陆 UsernamePasswordToken token = new UsernamePasswordToken("sunny", "1127"); try { logger.info("=======>执行登陆"); subject.login(token); logger.info("=======>登陆成功"); } catch (Exception e) { logger.error("========>登陆失败:" + e); } //登出 subject.logout(); }}

执行结果: 这里写图片描述


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表