1. Create a SpringBoot project

Select Web and Thymeleaf

1.1 the new index. HTML

<! DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> The < / head > < body > < h1 > home page < / h1 > < p th: text = "${MSG}" > < / p > < / body > < / HTML >Copy the code

1.2 Creating a Controller

package com.yao.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class MyController { @RequestMapping({"/","/index"}) public String toIndex(Model model){ model.addAttribute("msg","hello,Shiro"); return "index"; }}Copy the code

Keep shiro’s top three targets in mind

1. Subject: user

2.SecurityManager: Manages all users

Realm: Connect data

1.3 Importing dependency packages for integration

< the dependency > < groupId > org, apache shiro < / groupId > < artifactId > shiro - spring < / artifactId > < version > 1.4.1 < / version > </dependency>Copy the code

1.4 Create a config and write it

package com.yao.config; import org.springframework.context.annotation.Configuration; @ Configuration public class ShiroConfig {/ / ShiroFilterFactoryBean / / DefaultWebSecurityManager / / objects created realm, This realm object needs to be customized}Copy the code

Create your own RealmConfig, i.e. create another configuration class UserRealm in config

package com.yao.config; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; Public class UserRealm extends AuthorizingRealm {Override protected AuthorizationInfo DoGetAuthorizationInfo (PrincipalCollection PrincipalCollection) {system.out.println (" PrincipalCollection... ); return null; } // Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken AuthenticationToken) throws AuthenticationException {system.out.println (" AuthenticationException ") ); return null; }}Copy the code

1.6 Register UserRealm with ShiroConfig. We wrote this class and spring hosted it

1.7 Create two new test pages and rewrite the index page

add.html

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>add</h1> </body> </html>Copy the code

update.html

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>update</h1> </body>  </html>Copy the code

index.html

<! DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> < / head > < body > < h1 > home page < / h1 > < p th: text = "${MSG}" > < / p > < hr > < th: a href = "@ {/ user/add}" > add < / a > | < a th:href="@{/user/update}">update</a> </body> </html>Copy the code

1.8 Writing the Controller layer

package com.yao.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class MyController { @RequestMapping({"/","/index"}) public String toIndex(Model model){ model.addAttribute("msg","hello,Shiro"); return "index"; } @RequestMapping("/user/add") public String add(){ return "user/add"; } @RequestMapping("/user/update") public String update(){ return "user/update"; }}Copy the code

1.9 Adding a Filter

In shiroconfig, add:

// Add Shiro's built-in filter /* anon: access without authentication authc: access with authentication user: access with authentication perms: access with permission to a resource role: */ Map<String,String> filterMap = new LinkedHashMap<>(); // filterMap.put("/user/add","authc"); // filterMap.put("/user/update","authc"); filterMap.put("/user/*","authc"); bean.setFilterChainDefinitionMap(filterMap); // Set the login request bean.setLoginURL ("/toLogin"); return bean;Copy the code

I want to jump from add and update to login without authentication so I have to write a login page and rewrite the Controller

The controller layer:

@RequestMapping("/toLogin")
public String toLogin(){
return "login";
}
Copy the code

The login page:

<! DOCTYPE HTML > < HTML lang="en"> <head> <meta charset="UTF-8"> <title> </head> <body> <form> <p> <input type="text" name="username"></p> <input type="text" name="password"></p> <p><input type="submit"></p> </form> </body> </html>Copy the code

1.10 The page blocking function has been completed above. Next, the user authentication work has been implemented

login.html:

<! DOCTYPE HTML > < HTML lang="en" XMLNS :th="http://www.thymeleaf.org"> <head> <meta charset=" utF-8 "> <title> </head> <body> <p th:text="${msg}" style="color: Red "> < / p > < form th: action =" @ {/ login} "> < p > username: < input type =" text "name =" username "> < / p > < p > password: <input type="text" name="password"></p> <p><input type="submit"></p> </form> </body> </html>Copy the code

controller:

@requestMapping ("/login") public String login(String username,String password,Model Model){// Obtain the current user Subject Subject = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken(username, password); try { subject.login(token); Return "index"; } Catch (UnknownAccountException e) {model. AddAttribute (" MSG "," UnknownAccountException "); return "login"; {} the catch (IncorrectCredentialsException e) model. The addAttribute (" MSG ", "password error"); return "login"; }}Copy the code

UserRealm:

// Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {system.out.println (" AuthenticationException ") ); // User name and password String name = "root"; String password = "123456"; UsernamePasswordToken userToken = (UsernamePasswordToken) token; if(! userToken.getUsername().equals(name)){ return null; Return new SimpleAuthenticationInfo("",password,""); return SimpleAuthenticationInfo("",password,""); }}Copy the code

Direct test can be found above function basic realization.

package com.yao.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class MyController { @RequestMapping({"/","/index"}) public String toIndex(Model model){ model.addAttribute("msg","hello,Shiro"); return "index"; }}Copy the code

2. Mybatis springboot integration

2.1 Importing Dependencies

<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> Log4j </groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.12</version> </dependency> <dependency> < the groupId > org. Mybatis. Spring. The boot < / groupId > < artifactId > mybatis - spring - the boot - starter < / artifactId > < version > 2.1.0 < / version >  </dependency>Copy the code

2.2 Compiling the configuration file application.yml

spring: datasource: username: root password: 892095368llq #? ServerTimezone = UTC time zone solving error url: JDBC: mysql: / / localhost: 3306 / yao? serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8 driver-class-name: com.mysql.cj.jdbc.Driver type: Com. Alibaba. Druid. Pool. # DruidDataSource Spring Boot is not inject the attribute values by default, the need to binding # druid proprietary data source configuration initialSize: 5 minIdle: 5 maxActive: 20 maxWait: 60000 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: SELECT 1 FROM DUAL testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: True # configuration monitoring statistics of intercepting filters, stat: monitoring statistics, log4j: logging, wall: the defense against SQL injection # if allowed times wrong Java. Lang. ClassNotFoundException: Org, apache log4j. Priority # import log4j dependence can, Maven address: https://mvnrepository.com/artifact/log4j/log4j filters: stat,wall,log4j maxPoolPreparedStatementPerConnectionSize: 20 useGlobalDataSourceStat: true connectionProperties: druid.stat.mergeSql=true; druid.stat.slowSqlMillis=500Copy the code

2.3 Compile the configuration file application.properties and create a mapper folder

application.properties

mybatis.type-aliases-package=com.yao.pojo
mybatis.mapper-locations=classpath:mapper/*.xml
Copy the code

2.4 Create a POJO layer and configure Lombok

< the dependency > < groupId > org. Projectlombok < / groupId > < artifactId > lombok < / artifactId > < version > 1.16.10 < / version > </dependency>Copy the code

Write a user.java

package com.yao.pojo;
 
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
 
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String name;
    private String pwd;
}
Copy the code

2.4 Create a Mapper layer and write the corresponding Mapper interface and mapper implementation in Resources

UserMapper interface

package com.yao.mapper; import com.yao.pojo.User; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Repository; @Repository @Mapper public interface UserMapper { public User queryUserByName(String name); } mapper. xml <? The XML version = "1.0" encoding = "utf-8"? > <! DOCTYPE mapper PUBLIC "- / / mybatis.org//DTD mapper / 3.0 / EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > < mapper namespace="com.yao.mapper.UserMapper"> <select id="queryUserByName" parameterType="String" resultType="User"> select * from user where name = #{name} </select> </mapper>Copy the code

UserService.interface

package com.yao.service; import com.yao.pojo.User; public interface UserService { public User queryUserByName(String name); } UserServiceImpl.java package com.yao.service; import com.yao.mapper.UserMapper; import com.yao.pojo.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserServiceImpl implements UserService{ @Autowired UserMapper userMapper; @Override public User queryUserByName(String name) { return userMapper.queryUserByName(name); }}Copy the code

2.6 Testing in Test

package com.yao; import com.yao.service.UserService; import com.yao.service.UserServiceImpl; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class ShiroSpringbootApplicationTests { @Autowired UserServiceImpl userService; @ Test void contextLoads () {System. Out. Println (userService. QueryUserByName (" MAO MAO ")); }}Copy the code

Test successful, continue writing

2.7 change UserRealm

package com.yao.config; import com.yao.pojo.User; import com.yao.service.UserService; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.*; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.subject.Subject; import org.springframework.beans.factory.annotation.Autowired; Public class UserRealm extends AuthorizingRealm {@autoWired UserService UserService; Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection PrincipalCollection) { System.out.println(" authorized... ") ); return null; } // Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {system.out.println (" AuthenticationException ") ); UsernamePasswordToken userToken = (UsernamePasswordToken) token; / / a real database connection User User = userService. QueryUserByName (userToken. GetUsername ()); if (user==null){ return null; Return new SimpleAuthenticationInfo("",user.getPwd(),""); }}Copy the code

2.8 Adding Password Encryption

// There is also an MD5 encryption, Integrates the hashcode is not reversible / / such as your password is 123456 / / md5 (123456, 32) = e10adc3949ba59abbe56e057f20f883e / / md5 = (123456) 49 ba59abbe56e057 / / MD5 encryption e10adc3949ba59abbe56e057f20f883eusername salt value / / password authentication, won't let you do it yourself, Return new SimpleAuthenticationInfo("",user.getPwd(),"");Copy the code

2.9 Requesting Authorization Implementation

2.10 binding thymeleaf

package com.yao.mapper;

import com.yao.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

@Repository
@Mapper
public interface UserMapper {
public User queryUserByName(String name);
}
Copy the code

Recommended reading

Why are Alibaba’s programmers growing so fast?

What? Is SpringCloud on the way out?

What exactly is Project Pegasus? Tens of thousands of programmers are fascinated by it

How much is appropriate for a year and a half of development experience?

After watching three things

If you find this article helpful, I’d like to invite you to do three small favors for me:

Like, forward, have your “like and comment”, is the motivation of my creation.

Follow the public account “Java Doudi” to share original knowledge from time to time.

Also look forward to the follow-up article ing🚀