<dependencies> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.1.3</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-all</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> </dependencies> |
[users] test=test [main] userRealm=test.mylo.UserRealm securityManager.realms=$userRealm |
package test.mylo; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.config.IniSecurityManagerFactory; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.subject.Subject; public class TestShiro { public static void main(String[] args) { //加载配置文件IniSecurityManagerFactory ini = new IniSecurityManagerFactory("classpath:shiro.ini"); //获取securityManagers实例对象SecurityManager securityManager = ini.getInstance(); //获取 SecurityManager 并绑定到 SecurityUtilsSecurityUtils.setSecurityManager(securityManager); //获取当前主体对象Subject subject = SecurityUtils.getSubject(); //设置当前的TOKENUsernamePasswordToken token = new UsernamePasswordToken("test", "test"); try { System.out.println(1); subject.login(token); System.out.println("验证成功"); } catch (AuthenticationException e) { //验证失败e.printStackTrace(); System.out.println("验证失败"); } } } |
package test.mylo; import org.apache.shiro.authc.*; import org.apache.shiro.realm.Realm; public class UserRealm implements Realm{ @Override //返回一个唯一的Realm名字 public String getName() { return "userRealm"; } @Override //判断此Realm是否支持此Token public boolean supports(AuthenticationToken token) { return token instanceof UsernamePasswordToken; } //根据Token获取认证信息 @Override public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { String username = (String)token.getPrincipal(); String password = new String((char[])token.getCredentials()); if("test".equals(username)){ if("test".equals(password)){ return new SimpleAuthenticationInfo(username,password,getName()); }else { //用户密码错误throw new IncorrectCredentialsException(); } }else { //用户账号错误throw new UnknownAccountException(); } } } |
| 欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |