Spring Boot中引入Jpa和Shiro
Apache Shiro是一个强大且易用的Java安全框架,具有身份验证、授权、密码加密和会话管理功能。
三个核心组件:Subject, SecurityManager 和 Realms
Subject:主体,代表了当前用户,Subject也可以是第三方进程、后台帐户(Daemon Account)等。Subject代表了当前用户的安全操作,SecurityManager则管理所有用户的安全操作。
SecurityManager:安全管理器;Shiro框架的核心,典型的Facade模式,Shiro通过SecurityManager来管理内部组件实例,并通过它来提供安全管理的各种服务。
Realm:域,Shiro从从Realm获取安全数据(如用户、角色、权限),就是说当对用户执行认证(登录)和授权(访问控制)验证时,Shiro会从应用配置的Realm中查找用户及其权限信息。
本次使用了JPA框架的表关联查询,自定义模式可能更好。
1、配置
上篇已引入Jpa,本文不重复已有内容
pom.xml
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.0</version>
</dependency>
application.properties
#输出SQL语句
spring.jpa.show-sql=true
ShiroConfig.java
@Configuration
public class ShiroConfig {
@Bean
//org.apache.shiro.mgt.SecurityManager
public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
System.out.println("ShiroConfiguration.shirFilter()");
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
//拦截器.
Map<String,String> filterChainDefinitionMap = new LinkedHashMap<String,String>();
// 配置不会被拦截的链接 顺序判断
filterChainDefinitionMap.put("/*.ico", "anon");
//配置退出 过滤器,其中的具体的退出代码Shiro已经替我们实现了
filterChainDefinitionMap.put("/logout", "logout");
//<!-- 过滤链定义,从上向下顺序执行,一般将/**放在最为下边 -->:这是一个坑呢,一不小心代码就不好使了;
//<!-- authc:所有url都必须认证通过才可以访问; anon:所有url都都可以匿名访问-->
filterChainDefinitionMap.put("/**", "authc");
// 如果不设置默认会自动寻找Web工程根目录下的"/login.jsp"页面
shiroFilterFactoryBean.setLoginUrl("/login");
// 登录成功后要跳转的链接
shiroFilterFactoryBean.setSuccessUrl("/index");
//未授权界面;
shiroFilterFactoryBean.setUnauthorizedUrl("/403");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
}
/**
* 凭证匹配器
* (由于我们的密码校验交给Shiro的SimpleAuthenticationInfo进行处理了 )
* @return
*/
@Bean
public HashedCredentialsMatcher hashedCredentialsMatcher(){
HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
//散列算法:这里使用MD5算法;
hashedCredentialsMatcher.setHashAlgorithmName("md5");
//散列的次数,比如散列两次,相当于 md5(md5(""));
hashedCredentialsMatcher.setHashIterations(1);
return hashedCredentialsMatcher;
}
@Bean
public MyShiroRealm myShiroRealm(){
MyShiroRealm myShiroRealm = new MyShiroRealm();
myShiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());
return myShiroRealm;
}
@Bean
public SecurityManager securityManager(){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//the realm to set for a single-realm application
securityManager.setRealm(myShiroRealm());
return securityManager;
}
/**
* 开启shiro aop注解支持.
* 使用代理方式;所以需要开启代码支持
* 加入注解的使用,不加入这个注解不生效
* @param securityManager
* @return
*/
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager sm){
AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
advisor.setSecurityManager(sm);
return advisor;
}
@Bean(name="simpleMappingExceptionResolver")
public SimpleMappingExceptionResolver createSimpleMappingExceptionResolver() {
SimpleMappingExceptionResolver r = new SimpleMappingExceptionResolver();
Properties mappings = new Properties();
mappings.setProperty("DatabaseException", "databaseError");//数据库异常处理
mappings.setProperty("UnauthorizedException","403");
r.setExceptionMappings(mappings); // None by default
r.setDefaultErrorView("error"); // No default
r.setExceptionAttribute("ex"); // Default is "exception"
//r.setWarnLogCategory("example.MvcLogger"); // No default
return r;
}
}
MyShiroRealm.java
/**
* 在认证、授权内部实现机制中都有提到,最终处理都将交给Realm进行处理。
* 因为在Shiro中,最终是通过Realm来获取应用程序中的用户、角色及权限信息的。
* 通常情况下,在Realm中会直接从我们的数据源中获取Shiro需要的验证信息。
* Realm是专用于安全框架的DAO
*/
public class MyShiroRealm extends AuthorizingRealm {
@Resource
private JpaUserRepository userRepository;
/**
* 授权,即权限验证
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(
PrincipalCollection principals) {
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
JpaUser userInfo = (JpaUser) principals.getPrimaryPrincipal();
for(SysUserRole role:userInfo.getRoleList()){
authorizationInfo.addRole(role.getRole_id()+"");
}
return authorizationInfo;
}
/**
* 认证过程:验证用户输入的账号和密码是否正确
* 1、检查提交的进行认证的令牌信息
* 2、根据令牌信息从数据源(通常为数据库)中获取用户信息
* 3、对用户信息进行匹配验证
* 4、验证通过将返回一个封装了用户信息的AuthenticationInfo实例
* 5、验证失败则抛出AuthenticationException异常信息
*/
@Override
public AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
throws AuthenticationException {
// 获取用户的输入的账号.
String username = (String) token.getPrincipal();
System.out.println("--AuthenticationInfo: "
+ String.valueOf((char[]) token.getCredentials()));
// 通过username从数据库中查找 User对象
// Shiro有时间间隔机制,2分钟内不会重复执行该方法
JpaUser userInfo = null;
List<JpaUser> userInfoList = userRepository.findByUsername(username);
if (userInfoList == null) {
return null;
} else if (userInfoList.size() <= 0) {
return null;
} else {
userInfo = userInfoList.get(0);
}
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
userInfo, // 用户名
userInfo.getPassword(), // 密码
//salt=username+salt
// ByteSource.Util.bytes(userInfo.getCredentialsSalt()),
getName() // realm name
);
return authenticationInfo;
}
}
2、业务模拟
JpaUser.java
@Entity
@Table(name = "user_info")
public class JpaUser{
@Id
private Integer id;
private String name;
private String username;
private String password;
private String salt;
private String state;
@OneToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
@JoinColumn(name="u_id",referencedColumnName = "id")
private List<SysUserRole> roleList;
//get,set...
/**
* 密码盐
* @return
*/
public String getCredentialsSalt(){
return this.username + this.salt;
}
public String toString() {
String roles = "";
if(roleList!=null){
for(SysUserRole role : roleList){
roles += role.getRole_id()+", ";
}
}
return "The Entity is userName:"+username+",passWord:"
+password+",id:"+id+"; roleid:"+roles;
}
}
SysUserRole.java
@Entity
@Table(name = "sys_user_role")
public class SysUserRole {
@Id
private Integer id;
@Column(name="role_id")
private Long roleid;
@Column(name="u_id")
private Long uid;
@ManyToOne
@JoinColumn(name="u_id",insertable=false,updatable=false)
private JpaUser jpaUser;
get,set...
}
UserController.java
@Controller
public class UserController {
@Autowired
// 自动从spring容器中加载userRepository
private JpaUserRepository userRepository;
@RequestMapping("/login")
public String login(HttpServletRequest request, Map<String, Object> map)
throws Exception {
// 登录失败从request中获取shiro处理的异常信息。
// shiroLoginFailure:就是shiro异常类的全类名.
String exception = (String) request.getAttribute("shiroLoginFailure");
System.out.println("-- shiroLoginFailure:" + exception);
String msg = "";
if (exception != null) {
if (UnknownAccountException.class.getName().equals(exception)) {
msg = "UnknownAccountException : 账号不存在";
} else if (IncorrectCredentialsException.class.getName().equals(exception)) {
msg = "IncorrectCredentialsException : 密码不正确";
} else if ("kaptchaValidateFailed".equals(exception)) {
msg = "kaptchaValidateFailed : 验证码错误";
} else {
msg = "exception: "+exception;
}
}
map.put("msg", msg);
// 此方法不处理登录成功,由shiro进行处理
return "/login";
}
}
login.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>用户登录-Login</title>
<link rel="stylesheet" th:href="@{css/bootstrap.css}" />
</head>
<body>
错误信息:<h4 th:text="${msg}"></h4>
<div class="form-group">
<div class="col-sm-2 control-label">
<form action="" method="post">
<p>账号:<input type="text" name="username" value="admin"/></p>
<p>密码:<input type="text" name="password" value="123456"/></p>
<p><input type="submit" value="登录"/></p>
</form>
</div>
</div>
</body>
</html>
3、测试
浏览器地址录入内容http://cos6743:8081/login