springboot整合shiro+mybatis-plus
文章目錄
- Shiro框架簡(jiǎn)介
- 環(huán)境搭建springboot+shiro+mybatis-plus+thymeleaf
- 1.創(chuàng)建Spring Boot項(xiàng)目,集成Shiro及相關(guān)組件
- 2.準(zhǔn)備一個(gè)sql表
- 3.配置yml
- 4.創(chuàng)建表的實(shí)體類(lèi)
- 5.創(chuàng)建mybatis-plus的basemapper接口
- 6.創(chuàng)建UserService接口實(shí)現(xiàn)
- 7.創(chuàng)建UserServiceImpl業(yè)務(wù)邏輯
- 8.編寫(xiě)自定義Realm認(rèn)證授權(quán)
- 9.編寫(xiě)Shiro的配置類(lèi)
- 10.編寫(xiě)controller控制器
- 11.編寫(xiě)controller對(duì)應(yīng)的界面html
- 12.啟動(dòng)器測(cè)試
- shiro完美解釋
Shiro框架簡(jiǎn)介
Apache Shiro是一個(gè)強(qiáng)大且易用的Java安全框架,執(zhí)行身份認(rèn)證丶授權(quán)丶密碼和會(huì)話管理。
以用戶(hù)登錄為例-多圖參考↓
Shiro主要用來(lái)用戶(hù)認(rèn)證和用戶(hù)授權(quán)
用戶(hù)認(rèn)證 — 用戶(hù)身份識(shí)別。得知道來(lái)的人是誰(shuí);
用戶(hù)授權(quán) — 用戶(hù)權(quán)限訪問(wèn)控制。得知道來(lái)的人有沒(méi)有資格進(jìn)來(lái),又不是“我家大門(mén)常打開(kāi)”;
環(huán)境搭建springboot+shiro+mybatis-plus+thymeleaf
springboot+shiro+mybatis-plus+thymeleaf
目錄結(jié)構(gòu)
1.創(chuàng)建Spring Boot項(xiàng)目,集成Shiro及相關(guān)組件
pom.xml
2.準(zhǔn)備一個(gè)sql表
創(chuàng)建數(shù)據(jù)庫(kù) create database 數(shù)據(jù)庫(kù)名;選擇數(shù)據(jù)庫(kù) use 數(shù)據(jù)庫(kù)名;創(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并且添加幾個(gè)用戶(hù)
3.配置yml
spring:datasource:url: jdbc:mysql://localhost:3306/shirompdbusername: rootpassword: guohuidriver-class-name: com.mysql.cj.jdbc.Driverthymeleaf:prefix: classpath:/templates4.創(chuàng)建表的實(shí)體類(lèi)
pojo
@Data @AllArgsConstructor @NoArgsConstructor @TableName("account")//account 對(duì)應(yīng)數(shù)據(jù)庫(kù)的表 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接口實(shí)現(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.編寫(xiě)自定義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)前登陸的對(duì)象Subject subject = SecurityUtils.getSubject();//拿到account對(duì)象user currentUser = (user) subject.getPrincipal();//設(shè)置當(dāng)前用戶(hù)權(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ù)庫(kù)UsernamePasswordToken Token = (UsernamePasswordToken) authenticationToken;user user = userService.queryUserByName(Token.getUsername());if (user != null) {return new SimpleAuthenticationInfo(user, user.getPassword(), getName());}return null;} }9.編寫(xiě)Shiro的配置類(lèi)
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)置過(guò)濾器anon: 無(wú)需認(rèn)證就可以訪問(wèn)authc: 必須認(rèn)證了才能訪問(wèn)user: 必須擁有我 記住我 功能才能訪問(wèn)perms: 擁有對(duì)莫個(gè)資源的權(quán)限才能訪問(wèn)role: 擁有莫個(gè)角色權(quán)限才能訪問(wèn)*/LinkedHashMap<String, String> filterMap = new LinkedHashMap<>();filterMap.put("/user/add", "perms[user:add]");//user,的add anon設(shè)置所有人可以訪問(wèn)filterMap.put("/user/update", "perms[user:update]");//user,的update authc設(shè)置認(rèn)證了才能訪問(wèn)bean.setFilterChainDefinitionMap(filterMap);bean.setLoginUrl("/tologin");bean.setUnauthorizedUrl("/noauth");return bean;}//2. 接管對(duì)象 DafaultWebSecurityManager@Beanpublic DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("userRealm") AccountRealm userRealm) {DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();//關(guān)聯(lián)userReal 接管reaml對(duì)象securityManager.setRealm(userRealm);return securityManager;}//1. 創(chuàng)建realm對(duì)象 、需要自定義@Beanpublic AccountRealm userRealm() {return new AccountRealm();} }10.編寫(xiě)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)前的用戶(hù)Subject subject = SecurityUtils.getSubject();//封裝用戶(hù)的登錄數(shù)據(jù)UsernamePasswordToken token = new UsernamePasswordToken(username, password);try {//執(zhí)行登錄的方法subject.login(token);return "index";} catch (UnknownAccountException e) {//用戶(hù)名不存在model.addAttribute("msg","用戶(hù)名錯(cuò)誤");return "login";}catch (IncorrectCredentialsException e){//密碼錯(cuò)誤model.addAttribute("msg","密碼錯(cuò)誤");return "login";}}@RequestMapping("/noauth")@ResponseBodypublic String unauthorized(){return "未授權(quán)無(wú)法訪問(wèn)此頁(yè)面";} }11.編寫(xiě)controller對(duì)應(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>首頁(yè)</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>用戶(hù)名:<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>加一個(gè)用戶(hù)</title> </head> <body> <h1>add</h1> </body> </html>templates\user\update.html
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>修改一個(gè)用戶(hù)</title> </head> <body> <h1>update</h1> </body> </html>12.啟動(dòng)器測(cè)試
啟動(dòng)類(lèi)上添加@MapperScan(“com.guohui.mapper”) 掃描你自己mapper
@SpringBootApplication @MapperScan("com.guohui.mapper") public class SpringbootShirotestApplication {public static void main(String[] args) {SpringApplication.run(SpringbootShirotestApplication.class, args);} }啟動(dòng)測(cè)試
用戶(hù)認(rèn)證 — 用戶(hù)身份識(shí)別
用戶(hù)授權(quán) — 用戶(hù)權(quán)限訪問(wèn)控制。
shiro完美解釋
讓 Apache Shiro 保護(hù)你的應(yīng)用
總結(jié)
以上是生活随笔為你收集整理的springboot整合shiro+mybatis-plus的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: SpringBoot整合Shiro(认证
- 下一篇: mysql基础语法(常用)