这个demo是基于springboot项目的。
名词介绍:
Shiro
Shiro 主要分为 安全认证 和 接口授权 两个部分,其中的核心组件为 Subject、 SecurityManager、 Realms,公共部分 Shiro 都已经为我们封装好了,我们只需要按照一定的规则去编写响应的代码即可…
Subject 即表示主体,将用户的概念理解为当前操作的主体,因为它即可以是一个通过浏览器请求的用户,也可能是一个运行的程序,外部应用与 Subject 进行交互,记录当前操作用户。Subject 代表了当前用户的安全操作,SecurityManager 则管理所有用户的安全操作。
SecurityManager 即安全管理器,对所有的 Subject 进行安全管理,并通过它来提供安全管理的各种服务(认证、授权等)
Realm 充当了应用与数据安全间的 桥梁 或 连接器。当对用户执行认证(登录)和授权(访问控制)验证时,Shiro 会从应用配置的 Realm 中查找用户及其权限信息。
1.导入shiro依赖
- <dependency>
- <groupId>org.apache.shiro</groupId>
- <artifactId>shiro-spring</artifactId>
- <version>1.4.0</version>
- </dependency>
-
- <dependency>
- <groupId>org.crazycake</groupId>
- <artifactId>shiro-redis</artifactId>
- <version>2.8.24</version>
- </dependency>
- shiro-redis为什么要导入这个包呢?将用户信息交给redis管理。
2.shiro配置类
3.安全认证和权限验证的核心,自定义Realm
- package com.test.cbd.shiro;
- import com.google.gson.JsonObject;
- import com.test.cbd.service.UserService;
- import com.test.cbd.vo.SysPermission;
- import com.test.cbd.vo.SysRole;
- import com.test.cbd.vo.UserInfo;
- import org.apache.commons.beanutils.BeanUtils;
- import org.apache.shiro.SecurityUtils;
- import org.apache.shiro.authc.*;
- import org.apache.shiro.authz.AuthorizationInfo;
- import org.apache.shiro.authz.SimpleAuthorizationInfo;
- import org.apache.shiro.realm.AuthorizingRealm;
- import org.apache.shiro.session.Session;
- import org.apache.shiro.subject.PrincipalCollection;
- import org.apache.shiro.subject.Subject;
- import org.apache.shiro.util.ByteSource;
- import springfox.documentation.spring.web.json.Json;
- import javax.annotation.Resource;
- import java.util.HashSet;
- import java.util.Set;
-
- public class MyShiroRealm extends AuthorizingRealm {
- @Resource
- private UserService userInfoService;
- @Override
- protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals){
- // // 权限信息对象info,用来存放查出的用户的所有的角色(role)及权限(permission)
- SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
- Session session = SecurityUtils.getSubject().getSession();
- UserInfo user = (UserInfo) session.getAttribute("USER_SESSION");
- // 用户的角色集合
- Set<String> roles = new HashSet<>();
- roles.add(user.getRoleList().get(0).getRole());
- authorizationInfo.setRoles(roles);
- return authorizationInfo;
- }
- /*主要是用来进行身份认证的,也就是说验证用户输入的账号和密码是否正确。*/
- @Override
- protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
- throws AuthenticationException {
- // System.out.println("MyShiroRealm.doGetAuthenticationInfo()");
- //获取用户的输入的账号.
- String username = (String) token.getPrincipal();
- // System.out.println(token.getCredentials());
- //通过username从数据库中查找 User对象,如果找到,没找到.
- //实际项目中,这里可以根据实际情况做缓存,如果不做,Shiro自己也是有时间间隔机制,2分钟内不会重复执行该方法
- UserInfo userInfo = userInfoService.findByUsername(username);
- // Subject subject = SecurityUtils.getSubject();
- //Session session = subject.getSession();
- //session.setAttribute("role",userInfo.getRoleList());
- // System.out.println("----->>userInfo="+userInfo);
- if (userInfo == null) {
- return null;
- }
- if (userInfo.getState() == 1) { //账户冻结
- throw new LockedAccountException();
- }
- String credentials = userInfo.getPassword();
- System.out.println("credentials="+credentials);
- ByteSource credentialsSalt = ByteSource.Util.bytes(username);
- SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
- userInfo.getUserName(), //用户名
- credentials, //密码
- credentialsSalt,
- getName() //realm name
- );
- Session session = SecurityUtils.getSubject().getSession();
- session.setAttribute("USER_SESSION", userInfo);
- return authenticationInfo;
- }
- }
4.全局异常处理器
- package com.test.cbd.shiro;
- import com.alibaba.fastjson.support.spring.FastJsonJsonView;
- import org.apache.shiro.authz.UnauthenticatedException;
- import org.apache.shiro.authz.UnauthorizedException;
- import org.springframework.web.servlet.HandlerExceptionResolver;
- import org.springframework.web.servlet.ModelAndView;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import java.util.HashMap;
- import java.util.Map;
- /**
- * Created by Administrator on 2017/12/11.
- * 全局异常处理
- */
- public class MyExceptionHandler implements HandlerExceptionResolver {
- public ModelAndView resolveException(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse, Object o, Exception ex) { - ModelAndView mv = new ModelAndView();
- FastJsonJsonView view = new FastJsonJsonView();
- Map<String, Object> attributes = new HashMap<String, Object>();
- if (ex instanceof UnauthenticatedException) {
- attributes.put("code", "1000001");
- attributes.put("msg", "token错误");
- } else if (ex instanceof UnauthorizedException) {
- attributes.put("code", "1000002");
- attributes.put("msg", "用户无权限");
- } else {
- attributes.put("code", "1000003");
- attributes.put("msg", ex.getMessage());
- }
- view.setAttributesMap(attributes);
- mv.setView(view);
- return mv;
- }
- }
5.因为现在的项目大多都是前后端分离的,所以我们需要实现自己的session管理
- package com.test.cbd.shiro;
- import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
- import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
- import org.apache.shiro.web.util.WebUtils;
- import org.springframework.util.StringUtils;
- import javax.servlet.ServletRequest;
- import javax.servlet.ServletResponse;
- import java.io.Serializable;
-
- public class MySessionManager extends DefaultWebSessionManager {
- private static final String TOKEN = "token";
- private static final String REFERENCED_SESSION_ID_SOURCE = "Stateless request";
- public MySessionManager() {
- super();
- }
- @Override
- protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
- String id = WebUtils.toHttp(request).getHeader(TOKEN);
- //如果请求头中有 token 则其值为sessionId
- if (!StringUtils.isEmpty(id)) {
- request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, REFERENCED_SESSION_ID_SOURCE);
- request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, id);
- request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
- return id;
- } else {
- //否则按默认规则从cookie取sessionId
- return super.getSessionId(request, response);
- }
- }
- }
6.控制器
- package com.test.cbd.shiro;
- import com.alibaba.fastjson.JSONObject;
- import com.test.cbd.vo.UserInfo;
- import io.swagger.annotations.Api;
- import lombok.extern.slf4j.Slf4j;
- 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.UsernamePasswordToken;
- import org.apache.shiro.authz.annotation.RequiresRoles;
- import org.apache.shiro.crypto.hash.SimpleHash;
- import org.apache.shiro.session.Session;
- import org.apache.shiro.subject.Subject;
- import org.apache.shiro.util.ByteSource;
- import org.springframework.web.bind.annotation.*;
- import javax.servlet.http.HttpServletRequest;
- import java.net.InetAddress;
- @Slf4j
- @Api(value="shiro测试",description="shiro测试")
- @RestController
- @RequestMapping("/")
- public class ShiroLoginController {
- /**
- * 登录测试
- * @param userInfo
- * @return
- */
- @RequestMapping(value = "/ajaxLogin", method = RequestMethod.POST)
- @ResponseBody
- public String ajaxLogin(UserInfo userInfo) {
- JSONObject jsonObject = new JSONObject();
- UsernamePasswordToken token = new UsernamePasswordToken(userInfo.getUserName(), userInfo.getPassword());
- Subject subject = SecurityUtils.getSubject();
- try {
- subject.login(token);
- jsonObject.put("token", subject.getSession().getId());
- jsonObject.put("msg", "登录成功");
- } catch (IncorrectCredentialsException e) {
- jsonObject.put("msg", "密码错误");
- } catch (LockedAccountException e) {
- jsonObject.put("msg", "登录失败,该用户已被冻结");
- } catch (AuthenticationException e) {
- jsonObject.put("msg", "该用户不存在");
- } catch (Exception e) {
- e.printStackTrace();
- }
- return jsonObject.toString();
- }
- /**
- * 鉴权测试
- * @param userInfo
- * @return
- */
- @RequestMapping(value = "/check", method = RequestMethod.GET)
- @ResponseBody
- @RequiresRoles("guest")
- public String check() {
- JSONObject jsonObject = new JSONObject();
- jsonObject.put("msg", "鉴权测试");
- return jsonObject.toString();
- }
- }
常用注解
@RequiresGuest 代表无需认证即可访问,同理的就是 /path=anon
@RequiresAuthentication 需要认证,只要登录成功后就允许你操作
@RequiresPermissions 需要特定的权限,没有则抛出 AuthorizationException
@RequiresRoles 需要特定的橘色,没有则抛出 AuthorizationException
7.以上就是shiro登陆和鉴权的主要配置和类,下面补充一下其他信息。
①application.properties中shiro-redis相关配置:
- spring.redis.shiro.host=127.0.0.1
- spring.redis.shiro.port=6379
- spring.redis.shiro.timeout=5000
- spring.redis.shiro.password=123456
②因为数据是模拟的,所以在登陆认证的时候,并没有通过数据库查用户信息,可以通过以下方式模拟加密后的密码:
- /**
- * 生成测试用的md5加密的密码
- * @param args
- */
- public static void main(String[] args) {
- String hashAlgorithmName = "md5";
- String credentials = "123456";//密码
- int hashIterations = 1024;
- ByteSource credentialsSalt = ByteSource.Util.bytes("root");//账号
- String obj = new SimpleHash(hashAlgorithmName, credentials, credentialsSalt, hashIterations).toHex();
- System.out.println(obj);
- }
上面obj的结果是b1ba853525d0f30afe59d2d005aad96c
③登陆认证的findByUsername方法,模拟到数据库查询用户信息,实际是自己构造的数据,偷偷懒。
- public UserInfo findByUsername(String userName){
- SysRole admin = SysRole.builder().role("admin").build();
- List<SysPermission> list=new ArrayList<SysPermission>();
- SysPermission sysPermission=new SysPermission("read");
- SysPermission sysPermission1=new SysPermission("write");
- list.add(sysPermission);
- list.add(sysPermission1);
- admin.setPermissions(list);
- UserInfo root = UserInfo.builder().userName("root").password("b1ba853525d0f30afe59d2d005aad96c").credentialsSalt("123").state(0).build();
- List<SysRole> roleList=new ArrayList<SysRole>();
- roleList.add(admin);
- root.setRoleList(roleList);
- return root;
- }
8.结果演示
输入正确的账号密码时,返回信息如下:

故意输错密码时,返回信息如下:

鉴权时,如果该用户没有角色:

完!