xzxt-shiro刑专系统权限服务数据封装

parent 94484cd5
package com.xzxtshiro.controller;
import javax.servlet.http.HttpSession;
import com.xzxtshiro.service.imp.ShiroService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
@RequestMapping("/shiro")
public class ShiroHandler {
/* @Autowired
private ShiroService shiroService;
@RequestMapping("/testShiroAnnotation")
public String testShiroAnnotation(HttpSession session){
session.setAttribute("key", "value12345");
shiroService.testMethod();
return "redirect:/list.jsp";
}*/
@RequestMapping("/login")
public String login(@RequestParam("username") String username,
@RequestParam("password") String password){
Subject currentUser = SecurityUtils.getSubject();
if (!currentUser.isAuthenticated()) {
// 把用户名和密码封装为 UsernamePasswordToken 对象
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
// rememberme
token.setRememberMe(true);
try {
System.out.println("登陆token" + token.hashCode());
// 执行登录.
currentUser.login(token);
}
// ... catch more exceptions here (maybe custom ones specific to your application?
// 所有认证时异常的父类.
catch (AuthenticationException ae) {
//unexpected condition? error?
System.out.println("登录失败: " + ae.getMessage());
return "login";
}
}
//return "redirect:/list.jsp";
//return "";
return "redirect:/admin/pagejump/index";
}
}
package com.xzxtshiro.service.imp;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.session.Session;
import java.util.Date;
public class ShiroService {
@RequiresRoles({"admin"})
public void testMethod(){
System.out.println("testMethod, time: " + new Date());
Session session = SecurityUtils.getSubject().getSession();
Object val = session.getAttribute("key");
String JSESSIONID=(String) session.getId();
System.out.println("Service SessionVal: " + val);
System.out.println("Service JSESSIONID: " + JSESSIONID);
}
}
\ No newline at end of file
package com.xzxtshiro.shiro.realm;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.xzxtshiro.pojo.SysPermissionNew;
import com.xzxtshiro.pojo.SysRole;
import com.xzxtshiro.pojo.SysUser;
import com.xzxtshiro.service.SysUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
public class ShiroRealm extends AuthorizingRealm {
private static final Logger logger = LoggerFactory.getLogger(ShiroRealm.class);
@Autowired
private SysUserService userService;
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(
AuthenticationToken token) throws AuthenticationException {
System.out.println("[FirstRealm] doGetAuthenticationInfo");
//1. 把 AuthenticationToken 转换为 UsernamePasswordToken
UsernamePasswordToken upToken = (UsernamePasswordToken) token;
//2. 从 UsernamePasswordToken 中来获取 username
String username = upToken.getUsername();
String password = new String((char[]) upToken.getCredentials());
SysUser user = userService.login(username, password);
System.out.println("user***********************************"+user);
if (user != null) {
// 第 1 个参数可以传一个实体对象,然后在认证的环节可以取出
// 第 2 个参数应该传递在数据库中“正确”的数据,然后和 token 中的数据进行匹配
// SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), getName());
// 设置盐值
// info.setCredentialsSalt(ByteSource.Util.bytes(username.getBytes()));
System.out.println("password+++++++++++++++++++++++++++++==" + user.getPassword());
String realmName = getName();
//4). 盐值.
ByteSource credentialsSalt = ByteSource.Util.bytes(username);
SimpleAuthenticationInfo info = null; //new SimpleAuthenticationInfo(principal, credentials, realmName);
info = new SimpleAuthenticationInfo(user, user.getPassword(), credentialsSalt, realmName);
return info;
}
return null;
}
//授权
//授权会被 shiro 回调的方法
@Override
protected AuthorizationInfo doGetAuthorizationInfo(
PrincipalCollection principals) {
logger.info("--- MyRealm doGetAuthorizationInfo ---");
System.out.println("--- MyRealm doGetAuthorizationInfo ---");
// 获得经过认证的主体信息
SysUser user = (SysUser) principals.getPrimaryPrincipal();
String userId = user.getId();
List<SysPermissionNew> permissions = userService.selectSysPermissionNewByUserId(userId);
List<SysRole> sysRoles = userService.selectSysRoleByUserId(userId);
List<String> roleSns = new ArrayList<String>();
for (SysRole role:sysRoles){
roleSns.add(role.getRolename());
}
List<String> resStrList = new ArrayList<>();
for (SysPermissionNew permission : permissions) {
if (permission != null) {
if(permission.getUrl()!=null){
resStrList.add(permission.getUrl());
}
}
}
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.setRoles(new HashSet<>(roleSns));
info.setStringPermissions(new HashSet<>(resStrList));
// 以上完成了动态地对用户授权
logger.debug("role => " + roleSns);
logger.debug("permission => " + resStrList);
logger.info("role => " + roleSns);
logger.info("permission => " + resStrList);
return info;
}
}
\ No newline at end of file
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h4>List Page</h4>
Welcome: <shiro:principal></shiro:principal>
<shiro:hasRole name="admin">
<br><br>
<a href="admin.jsp">Admin Page</a>
</shiro:hasRole>
<shiro:hasRole name="user">
<br><br>
<a href="user.jsp">User Page</a>
</shiro:hasRole>
<br><br>
<a href="shiro/testShiroAnnotation">Test ShiroAnnotation</a>
<br><br>
<a href="shiro/logout">Logout</a>
</body>
</html>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment