Shiro 十分钟教程
package com.wjz.demo; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.IncorrectCredentialsException; import org.apache.shiro.authc.LockedAccountException; import org.apache.shiro.authc.UnknownAccountException; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.session.Session; import org.apache.shiro.subject.Subject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Quickstart { private static final Logger log = LoggerFactory.getLogger(Quickstart.class); public static void main(String[] args) { // 获得用户信息 Subject currentUser = SecurityUtils.getSubject(); // 获得会话信息 Session session = currentUser.getSession(); session.setAttribute("url", "www.baidu.com"); // 判断用户是否已经登录 if (currentUser.isAuthenticated()) { UsernamePasswordToken token = new UsernamePasswordToken("username", "password"); token.setRememberMe(true); // 当前用户拿着Token去登录系统 try { currentUser.login(token); } catch (UnknownAccountException e) { // TODO 用户不存在 } catch (IncorrectCredentialsException e) { // TODO 用户名或密码不正确 // For example, this exception might be thrown //if a user's password is "secret" and "secrets" was entered by mistake } catch (LockedAccountException e) { // TODO 用户被锁定不能登录 } catch (AuthenticationException e) { // TODO 认证过程中意想不到的异常 } } // Principal -用户的基本信息 log.info("User ["+ currentUser.getPrincipal() +"] logged in successfully."); // 判断会员是否有某个权限 -角色级权限控制 if (currentUser.hasRole("finance")) { // ignore } // 判断用户是否有权限请求特定的路径 -用户级权限控制 if (currentUser.isPermitted("finance:selectById")) { // ignore } // 注销登录 currentUser.logout(); // TODO 至于谁负责在登录时获得用户数据(用户名和密码、角色和权限),以及谁在运行时真正执行安全检,Shiro 配置使用Realm来完成这些工作 } }