文章字数:455,阅读全文大约需要1分钟
shiro
是一个可以管理项目权限的框架
springBoot中引入 maven
依赖添加
1 2 3 4 5 <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.4.0</version> </dependency>
密码加密工具类 shiro
提供了加密、生成随机盐的方法,封装成工具类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 import org.apache.shiro.crypto.SecureRandomNumberGenerator;import org.apache.shiro.crypto.RandomNumberGenerator;import org.apache.shiro.crypto.hash.SimpleHash;import org.apache.shiro.util.ByteSource;public class PasswordHelper { private RandomNumberGenerator randomOb = new RandomNumberGenerator(); private static final String ALGORITHM_NAME = "md5" ; private static final int HASH_ITERATION = 2 ; public void encryptPassword (User user) { user.setSalt(randomOb.nextBytes().toHex()); String newPassword = new SimpleHash(ALGORITHM_NAME ,user.getPwd,ByteSource.Util.bytes(user.getSalt()),HASH_ITERATION).toHex(); user.setPwd(newPassword ); } }
自定义Realm shiro
需要我们提供doGetAuthenticationInfo
和doGetAuthorizationInfo
的实现,已完成登录认证和权限信息。 自定义Realm
,继承与AuthorizingRealm
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 public class EnceladusShiroRealm extends AuthorizingRealm { @Autowired private UserService userService; @Override protected AuthorizationInfo doGetAuthorizationInfo (PrincipalCollection principals) { SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); String userName = (String) principals.getPrimaryPrincipal(); User user = userService.findUserByName(userName); for (SysRole role : user.getRoles()) { authorizationInfo.addRole(role.getRole()); for (SysPermission permission : role.getPermissions()) { authorizationInfo.addStringPermission(permission.getName()); } } return authorizationInfo; } @Override protected AuthenticationInfo doGetAuthenticationInfo (AuthenticationToken token) throws AuthenticationException { String userName = (String) token.getPrincipal(); User user = userService.findUserByName(username); if (user == null ) return null ; SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo( user.getUsername(), user.getPassword(), ByteSource.Util.bytes(user.getCredentialsSalt()), getName()); return authenticationInfo; } }
shiro配置 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 @Configuration public class ShiroConfig { @Bean public ShiroFilterFactoryBean shirFilter (SecurityManager securityManager) { ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); shiroFilterFactoryBean.setSecurityManager(securityManager); Map<String, String> filterChainDefinitionMap = new HashMap<String, String>(); shiroFilterFactoryBean.setLoginUrl("/login" ); shiroFilterFactoryBean.setUnauthorizedUrl("/unauthc" ); shiroFilterFactoryBean.setSuccessUrl("/home/index" ); filterChainDefinitionMap.put("/*" , "anon" ); filterChainDefinitionMap.put("/authc/index" , "authc" ); filterChainDefinitionMap.put("/authc/admin" , "roles[admin]" ); filterChainDefinitionMap.put("/authc/renewable" , "perms[Create,Update]" ); filterChainDefinitionMap.put("/authc/removable" , "perms[Delete]" ); shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); return shiroFilterFactoryBean; } @Bean public HashedCredentialsMatcher hashedCredentialsMatcher () { HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher(); hashedCredentialsMatcher.setHashAlgorithmName(PasswordHelper.ALGORITHM_NAME); hashedCredentialsMatcher.setHashIterations(PasswordHelper.HASH_ITERATIONS); return hashedCredentialsMatcher; } @Bean public EnceladusShiroRealm shiroRealm () { EnceladusShiroRealm shiroRealm = new EnceladusShiroRealm(); shiroRealm.setCredentialsMatcher(hashedCredentialsMatcher()); return shiroRealm; } @Bean public SecurityManager securityManager () { DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); securityManager.setRealm(shiroRealm()); return securityManager; } @Bean public PasswordHelper passwordHelper () { return new PasswordHelper(); } }
1 2 3 4 5 常用的过滤器如下: authc:所有已登陆用户可访问 roles:有指定角色的用户可访问,通过[ ]指定具体角色,这里的角色名称与数据库中配置一致 perms:有指定权限的用户可访问,通过[ ]指定具体权限,这里的权限名称与数据库中配置一致 anon:所有用户可访问,通常作为指定页面的静态资源时使用
test 获取权限的操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.IncorrectCredentialsException; import org.apache.shiro.authc.UnknownAccountException; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.subject.Subject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.learnhow.springboot.web.PasswordHelper; import com.learnhow.springboot.web.entity.User; import com.learnhow.springboot.web.service.UserService; @RestController @RequestMapping public class HomeController { @Autowired private UserService userService; @Autowired private PasswordHelper passwordHelper; @GetMapping("login") public Object login() { return "Here is Login page"; } @GetMapping("unauthc") public Object unauthc() { return "Here is Unauthc page"; } @GetMapping("doLogin") public Object doLogin(@RequestParam String username, @RequestParam String password) { UsernamePasswordToken token = new UsernamePasswordToken(username, password); Subject subject = SecurityUtils.getSubject(); try { subject.login(token); } catch (IncorrectCredentialsException ice) { return "password error!"; } catch (UnknownAccountException uae) { return "username error!"; } User user = userService.findUserByName(username); subject.getSession().setAttribute("user", user); return "SUCCESS"; } @GetMapping("register") public Object register(@RequestParam String username, @RequestParam String password) { User user = new User(); user.setUsername(username); user.setPassword(password); passwordHelper.encryptPassword(user); userService.saveUser(user); return "SUCCESS"; } }
权限拦截
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 import org.apache.shiro.SecurityUtils;import org.apache.shiro.subject.Subject;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import com.learnhow.springboot.web.entity.User;@RestController @RequestMapping ("authc" )public class AuthcController { @GetMapping ("index" ) public Object index () { Subject subject = SecurityUtils.getSubject(); User user = (User) subject.getSession().getAttribute("user" ); return user.toString(); } @GetMapping ("admin" ) public Object admin () { return "Welcome Admin" ; } @GetMapping ("removable" ) public Object removable () { return "removable" ; } @GetMapping ("renewable" ) public Object renewable () { return "renewable" ; } }