| | |
| | | package com.whyc.config; |
| | | |
| | | import com.whyc.filter.KickedOutFilter; |
| | | import com.whyc.filter.RolesOrAuthorizationFilter; |
| | | import com.whyc.properties.PropertiesUtil; |
| | | import com.whyc.realm.CustomRealm; |
| | |
| | | shiroFilter.setSecurityManager(defaultWebSecurityManager()); |
| | | shiroFilter.setFilterChainDefinitionMap(filterChainDefinition()); |
| | | shiroFilter.setLoginUrl("/login.html"); |
| | | //shiroFilter.setLoginUrl("/index.html#login"); |
| | | shiroFilter.setUnauthorizedUrl("/login/unauthorized"); |
| | | return shiroFilter; |
| | | } |
| | |
| | | |
| | | //这个是可行的,解析的时候path为*.html,校验路径admin下是否存在 |
| | | //registry.addResourceHandler("admin/*.html").addResourceLocations("classpath:/META-INF/resources/admin/"); |
| | | registry.addResourceHandler("/login.html").addResourceLocations("classpath:/META-INF/resources/"); |
| | | registry.addResourceHandler("/map/*").addResourceLocations("classpath:/META-INF/resources/map/"); |
| | | |
| | | //registry.addResourceHandler("/login.html").addResourceLocations("classpath:/META-INF/resources/"); |
| | | registry.addResourceHandler("*.html").addResourceLocations("classpath:/META-INF/resources/"); |
| | | registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); |
| | | registry.addResourceHandler("/service-worker.js").addResourceLocations("classpath:/META-INF/resources/"); |
| | | //registry.addResourceHandler("/favicon.ico").addResourceLocations("classpath:/META-INF/resources/"); |
| | | super.addResourceHandlers(registry); |
| | | //registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/"); |
| | | //registry.addResourceHandler("*.html").addResourceLocations("classpath:/META-INF/resources/"); |
| | |
| | | |
| | | @PostMapping("login") |
| | | @ApiOperation(value ="登录") |
| | | public Response login(@RequestParam String userName, String password){ |
| | | return service.login(userName,password); |
| | | public Response login(@RequestParam String userName, String password,HttpServletRequest request){ |
| | | return service.login(userName,password,request); |
| | | } |
| | | |
| | | @PostMapping("logout") |
| | |
| | | import io.swagger.annotations.ApiOperation; |
| | | import lombok.extern.slf4j.Slf4j; |
| | | import org.springframework.beans.factory.annotation.Autowired; |
| | | import org.springframework.cache.annotation.CacheEvict; |
| | | import org.springframework.web.bind.annotation.*; |
| | | |
| | | import javax.servlet.http.HttpServletRequest; |
| | |
| | | |
| | | @PostMapping("bindingUserWithRole") |
| | | @ApiOperation(value = "绑定用户和角色") |
| | | @CacheEvict(cacheNames = {"userBridge"},key="'getAuthorizationInfo'+#p0") //清除 |
| | | public boolean bindingUserWithRole(@RequestParam int userId,int roleId){ |
| | | return userRoleService.bindingUserWithRole(userId,roleId); |
| | | } |
| | | |
| | | @PostMapping("bindingUserWithRoleBatch") |
| | | @ApiOperation(value = "批量绑定用户和角色",notes = "传入userId和roleId的数组") |
| | | @CacheEvict(cacheNames = {"userBridge"},allEntries = true) //全部清除 |
| | | public boolean bindingUserWithRoleBatch(@RequestBody List<UserRole> userRoles){ |
| | | return userRoleService.bindingUserWithRoleBatch(userRoles); |
| | | } |
| | | |
| | | /**===============角色与权限================**/ |
| | | |
| | | @PostMapping("bindingRoleWithPrivilege") |
| | | @PostMapping("bindingRoleWithPermission") |
| | | @ApiOperation(value = "绑定角色-权限") |
| | | public boolean bindingRoleWithPrivilege(@RequestParam int roleId,int privilegeId){ |
| | | return rolePermissionService.bindingUserWithRole(roleId,privilegeId); |
| | | @CacheEvict(cacheNames = {"userBridge"},allEntries = true) //全部清除 |
| | | public boolean bindingRoleWithPermission(@RequestParam int roleId,int permissionId){ |
| | | return rolePermissionService.bindingUserWithRole(roleId,permissionId); |
| | | } |
| | | |
| | | @PostMapping("bindingRoleWithPrivilegeBatch") |
| | | @PostMapping("bindingRoleWithPermissionBatch") |
| | | @ApiOperation(value = "批量绑定角色-权限",notes = "传入roleId和privilegeId的数组") |
| | | public boolean bindingRoleWithPrivilegeBatch(@RequestBody List<RolePermission> rolePermissions){ |
| | | @CacheEvict(cacheNames = {"userBridge"},allEntries = true) //全部清除 |
| | | public boolean bindingRoleWithPermissionBatch(@RequestBody List<RolePermission> rolePermissions){ |
| | | return rolePermissionService.bindingUserWithRoleBatch(rolePermissions); |
| | | } |
| | | |
| | | @GetMapping("privilege") |
| | | @GetMapping("permissions") |
| | | @ApiOperation(value = "获取当前用户的权限") |
| | | public List<Permission> getPrivileges(HttpServletRequest request){ |
| | | public List<Permission> getPermissions(HttpServletRequest request){ |
| | | User user = CommonUtil.getUser(request); |
| | | return rolePermissionService.getPrivileges(user.getId()); |
| | | return rolePermissionService.getPermissions(user.getId()); |
| | | } |
| | | |
| | | /**==============用户-角色-菜单================**/ |
| | |
| | | package com.whyc.filter; |
| | | |
| | | import org.springframework.core.annotation.Order; |
| | | |
| | | import javax.servlet.*; |
| | | import javax.servlet.annotation.WebFilter; |
| | | import javax.servlet.http.HttpServletRequest; |
New file |
| | |
| | | package com.whyc.filter; |
| | | |
| | | import com.whyc.pojo.User; |
| | | import com.whyc.util.ShiroUtil; |
| | | |
| | | import javax.servlet.*; |
| | | import javax.servlet.annotation.WebFilter; |
| | | import javax.servlet.http.HttpServletRequest; |
| | | import javax.servlet.http.HttpSession; |
| | | import java.io.IOException; |
| | | |
| | | /** |
| | | * 账号同时登录只能1个 |
| | | */ |
| | | @WebFilter(urlPatterns = "/*",filterName = "kickedOutFilter") |
| | | public class KickedOutFilter implements Filter { |
| | | |
| | | @Override |
| | | public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { |
| | | HttpSession session = ((HttpServletRequest) request).getSession(); |
| | | //如果是登录,则不进行Session对比,放行 |
| | | if(!((HttpServletRequest) request).getRequestURI().contains("login")) { |
| | | User user = ShiroUtil.getUser(); |
| | | if (user.getId() != 0) { |
| | | System.out.println("Filter过滤器中获取到的当前Session的SessionId为:" + session.getId()); |
| | | if (!request.getServletContext().getAttribute(user.getName()).equals(session.getId())) { |
| | | //如果当前Session所对应的SessionId与全局中用户对应的SessionId不一致,则清除当前Session |
| | | session.invalidate(); |
| | | response.setContentType("text/html;charset=utf-8"); |
| | | response.getWriter().write("<script language='javascript' type='text/javascript'>alert('账号已经在其他地方登录,请重新登录');self.location='login.html'</script> "); |
| | | return; |
| | | } |
| | | } |
| | | } |
| | | |
| | | chain.doFilter(request,response); |
| | | } |
| | | } |
| | |
| | | |
| | | import com.whyc.pojo.Permission; |
| | | import com.whyc.pojo.RolePermission; |
| | | import org.apache.ibatis.annotations.Param; |
| | | import org.apache.ibatis.annotations.Select; |
| | | |
| | | import java.util.List; |
| | |
| | | */ |
| | | public interface RolePermissionMapper extends CustomMapper<RolePermission> { |
| | | |
| | | @Select("select p.privilege from tb_role_privilege rp inner join tb_privilege p on rp.privilege_id = p.id inner join tb_user_role ur\n" + |
| | | @Select("select p.name from tb_role_permission rp inner join tb_permission p on rp.permission_id = p.id inner join tb_user_role ur\n" + |
| | | "on rp.role_id = ur.role_id\n" + |
| | | "where ur.user_id=1 \n") |
| | | List<Permission> getPermissions(Integer userId); |
| | | |
| | | List<String> findPermissionsByUserId(@Param("userId") int userId); |
| | | } |
| | |
| | | package com.whyc.mapper; |
| | | |
| | | import com.whyc.pojo.Role; |
| | | import com.whyc.pojo.User; |
| | | import com.whyc.pojo.UserRole; |
| | | import org.apache.ibatis.annotations.Param; |
| | | |
| | | import java.util.List; |
| | | import java.util.Map; |
| | |
| | | List<UserRole> getUserWithRole(); |
| | | |
| | | List<UserRole> getUserWithRoleMap(); |
| | | |
| | | List<String> findRolesByUserId(@Param("userId") int userId); |
| | | } |
| | |
| | | /** |
| | | * 权限 |
| | | */ |
| | | @Alias("Privilege") |
| | | @TableName( schema = "`db_3.5mw_web`",value = "tb_privilege") |
| | | @Alias("Permission") |
| | | @TableName( schema = "`db_3.5mw_web`",value = "tb_permission") |
| | | public class Permission { |
| | | |
| | | private Integer id; |
| | | private String permission; |
| | | private String name; |
| | | |
| | | public Integer getId() { |
| | | return id; |
| | |
| | | this.id = id; |
| | | } |
| | | |
| | | public String getPermission() { |
| | | return permission; |
| | | public String getName() { |
| | | return name; |
| | | } |
| | | |
| | | public void setPermission(String permission) { |
| | | this.permission = permission; |
| | | public void setName(String name) { |
| | | this.name = name; |
| | | } |
| | | } |
| | |
| | | private Integer id; |
| | | @TableField("name") |
| | | private String name; |
| | | /**中文名*/ |
| | | private String label; |
| | | |
| | | public Role() { |
| | | } |
| | |
| | | public void setName(String name) { |
| | | this.name = name; |
| | | } |
| | | |
| | | public String getLabel() { |
| | | return label; |
| | | } |
| | | |
| | | public void setLabel(String label) { |
| | | this.label = label; |
| | | } |
| | | } |
| | |
| | | import org.apache.shiro.subject.PrincipalCollection; |
| | | import org.apache.shiro.util.ByteSource; |
| | | import org.springframework.beans.factory.annotation.Autowired; |
| | | import org.springframework.context.annotation.Lazy; |
| | | |
| | | import javax.annotation.PostConstruct; |
| | | |
| | |
| | | @Realm |
| | | public class CustomRealm extends AuthorizingRealm { |
| | | |
| | | /**必须@Lazy注解,@Lazy与@Autowired组合,使得依赖于Service相关的Bean都是lazy-resolution proxy*/ |
| | | @Lazy |
| | | @Autowired |
| | | UserBridgeService userBridgeService; |
| | | |
| | |
| | | import org.apache.shiro.subject.Subject; |
| | | import org.springframework.stereotype.Service; |
| | | |
| | | import javax.servlet.http.HttpServletRequest; |
| | | import javax.servlet.http.HttpSession; |
| | | |
| | | @Service |
| | | public class LoginService { |
| | | |
| | | public Response login(String userName, String password) { |
| | | public Response login(String userName, String password, HttpServletRequest request) { |
| | | UsernamePasswordToken userToken = new UsernamePasswordToken(userName, password); |
| | | Subject subject = SecurityUtils.getSubject(); |
| | | try { |
| | |
| | | return new Response<>().set(1,false); |
| | | } |
| | | if (subject.isAuthenticated()){ |
| | | //每个登录的用户都有一个全局变量,里面存着对应的SessionId; |
| | | //同一个账号,后面登录的,会挤掉之前登录的SessionId |
| | | System.out.println("全局存储中当前SessionId为:"+request.getSession().getId()); |
| | | request.getServletContext().setAttribute(userName,request.getSession().getId()); |
| | | return new Response<>().set(1,true); |
| | | } |
| | | return new Response<>().set(1,false); |
| | |
| | | @Resource |
| | | private RolePermissionMapper mapper; |
| | | |
| | | public boolean bindingUserWithRole(int roleId, int privilegeId) { |
| | | return mapper.insert(new RolePermission(roleId,privilegeId))>0; |
| | | public boolean bindingUserWithRole(int roleId, int permissionId) { |
| | | return mapper.insert(new RolePermission(roleId,permissionId))>0; |
| | | } |
| | | |
| | | @Transactional |
| | |
| | | return mapper.insertBatchSomeColumn(rolePermissions)== rolePermissions.size(); |
| | | } |
| | | |
| | | public List<Permission> getPrivileges(Integer userId) { |
| | | public List<Permission> getPermissions(Integer userId) { |
| | | return mapper.getPermissions(userId); |
| | | } |
| | | } |
| | |
| | | |
| | | import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; |
| | | import com.baomidou.mybatisplus.core.toolkit.Wrappers; |
| | | import com.whyc.mapper.PermissionMapper; |
| | | import com.whyc.mapper.RoleMapper; |
| | | import com.whyc.mapper.UserMapper; |
| | | import com.whyc.mapper.*; |
| | | import com.whyc.pojo.Permission; |
| | | import com.whyc.pojo.User; |
| | | import org.apache.shiro.authz.AuthorizationInfo; |
| | | import org.apache.shiro.authz.SimpleAuthorizationInfo; |
| | | import org.springframework.cache.annotation.CacheConfig; |
| | | import org.springframework.cache.annotation.Cacheable; |
| | | import org.springframework.context.annotation.Lazy; |
| | | import org.springframework.stereotype.Service; |
| | | |
| | | import javax.annotation.Resource; |
| | |
| | | * 处理 shiro认证,授权,和数据库交互 |
| | | */ |
| | | @Service |
| | | //Unified Naming |
| | | @CacheConfig(cacheNames ={"userBridge"}) |
| | | public class UserBridgeService { |
| | | |
| | | @Resource |
| | | private UserMapper userMapper; |
| | | |
| | | @Resource |
| | | private RoleMapper roleMapper; |
| | | private UserRoleMapper userRoleMapper; |
| | | |
| | | @Resource |
| | | private PermissionMapper permissionMapper; |
| | | private RolePermissionMapper rolePermissionMapper; |
| | | |
| | | public User findPasswordAndSlatByUserName(String userName) { |
| | | QueryWrapper<User> queryWrapper = Wrappers.query(); |
| | | queryWrapper.select("id","password","salt").eq("name",userName); |
| | | queryWrapper.select("id","name","password","salt").eq("name",userName); |
| | | try{ |
| | | return userMapper.selectOne(queryWrapper); |
| | | }catch (Exception e){ |
| | |
| | | } |
| | | } |
| | | |
| | | @Cacheable(cacheNames = "authorizationCache",key = "#root.method") |
| | | @Cacheable(key = "#root.methodName+#p0.id") |
| | | public AuthorizationInfo getAuthorizationInfo(User user) { |
| | | System.out.println("=========执行了UserBridgeService.getAuthorization方法=========="); |
| | | SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); |
| | | //添加Roles和Permissions |
| | | List<String> roles = this.findRolesByUserId(user.getId()); |
| | | List<String> perms = this.findPermissionsByUserId(user.getId()); |
| | | List<String> roles = findRolesByUserId(user.getId()); |
| | | List<String> perms = findPermissionsByUserId(user.getId()); |
| | | |
| | | authorizationInfo.addRoles(roles); |
| | | authorizationInfo.addStringPermissions(perms); |
| | | return authorizationInfo; |
| | | } |
| | | |
| | | //@Cacheable(key = "#root.methodName+#userId") |
| | | private List<String> findPermissionsByUserId(int userId) { |
| | | QueryWrapper<Permission> query = Wrappers.query(); |
| | | List<String> perms = new LinkedList<>(); |
| | | //perms.add("water:all"); |
| | | List<String> perms = rolePermissionMapper.findPermissionsByUserId(userId); |
| | | return perms; |
| | | } |
| | | |
| | | //@Cacheable(key="#root.methodName+#userId") |
| | | private List<String> findRolesByUserId(int userId) { |
| | | List<String> roles = new LinkedList<>(); |
| | | List<String> roles =userRoleMapper.findRolesByUserId(userId); |
| | | //roles.add("dev"); |
| | | return roles; |
| | | } |
| | |
| | | |
| | | package com.whyc.util; |
| | | |
| | | import com.mysql.cj.core.util.StringUtils; |
| | | import com.whyc.constant.SuperConstant; |
| | | import com.whyc.pojo.User; |
| | | import org.apache.shiro.SecurityUtils; |
| | | import org.apache.shiro.session.Session; |
| | | import org.apache.shiro.subject.Subject; |
| | | import org.apache.shiro.util.ThreadContext; |
| | | |
| | | |
| | | /** |
| | |
| | | return subject.isAuthenticated(); |
| | | } |
| | | |
| | | public static User getUser() { |
| | | if (!isNullOrEmpty(ThreadContext.getSubject()) && !isNullOrEmpty(SecurityUtils.getSubject().getPrincipal())) { |
| | | return (User) SecurityUtils.getSubject().getPrincipal(); |
| | | }else { |
| | | return new User(0,"none"); |
| | | } |
| | | } |
| | | |
| | | public static boolean isNullOrEmpty(Object obj) { |
| | | if (obj == null || "".equals(obj)) { |
| | | return true; |
| | | } else { |
| | | return false; |
| | | } |
| | | } |
| | | } |
| | |
| | | #静态资源不拦截 |
| | | /static/**=anon |
| | | #登录链接不拦截 |
| | | login.html=anon |
| | | /login.html=anon |
| | | /login/**=anon |
| | | index.html=anon |
| | | /index.html=anon |
| | | #接口文档相关不拦截 |
| | | /doc.html=anon |
| | | /webjars/**=anon |
New file |
| | |
| | | <?xml version="1.0" encoding="UTF-8"?> |
| | | <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> |
| | | <mapper namespace="com.whyc.mapper.RolePermissionMapper" > |
| | | |
| | | <select id="findPermissionsByUserId" resultType="java.lang.String"> |
| | | select p.name from tb_user_role ur,tb_role_permission rp,tb_permission p |
| | | where ur.role_id = rp.role_id |
| | | and rp.permission_id=p.id |
| | | and user_id=#{userId}; |
| | | </select> |
| | | </mapper> |
| | |
| | | FROM tb_user_role userRole,tb_user user,tb_role role |
| | | WHERE user.id = userRole.user_id and userRole.role_id=role.id group by roleId |
| | | </select> |
| | | <select id="findRolesByUserId" resultType="string"> |
| | | select r.name from tb_user_role ur,tb_role r where ur.role_id=r.id and ur.user_id=#{userId}; |
| | | </select> |
| | | </mapper> |
| | |
| | | <title>Title</title> |
| | | </head> |
| | | <body> |
| | | <h1>web页面加载成功!</h1> |
| | | <h1>Index页面加载成功!</h1> |
| | | </body> |
| | | </html> |