springboot整合shiro+mybatis-plus
文章目錄
- Shiro框架簡介
- 環(huán)境搭建springboot+shiro+mybatis-plus+thymeleaf
- 1.創(chuàng)建Spring Boot項目,集成Shiro及相關(guān)組件
- 2.準(zhǔn)備一個sql表
- 3.配置yml
- 4.創(chuàng)建表的實體類
- 5.創(chuàng)建mybatis-plus的basemapper接口
- 6.創(chuàng)建UserService接口實現(xiàn)
- 7.創(chuàng)建UserServiceImpl業(yè)務(wù)邏輯
- 8.編寫自定義Realm認(rèn)證授權(quán)
- 9.編寫Shiro的配置類
- 10.編寫controller控制器
- 11.編寫controller對應(yīng)的界面html
- 12.啟動器測試
- shiro完美解釋
Shiro框架簡介
Apache Shiro是一個強(qiáng)大且易用的Java安全框架,執(zhí)行身份認(rèn)證丶授權(quán)丶密碼和會話管理。
以用戶登錄為例-多圖參考↓
Shiro主要用來用戶認(rèn)證和用戶授權(quán)
用戶認(rèn)證 — 用戶身份識別。得知道來的人是誰;
用戶授權(quán) — 用戶權(quán)限訪問控制。得知道來的人有沒有資格進(jìn)來,又不是“我家大門常打開”;
環(huán)境搭建springboot+shiro+mybatis-plus+thymeleaf
springboot+shiro+mybatis-plus+thymeleaf
目錄結(jié)構(gòu)
1.創(chuàng)建Spring Boot項目,集成Shiro及相關(guān)組件
pom.xml
2.準(zhǔn)備一個sql表
創(chuàng)建數(shù)據(jù)庫 create database 數(shù)據(jù)庫名;選擇數(shù)據(jù)庫 use 數(shù)據(jù)庫名;創(chuàng)建數(shù)據(jù)表
create database shirompdb;use shirompdb;create table account(id int AUTO_INCREMENT,name varchar(30) default null,password varchar(30) default null,perms varchar(30) default null,primary key(id) )engine=innodb charset=utf8;mysql連接idea并且添加幾個用戶
3.配置yml
spring:datasource:url: jdbc:mysql://localhost:3306/shirompdbusername: rootpassword: guohuidriver-class-name: com.mysql.cj.jdbc.Driverthymeleaf:prefix: classpath:/templates4.創(chuàng)建表的實體類
pojo
@Data @AllArgsConstructor @NoArgsConstructor @TableName("account")//account 對應(yīng)數(shù)據(jù)庫的表 public class user {private Integer id;private String name;private String password;private String perms; }5.創(chuàng)建mybatis-plus的basemapper接口
mapper
@Repository public interface UserMapper extends BaseMapper<user> {}6.創(chuàng)建UserService接口實現(xiàn)
service
@Service public interface UserService {public user queryUserByName(String name); }7.創(chuàng)建UserServiceImpl業(yè)務(wù)邏輯
service/impl
@Service public class UserServiceImpl implements UserService {@Autowiredprivate UserMapper userMapper;@Overridepublic user queryUserByName(String name) {QueryWrapper wrapper = new QueryWrapper();wrapper.eq("name",name);return userMapper.selectOne(wrapper);} }8.編寫自定義Realm認(rèn)證授權(quán)
shiro
public class AccountRealm extends AuthorizingRealm {@Autowiredprivate UserService userService;//。1 自定義的Realm@Override//授權(quán)protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {System.out.println("執(zhí)行了授權(quán)===》doGetAuthorizationInfo");SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();//拿到當(dāng)前登陸的對象Subject subject = SecurityUtils.getSubject();//拿到account對象user currentUser = (user) subject.getPrincipal();//設(shè)置當(dāng)前用戶權(quán)限info.addStringPermission(currentUser.getPerms());return info;}@Override//認(rèn)證protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {System.out.println("執(zhí)行了認(rèn)證===》doGetAuthenticationInfo");//連接數(shù)據(jù)庫UsernamePasswordToken Token = (UsernamePasswordToken) authenticationToken;user user = userService.queryUserByName(Token.getUsername());if (user != null) {return new SimpleAuthenticationInfo(user, user.getPassword(), getName());}return null;} }9.編寫Shiro的配置類
config
@Configuration public class ShiroConfig {//3. 連接前端 ShiroFilterFactoryBean@Beanpublic ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager) {ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();//設(shè)置安全管理器bean.setSecurityManager(defaultWebSecurityManager);/* 添加Shiro的內(nèi)置過濾器anon: 無需認(rèn)證就可以訪問authc: 必須認(rèn)證了才能訪問user: 必須擁有我 記住我 功能才能訪問perms: 擁有對莫個資源的權(quán)限才能訪問role: 擁有莫個角色權(quán)限才能訪問*/LinkedHashMap<String, String> filterMap = new LinkedHashMap<>();filterMap.put("/user/add", "perms[user:add]");//user,的add anon設(shè)置所有人可以訪問filterMap.put("/user/update", "perms[user:update]");//user,的update authc設(shè)置認(rèn)證了才能訪問bean.setFilterChainDefinitionMap(filterMap);bean.setLoginUrl("/tologin");bean.setUnauthorizedUrl("/noauth");return bean;}//2. 接管對象 DafaultWebSecurityManager@Beanpublic DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("userRealm") AccountRealm userRealm) {DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();//關(guān)聯(lián)userReal 接管reaml對象securityManager.setRealm(userRealm);return securityManager;}//1. 創(chuàng)建realm對象 、需要自定義@Beanpublic AccountRealm userRealm() {return new AccountRealm();} }10.編寫controller控制器
controller
@Controller public class MyController {@RequestMapping("/index")public String toIndex(Model model) {model.addAttribute("msgTest", "hello,shiro");return "index";}@RequestMapping("user/add")public String add() {return "user/add";}@RequestMapping("user/update")public String update() {return "user/update";}@RequestMapping("/tologin")public String toLonin() {return "login";}@RequestMapping("/login")public String login(String username, String password, Model model) {//獲取當(dāng)前的用戶Subject subject = SecurityUtils.getSubject();//封裝用戶的登錄數(shù)據(jù)UsernamePasswordToken token = new UsernamePasswordToken(username, password);try {//執(zhí)行登錄的方法subject.login(token);return "index";} catch (UnknownAccountException e) {//用戶名不存在model.addAttribute("msg","用戶名錯誤");return "login";}catch (IncorrectCredentialsException e){//密碼錯誤model.addAttribute("msg","密碼錯誤");return "login";}}@RequestMapping("/noauth")@ResponseBodypublic String unauthorized(){return "未授權(quán)無法訪問此頁面";} }11.編寫controller對應(yīng)的界面html
templates\index.html
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro"> <head><meta charset="UTF-8"><title>shiro學(xué)習(xí)</title> </head> <body> <H1>首頁</H1> <p th:test="${msgTest}"></p> <hr> <div shiro:hasPermission="user:add"></div> <a th:href="@{/user/add}">add</a> <div shiro:hasPermission="user:update"></div> <a th:href="@{/user/update}">update</a> </body> </html>templates\login.html
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head><meta charset="UTF-8"><title>shiro登錄</title> </head> <body> <div><p th:text="${msg}" style="color: #ff0000"></p><form method="get" th:action="@{/login}"><p>用戶名:<input type="text" name="username"></p><p>密 碼:<input type="text" name="password"></p><p><input type="submit" value="登錄"></p></form> </div> </body> </html>templates\user\add.html
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>加一個用戶</title> </head> <body> <h1>add</h1> </body> </html>templates\user\update.html
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>修改一個用戶</title> </head> <body> <h1>update</h1> </body> </html>12.啟動器測試
啟動類上添加@MapperScan(“com.guohui.mapper”) 掃描你自己mapper
@SpringBootApplication @MapperScan("com.guohui.mapper") public class SpringbootShirotestApplication {public static void main(String[] args) {SpringApplication.run(SpringbootShirotestApplication.class, args);} }啟動測試
用戶認(rèn)證 — 用戶身份識別
用戶授權(quán) — 用戶權(quán)限訪問控制。
shiro完美解釋
讓 Apache Shiro 保護(hù)你的應(yīng)用
總結(jié)
以上是生活随笔為你收集整理的springboot整合shiro+mybatis-plus的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SpringBoot整合Shiro(认证
- 下一篇: vm固定ip