下面我将详细讲解springboot2.x整合shiro权限框架的使用的完整攻略。
一、前置知识
在学习springboot2.x整合shiro权限框架之前,需对以下知识点进行了解:
-
Spring框架
-
SpringMVC框架
-
Maven工具
-
Shiro框架
二、整合步骤
1.创建Springboot工程
在Maven中新建一个springboot项目,添加web和thymeleaf依赖,并引入shiro依赖。
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.7.0</version>
</dependency>
2.配置Shiro
在Springboot中使用Shiro需要对Shiro进行配置,创建ShiroConfig配置类,并使用注解@Configuration和@ImportResource引入shiro.ini文件。
@Configuration
@ImportResource(locations = { "classpath:shiro.ini" })
public class ShiroConfig {
}
3.添加自定义Realm
自定义Realm是Shiro进行权限验证的关键所在,我们需要继承org.apache.shiro.realm.Realm接口并实现其中的方法,进行用户身份认证和用户授权验证。
public class MyRealm implements Realm {
@Autowired
private UserService userService;
@Override
public String getName() {
return "MyRealm";
}
@Override
public boolean supports(AuthenticationToken token) {
return token instanceof UsernamePasswordToken;
}
@Override
public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String username = token.getPrincipal().toString();
User user = userService.findByName(username);
if (user == null) {
throw new UnknownAccountException();
}
return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), getName());
}
@Override
public AuthorizationInfo getAuthorizationInfo(PrincipalCollection principals) {
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
User user = userService.findByName(principals.getPrimaryPrincipal().toString());
info.addRoles(user.getRoleList());
info.addStringPermissions(user.getPermissionList());
return info;
}
}
4.配置SecurityManager
在ShiroConfig配置类中添加SecurityManager,并将自定义Realm添加到SecurityManager中。
@Bean
public SecurityManager securityManager() {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(myRealm());
return securityManager;
}
@Bean
public MyRealm myRealm() {
return new MyRealm();
}
5.配置Shiro的过滤器
对于不同的请求进行不同的权限验证,可以使用Shiro的过滤器。我们可以通过配置ShiroFilterFactoryBean来实现。
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
factoryBean.setSecurityManager(securityManager);
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
filterChainDefinitionMap.put("/", "anon");
filterChainDefinitionMap.put("/login", "anon");
filterChainDefinitionMap.put("/logout", "logout");
filterChainDefinitionMap.put("/admin/**", "roles[admin]");
filterChainDefinitionMap.put("/**", "authc");
factoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
factoryBean.setLoginUrl("/login");
factoryBean.setSuccessUrl("/index");
factoryBean.setUnauthorizedUrl("/unauthorized");
return factoryBean;
}
6.编写登录页面和授权页面
完成Shiro权限框架的配置之后,我们需要编写登录页面和授权页面,这里使用Thymeleaf模板引擎编写。
登录页面login.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<form action="/login" method="post">
<input type="text" name="username" placeholder="用户名">
<input type="password" name="password" placeholder="密码">
<button type="submit">登录</button>
</form>
</body>
</html>
授权页面index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>授权页面</title>
</head>
<body>
<h1>欢迎访问授权页面</h1>
</body>
</html>
7.编写Controller
编写登录Controller和授权Controller。
登录Controller:
@Controller
public class LoginController {
@GetMapping("/login")
public String login() {
return "login";
}
@PostMapping("/login")
public String checkLogin(String username, String password) {
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
try {
subject.login(token);
return "redirect:/index";
} catch (Exception e) {
return "redirect:/login";
}
}
@GetMapping("/logout")
public String logout() {
Subject subject = SecurityUtils.getSubject();
subject.logout();
return "redirect:/login";
}
}
授权Controller:
@Controller
public class IndexController {
@GetMapping("/index")
public String index() {
return "index";
}
@GetMapping("/admin")
public String admin() {
return "admin";
}
}
8.运行程序
完成上述步骤,我们就可以运行程序,输入正确用户名和密码可以访问授权页面,输入错误用户名和密码则跳转到登录页面。
三、示例
下面提供两个示例帮助理解整合过程:
示例一:shiro.ini配置文件
[users]
zhangsan = 123456, user
lisi = 123456, admin
[roles]
admin = *
[urls]
/admin/** = roles[admin]
/** = authc
示例二:自定义Realm
public class MyRealm implements Realm {
@Autowired
private UserService userService;
@Override
public String getName() {
return "MyRealm";
}
@Override
public boolean supports(AuthenticationToken token) {
return token instanceof UsernamePasswordToken;
}
@Override
public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String username = token.getPrincipal().toString();
User user = userService.findByName(username);
if (user == null) {
throw new UnknownAccountException();
}
return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), getName());
}
@Override
public AuthorizationInfo getAuthorizationInfo(PrincipalCollection principals) {
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
User user = userService.findByName(principals.getPrimaryPrincipal().toString());
info.addRoles(user.getRoleList());
info.addStringPermissions(user.getPermissionList());
return info;
}
}
以上就是springboot2.x整合shiro权限框架的使用的完整攻略。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:springboot2.x整合shiro权限框架的使用 - Python技术站