首先引入需要的pom
<dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring-boot-web-starter</artifactId> <version>1.4.1</version> </dependency>
配置application.properties
#登錄界面 shiro.loginUrl=/login #無權限界面 shiro.unauthorizedUrl=/403 #成功界面 shiro.successUrl=/index
自定義UserRealm
public class UserRealm extends AuthorizingRealm { @Autowired private UserService userService; @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { if(principalCollection == null){ throw new AuthenticationException("PrincipalCollection參數不能為空。"); } TUser user = (TUser) getAvailablePrincipal(principalCollection); if(ObjectUtils.isEmpty(user)){ throw new AuthenticationException("用戶不存在"); } SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); if(ObjectUtils.isEmpty(user.getRole())){ info.setRoles(new HashSet<String>(){{add("public");}}); }else{ info.setRoles(new HashSet<String>(){{add(user.getRole());}}); } return info; } @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken; String username = token.getUsername(); if(StringUtils.isEmpty(username)){ throw new UnknownAccountException(); } TUser user = userService.fetchByUsername(username); if(ObjectUtils.isEmpty(user)){ throw new UnknownAccountException(); } if(user.getDisabled()){ throw new LockedAccountException(); } SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,user.getPassword(),ByteSource.Util.bytes(user.getSalt()),getName()); return info; } }
添加用戶時密碼加密方法
public String md5(String password,String salt){ //加密方式 String algorithmName = "MD5"; //鹽值 ByteSource byteSalt = ByteSource.Util.bytes(salt); //加密次數 int hashIterations = 6; SimpleHash result = new SimpleHash(algorithmName, password, byteSalt, hashIterations); //Md2Hash Md5Hash Sha1Hash Sha256Hash Sha384Hash Sha512Hash 最后都是調用SimpleHash加密 //Md5Hash r = new Md5Hash(password,byteSalt,hashIterations); return result.toHex(); }
配置 ShiroConfig
@Configuration public class ShiroConfig { @Bean public Realm realm(){ UserRealm userRealm = new UserRealm(); userRealm.setCredentialsMatcher(hashedCredentialsMatcher()); return userRealm; } /** * 配置url * anon 任何人都能訪問 * authc 認證成功后才能訪問 */ @Bean public ShiroFilterChainDefinition shiroFilterChainDefinition(){ DefaultShiroFilterChainDefinition chain = new DefaultShiroFilterChainDefinition(); Map<String,String> pathDefinitions = new HashMap<>(); pathDefinitions.put("/loginDo","anon"); pathDefinitions.put("/**","authc"); chain.addPathDefinitions(pathDefinitions); return chain; } /** * 密碼驗證 * @return */ @Bean public HashedCredentialsMatcher hashedCredentialsMatcher(){ HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher(); credentialsMatcher.setHashAlgorithmName("MD5"); credentialsMatcher.setHashIterations(6); credentialsMatcher.setStoredCredentialsHexEncoded(true); return credentialsMatcher; } }
登錄controller
@PostMapping("/loginDo") @ResponseBody public Result loginDo(String username, String password, boolean rememberMe) { if(StringUtils.isEmpty(username)){ return Result.error("請輸入用戶名"); } if(StringUtils.isEmpty(password)){ return Result.error("請輸入密碼"); } try { Subject subject = SecurityUtils.getSubject(); subject.login(new UsernamePasswordToken(username, password, rememberMe)); } catch (UnknownAccountException e1) { return Result.error("用戶名或密碼錯誤"); } catch (LockedAccountException e2) { return Result.error("用戶已被鎖定"); } catch (AuthenticationException e3) { return Result.error("登錄失敗"); } return Result.success(); }