备份自用
- pom.xml
org.apache.shiro
shiro-spring
1.3.2
- ShiroConfig
package com.school.service.config;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.linkedHashMap;
import java.util.Map;
@Configuration
public class ShiroConfig {
@Bean(name = "shiroFilter")
public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager){
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
shiroFilterFactoryBean.setLoginUrl("/school/goToLogin");//设置登录页面
shiroFilterFactoryBean.setUnauthorizedUrl("/school/goToLogin");//权限不足跳转页面,这个在Default过滤器中设置无效,具体看 https://blog.csdn.net/bicheng4769/article/details/86680955
Map filterChainDefinitionMap = new linkedHashMap<>();
//
filterChainDefinitionMap.put("/service/school
public class MyRealm extends AuthorizingRealm {
@Autowired
IUserService userService;
@Override //权限认证,发放权限
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
String username = (String) SecurityUtils.getSubject().getPrincipal();
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
Set stringSet = new HashSet<>();
stringSet.add("user:show");
stringSet.add("user:admin");
info.setStringPermissions(stringSet);
return info;
}
@Override //身份认证,验证登录
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("-------身份认证方法--------");
String userCode = (String) authenticationToken.getPrincipal();
String userPwd = new String((char[]) authenticationToken.getCredentials());
//根据用户名从数据库获取密码
User user = userService.getByUserCode(userCode);
String password = null;
if (user != null)
password = user.getPassword();
if (userCode == null || user == null) {
throw new AccountException("用户名不正确");
} else if (!userPwd.equals(password )) {
throw new AccountException("密码不正确");
}
return new SimpleAuthenticationInfo(userCode, password,getName());
}
}
- 注册时密码加盐加密
注册的时候将密码加密存储到数据库。
private static String hashAlgorithmName = "MD5"; //加密方式
private static final int hashIterations = 2; //加密的次数
private static final String salt = new SecureRandomNumberGenerator().nextBytes().toHex(); //盐
// private static final String salt = "6LCi5pmo5ZWK";
public static String getMD5Passwoed(String password){
//加密
SimpleHash simpleHash = new SimpleHash(hashAlgorithmName, password, salt, hashIterations);
return simpleHash.toString();
}
登录时
String getPassword = getMD5Passwoed(password); // 在认证提交前准备 token(令牌) UsernamePasswordToken token = new UsernamePasswordToken(userCode, getPassword);
注册时
String encryptionPassword = getMD5Passwoed(password);//获取加密密码 //保存到数据库



