4.数据库
建表语句在项目中有,项目地址: https://github.com/justdojava/java-samples
5.自定义 realm
public class MyShiroRealm extends AuthorizingRealm { @Autowired private UserService userService; @Autowired private RoleService roleService; @Autowired private PermissionService permissionService; @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); // HttpServletRequest request = (HttpServletRequest) ((WebSubject) SecurityUtils // .getSubject()).getServletRequest();//这个可以用来获取在登录的时候提交的其他额外的参数信息 String username = (String) principals.getPrimaryPrincipal(); // 受理权限 // 角色 Set<String> roles = new HashSet<String>(); Role role = roleService.getRoleByUserName(username); System.out.println(role.getRoleName()); roles.add(role.getRoleName()); authorizationInfo.setRoles(roles); // 权限 Set<String> permissions = new HashSet<String>(); List<Permission> querypermissions = permissionService.getPermissionsByRoleId(role.getId()); for (Permission permission : querypermissions) { permissions.add(permission.getPermissionName()); } authorizationInfo.setStringPermissions(permissions); return authorizationInfo; } @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException { String loginName = (String) authcToken.getPrincipal(); // 获取用户密码 User user = userService.getOne(new QueryWrapper<User>().eq("username", loginName)); if (user == null) { // 没找到帐号 throw new UnknownAccountException(); } String password = new String((char[]) authcToken.getCredentials()); String inpass = (new Md5Hash(password, user.getUsername())).toString(); if (!user.getPassword().equals(inpass)) { throw new IncorrectCredentialsException(); } // 交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配 SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(loginName, user.getPassword(), ByteSource.Util.bytes(loginName), getName()); return authenticationInfo; } }
6.shiro 配置类
@Configuration public class ShiroConfiguration { private static final Logger logger = LoggerFactory.getLogger(ShiroConfiguration.class); /** * Shiro的Web过滤器Factory 命名:shiroFilter */ @Bean(name = "shiroFilter") public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) { ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); // Shiro的核心安全接口,这个属性是必须的 shiroFilterFactoryBean.setSecurityManager(securityManager); //需要权限的请求,如果没有登录则会跳转到这里设置的url shiroFilterFactoryBean.setLoginUrl("/login.html"); //设置登录成功跳转url,一般在登录成功后自己代码设置跳转url,此处基本没用 shiroFilterFactoryBean.setSuccessUrl("/main.html"); //设置无权限跳转界面,此处一般不生效,一般自定义异常 shiroFilterFactoryBean.setUnauthorizedUrl("/error.html"); Map<String, Filter> filterMap = new LinkedHashMap<>(); // filterMap.put("authc", new AjaxPermissionsAuthorizationFilter()); shiroFilterFactoryBean.setFilters(filterMap); /* * 定义shiro过滤链 Map结构 * Map中key(xml中是指value值)的第一个'/'代表的路径是相对于HttpServletRequest.getContextPath()的值来的 * anon:它对应的过滤器里面是空的,什么都没做,这里.do和.jsp后面的*表示参数,比方说login.jsp?main这种 * authc:该过滤器下的页面必须验证后才能访问,它是Shiro内置的一个拦截器org.apache.shiro.web.filter.authc. * FormAuthenticationFilter */ Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>(); /* * 过滤链定义,从上向下顺序执行,一般将 /**放在最为下边; authc:所有url都必须认证通过才可以访问; * anon:所有url都都可以匿名访问 */ filterChainDefinitionMap.put("/login.html", "authc"); filterChainDefinitionMap.put("/login", "anon"); filterChainDefinitionMap.put("/js/**", "anon"); filterChainDefinitionMap.put("/css/**", "anon"); filterChainDefinitionMap.put("/logout", "logout"); filterChainDefinitionMap.put("/**", "authc"); shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); return shiroFilterFactoryBean; } /** * 权限管理 */ @Bean public SecurityManager securityManager() { logger.info("=======================shiro======================="); DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); securityManager.setRealm(MyShiroRealm()); // securityManager.setRememberMeManager(rememberMeManager); return securityManager; } /** * Shiro Realm 继承自AuthorizingRealm的自定义Realm,即指定Shiro验证用户登录的类为自定义的 */ @Bean public MyShiroRealm MyShiroRealm() { MyShiroRealm userRealm = new MyShiroRealm(); userRealm.setCredentialsMatcher(hashedCredentialsMatcher()); return userRealm; } /** * 凭证匹配器 密码验证 */ @Bean(name = "credentialsMatcher") public HashedCredentialsMatcher hashedCredentialsMatcher() { HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher(); // 散列算法:这里使用MD5算法; hashedCredentialsMatcher.setHashAlgorithmName("md5"); // 散列的次数,比如散列两次,相当于 md5(md5("")); hashedCredentialsMatcher.setHashIterations(1); // storedCredentialsHexEncoded默认是true,此时用的是密码加密用的是Hex编码;false时用Base64编码 hashedCredentialsMatcher.setStoredCredentialsHexEncoded(true); return hashedCredentialsMatcher; } /** * 开启Shiro的注解(如@RequiresRoles,@RequiresPermissions),需借助SpringAOP扫描使用Shiro注解的类,并在必要时进行安全逻辑验证 */ @Bean public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor() { AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor(); authorizationAttributeSourceAdvisor.setSecurityManager(securityManager()); return authorizationAttributeSourceAdvisor; } }
7.测试类
@RestController public class UserController { @PostMapping("login") public String name(String username, String password) { String result = "已登录"; Subject currentUser = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken(username, password); if (!currentUser.isAuthenticated()) { try { currentUser.login(token);// 会触发com.shiro.config.MyShiroRealm的doGetAuthenticationInfo方法 result = "登录成功"; } catch (UnknownAccountException e) { result = "用户名错误"; } catch (IncorrectCredentialsException e) { result = "密码错误"; } } return result; } @GetMapping("logout") public void logout() { Subject currentUser = SecurityUtils.getSubject(); currentUser.logout(); } @RequiresPermissions("role:update") @GetMapping("/role") public String name() { return "hello"; } @RequiresPermissions("user:select") @GetMapping("/role2") public String permission() { return "hello sel"; } }