springboot整合shiro(含MD5加密)
开发环境:
1、mysql - 5.7.21
2、navicat(mysql客户端管理工具)
3、idea 2017
4、jdk9
5、tomcat 8.5
6、springboot
7、mybatis 3
8、shiro
9、maven
项目开始:
一、数据库设计:
注:数据库三张表和spring整合shiro中的一模一样,在那边已经详细说明,这里直接大家看下三张表的ER图。
二、添加依赖,配置mybatis
1、用idea新建Spring Initializr项目,项目结构如下:
2、添加依赖:
org.springframework.boot spring-boot-starter-web org.mybatis.spring.boot mybatis-spring-boot-starter 1.3.2 mysql mysql-connector-java runtime org.springframework.boot spring-boot-starter-tomcat provided org.springframework.boot spring-boot-starter-test test org.apache.shiro shiro-core 1.2.3 org.apache.shiro shiro-spring 1.2.3 com.alibaba druid 1.0.20 org.apache.commons commons-lang3 3.4 org.springframework spring-context-support 4.1.7.RELEASE org.apache.tomcat.embed tomcat-embed-jasper javax.servlet jstl javax.servlet javax.servlet-api 3、application.propertiesspring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql:///#
spring.datasource.username=#
spring.datasource.password=#
mybatis.mapper-locations=mappers/*.xml
mybatis.type-aliases-package=com.zhu.shiro.entity
spring.mvc.view.prefix=/pages/
spring.mvc.view.suffix=.jsp
三、项目设计
注:spring整合shiro中是只有User实体类,在UserDao中定义了三个方法,通过表的关键关系查询Role和Permission;这里将采用另一种方式,三个实体类,设置实体类的关联关系。
1、entity层
User.java
public class User {
private Integer uid;
private String username;
private String password;
private Set roles = new HashSet<>();
}
Role.java
public class Role {
private Integer rid;
private String name;
private Set permissions = new HashSet<>();
}
Permission.java
public class Permission {
private Integer pid;
private String name;
}
2、dao层
UserDao.java
public interface UserDao {
User findByUsername(String username);
}
UserDao.xml
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public User findByUsername(String username) {
return userDao.findByUsername(username);
}
}
4、junit测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserServiceImplTest {
@Autowired
private UserService userService;
@Test
public void findByUsername() {
User u = userService.findByUsername(“tom”);
Set roleSet = u.getRoles();
for (Role role : roleSet){
Set permissionSet = role.getPermissions();
for (Permission permission : permissionSet){
System.out.println(permission.getName());
}
System.out.println(role.getName());
}
}
}
运行结果:
数据库中tom是admin角色,有增删改查权限,符合预期,测试通过。5、controller层
TestController.java
@Controller
public class TestController {
//用户登录
@RequestMapping("/loginUser")
public String loginUser(@RequestParam(“username”) String username,
@RequestParam(“password”) String password,
HttpSession session) {
//把前端输入的username和password封装为token
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
Subject subject = SecurityUtils.getSubject();
try {
subject.login(token);
session.setAttribute(“user”, subject.getPrincipal());
return “index”;
} catch (Exception e) {
return “login”;
}
}
//退出登录
@RequestMapping("/logout")
public String logout() {
Subject subject = SecurityUtils.getSubject();
if (subject != null) {
subject.logout();
}
return “login”;
}
//访问login时跳到login.jsp
@RequestMapping("/login")
public String login() {
return “login”;
}
//admin角色才能访问
@RequestMapping("/admin")
@ResponseBody
public String admin() {
return “admin success”;
}
//有delete权限才能访问
@RequestMapping("/edit")
@ResponseBody
public String edit() {
return “edit success”;
}
@RequestMapping("/test")
@ResponseBody
@RequiresRoles(“guest”)
public String test(){
return “test success”;
}
}
说明:这里用户登录方法用到了shiro,但是这里还没配置shiro,所以暂时不能使用,先搭起整个骨架,然后再加入shiro。
6、jsp页面
login.jsp
(登录页面)
%@ page contentType=“text/html;charset=UTF-8” language=“java” %>
Login(登录成功跳转的页面)
<%@ page contentType=“text/html;charset=UTF-8” language=“java” %>
Title(无权访问跳转的页面)
<%@ page contentType=“text/html;charset=UTF-8” language=“java” %>
unauthorized unauthorized! 现在说一下要求:admin路由要求只有具有admin角色的用户才能访问,edit路由需要有delete权限的用户才能访问,test路由要guest角色才能访问,login、loginUser都不做拦截,本文讲解两种拦截方式,对test的拦截是在controller对应的方法上加注解,其他是拦截是写在shiro的配置类中。
预期分析:
tom是有admin角色和所有权限,所以用tom登录后,可以访问edit和admin,但是不能访问guest;而cat是guest角色,只有create和query权限,所以不能访问admin和edit,但是可以访问guest。
四、配置shiro
由于springboot还没有集成shiro,所以不能直接在application.properties中配置,需要通过类的方式配置。
核心配置类:
ShiroConfiguration.java
@Configuration
public class ShiroConfiguration {
/**
自定义realm:
AutuRealm.java
public class AuthRealm extends AuthorizingRealm{
@Autowired
private UserService userService;
/**
这样就完成了springboot对shiro的整合,接下来就可以进行测试了!
五、测试
tom访问admin
cat登录
cat访问test
测试结果与预期相符,测试通过,springboot整合shiro成功!
特别说明:
由于设置了MD5加密,所以数据库中存储的用户密码应该是加密后的密文,否则在登录页面输入明文会验证不通过。假如1234的密文为asdfghjkl,数据库中存储的应该是asdfghjkl,在登录时输入1234就能验证通过。
附上明文转密文的代码:
public static void main(String[] args) {
String hashAlgorithName = “MD5”;
String password = “登录时输入的密码”;
int hashIterations = 1024;//加密次数
ByteSource credentialsSalt = ByteSource.Util.bytes(“登录时输入的用户名”);
Object obj = new SimpleHash(hashAlgorithName, password, credentialsSalt, hashIterations);
System.out.println(obj);
}
若不使用MD5加密
1、添加一个类
public class CredenttiaMatcher extends SimpleCredentialsMatcher{
@Override
public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
String password = new String(usernamePasswordToken.getPassword());
String dbPassword = (String) info.getCredentials();
return this.equals(password,dbPassword);
}
}
2、将ShiroConfiguration.java中名为"hashedCredentialsMatcher"的bean替换成:
*@Bean(“credenttiaMatcher”)
public CredenttiaMatcher credenttiaMatcher() {
return new CredenttiaMatcher();
}
将名为"authRealm"的bean替换成:
@Bean(“authRealm”)
@DependsOn(“lifecycleBeanPostProcessor”)//可选
public AuthRealm authRealm(@Qualifier(“credenttiaMatcher”) CredenttiaMatcher matcher) {
AuthRealm authRealm = new AuthRealm();
authRealm.setCredentialsMatcher(matcher);
return authRealm;
}
3、AuthRealm.java中的doGetAuthenticationInfo方法里面的内容替换成:
//=未加密版==
//token携带了用户登录的信息
UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
//获取前端输入的用户名
String username = usernamePasswordToken.getUsername();
//根据前端输入的用户名查询数据库中的记录
User user = userService.findByUsername(username);
//校验密码,验证登录
return new SimpleAuthenticationInfo(user,user.getPassword(),this.getClass().getName());
完成以上3步就去掉了MD5加密。
以上内容属于个人学习笔记整理,如有错误,欢迎批评指正!