如果你对shiro有问题的话,请看这篇文章:Springboot+shiro,完整教程,带你学会shiro-CSDN博客
数据库需要准备三个表,一个user表,一个role表,一个permission表。
CREATE TABLE `user` (
`id` int NOT NULL,
`username` varchar(100) DEFAULT NULL,
`password` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
CREATE TABLE `role` (
`id` int NOT NULL,
`name` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
CREATE TABLE `permission` (
`id` int NOT NULL,
`name` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
然后插入数据:
第一个是user表,第二个是permission表,第三个是role表。大家自己建就是了。
4.0.0
org.tianfan
shiroTest
1.0-SNAPSHOT
8
8
UTF-8
org.apache.shiro
shiro-spring-boot-web-starter
1.9.1
com.baomidou
mybatis-plus-boot-starter
3.4.3
org.projectlombok
lombok
1.18.30
org.slf4j
slf4j-simple
1.7.21
compile
org.slf4j
jcl-over-slf4j
1.7.21
test
org.springframework.boot
spring-boot-starter-web
2.7.7
mysql
mysql-connector-java
8.0.31
commons-logging
commons-logging
1.2
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
url: jdbc:mysql://localhost:3306/tianfan?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
user类:
package org.tianfan.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import java.io.Serializable;
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class User implements Serializable {
private Long id;
private String username;
private String password;
}
Role类:
package org.tianfan.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import java.io.Serializable;
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Role implements Serializable {
private Long id;
private String name;
// getter and setter
}
permission类:
package org.tianfan.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import java.io.Serializable;
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Permission implements Serializable {
private Long id;
private String name;
// getter and setter
}
PermissionMapper
package org.tianfan.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.tianfan.pojo.Permission;
public interface PermissionMapper extends BaseMapper {
}
RoleMapper
package org.tianfan.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.tianfan.pojo.Role;
public interface RoleMapper extends BaseMapper {
}
UserMapper
package org.tianfan.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.tianfan.pojo.User;
@Mapper
public interface UserMapper extends BaseMapper {
}
UserService:
package org.tianfan.service;
import org.apache.ibatis.annotations.Mapper;
import org.tianfan.pojo.Permission;
import org.tianfan.pojo.Role;
import org.tianfan.pojo.User;
import java.util.List;
public interface UserService {
User findByUsername(String username);
List findRolesByUserId(Long userId);
List findPermissionsByRoleId(Long roleId);
}
UserServiceImpl
package org.tianfan.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.tianfan.mapper.PermissionMapper;
import org.tianfan.mapper.RoleMapper;
import org.tianfan.mapper.UserMapper;
import org.tianfan.pojo.Permission;
import org.tianfan.pojo.Role;
import org.tianfan.pojo.User;
import org.tianfan.service.UserService;
import java.util.ArrayList;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserMapper userMapper;
@Autowired
RoleMapper roleMapper;
@Autowired
PermissionMapper permissionMapper;
@Override
public User findByUsername(String username) {
LambdaQueryWrapper lambdaQueryWrapper=new LambdaQueryWrapper();
lambdaQueryWrapper.eq(User::getUsername,username);
User user = userMapper.selectOne(lambdaQueryWrapper);
System.out.println(user);
return user;
}
@Override
public List findRolesByUserId(Long userId) {
LambdaQueryWrapper lambdaQueryWrapper=new LambdaQueryWrapper();
lambdaQueryWrapper.eq("id",userId);
Role role = roleMapper.selectOne(lambdaQueryWrapper);
List list=new ArrayList<>();
list.add(role);
return list;
}
@Override
public List findPermissionsByRoleId(Long roleId) {
LambdaQueryWrapper lambdaQueryWrapper=new LambdaQueryWrapper();
lambdaQueryWrapper.eq("id",roleId);
Permission permission = permissionMapper.selectOne(lambdaQueryWrapper);
List list=new ArrayList<>();
list.add(permission);
return list;
}
}
package org.tianfan.config;
import org.apache.shiro.mgt.SessionsSecurityManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.apache.shiro.mgt.SecurityManager;
import java.util.LinkedHashMap;
import java.util.Map;
@Configuration
public class ShiroConfig {
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
Map filterChainDefinitionMap = new LinkedHashMap<>();
filterChainDefinitionMap.put("/login", "anon");
filterChainDefinitionMap.put("/login.html", "anon");
filterChainDefinitionMap.put("/**", "authc");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
}
@Bean
public SessionsSecurityManager securityManager(MyShiroRealm userRealm) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//配置realm
securityManager.setRealm(userRealm);
return securityManager;
}
@Bean
public MyShiroRealm myShiroRealm() {
MyShiroRealm myShiroRealm = new MyShiroRealm();
return myShiroRealm;
}
@Bean
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
return new LifecycleBeanPostProcessor();
}
@Bean
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
defaultAdvisorAutoProxyCreator.setProxyTargetClass(true);
return defaultAdvisorAutoProxyCreator;
}
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
return authorizationAttributeSourceAdvisor;
}
}
MyShiroRealm认证规格类:
package org.tianfan.config;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.tianfan.service.UserService;
import org.tianfan.pojo.Permission;
import org.tianfan.pojo.Role;
import org.tianfan.pojo.User;
import org.tianfan.service.impl.UserServiceImpl;
import java.util.List;
public class MyShiroRealm extends AuthorizingRealm {
@Autowired
private UserServiceImpl userService;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
User user = (User) principalCollection.getPrimaryPrincipal();
List roles = userService.findRolesByUserId(user.getId());
for (Role role : roles) {
authorizationInfo.addRole(role.getName());
List permissions = userService.findPermissionsByRoleId(role.getId());
for (Permission permission : permissions) {
authorizationInfo.addStringPermission(permission.getName());
}
}
return authorizationInfo;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
System.out.println(token.getUsername());
User user = userService.findByUsername(token.getUsername());
if (user == null) {
throw new UnknownAccountException();
}
return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
}
}
package org.tianfan.contoller;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.tianfan.pojo.User;
import org.tianfan.service.UserService;
@RestController
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/login")
public String login( String username, String password) {
System.out.println(username+password);
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
try {
subject.login(token);
return "登录成功";
} catch (AuthenticationException e) {
return "用户名或密码错误";
}
}
@GetMapping("/user")
public User getUser() {
Subject subject = SecurityUtils.getSubject();
return (User) subject.getPrincipal();
}
@GetMapping("/admin")
public String admin() {
return "admin";
}
}
package org.tianfan;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class);
}
}
登录表单
输入正确的密码:
之后就可以直接访问
如果没有登录正确的账号信息的话,就不可以访问这个,并且会直接跳转到login.jsp
如果你对shiro有问题的话,请看这篇文章:Springboot+shiro,完整教程,带你学会shiro-CSDN博客