Table of Contents
Springboot-cli development scaffolding series
2. Introduction
Preface
1. Environment
3. Realm configuration
4. Core configuration
5. Interface Write
6. Web page resources
首页
登陆页
用户信息
table
7. Effect demonstration
Home Java javaTutorial How Springboot integrates Shiro to implement login and permission verification

How Springboot integrates Shiro to implement login and permission verification

May 17, 2023 pm 02:55 PM
springboot shiro

Springboot-cli development scaffolding series

Springboot elegantly integrates Shiro for login verification and authority authentication (with source code download)

Introduction

Springboo configures Shiro for login Verification, authority authentication, demo demonstration attached.

Preface

We are committed to allowing developers to quickly build a basic environment and get applications running. We provide usage examples for users to refer to and allow beginners to get started quickly.

The source code address of this blog project:

Project source code github address

Project source code domestic gitee address

1. Environment

Dependencies

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

<!-- Shiro核心框架 -->

   <dependency>

       <groupId>org.apache.shiro</groupId>

       <artifactId>shiro-core</artifactId>

       <version>1.9.0</version>

   </dependency>

   <!-- Shiro使用Spring框架 -->

   <dependency>

       <groupId>org.apache.shiro</groupId>

       <artifactId>shiro-spring</artifactId>

       <version>1.9.0</version>

   </dependency>

   <!-- Thymeleaf中使用Shiro标签 -->

   <dependency>

       <groupId>com.github.theborakompanioni</groupId>

       <artifactId>thymeleaf-extras-shiro</artifactId>

       <version>2.1.0</version>

   </dependency>

   <dependency>

       <groupId>org.springframework.boot</groupId>

       <artifactId>spring-boot-starter-thymeleaf</artifactId>

   </dependency>

Copy after login

yml configuration

server:
port: 9999
servlet:
session:
# Let Tomcat only obtain session information from COOKIE, In this way, when there is no cookie, the URL will not be automatically added;jsessionid=….
tracking-modes: COOKIE

spring:
thymeleaf:
# Turn off page caching to facilitate development environment testing
cache: false
# Static resource path
prefix : classpath:/templates/
# Default .html ending for web resources is
mode: HTML

2. Introduction

Shiro’s three functional modules

  • Subject

Authentication subject, usually refers to the user (leave the operation to SecurityManager).

  • SecurityManager

Security manager, security manager, manages all Subjects and can cooperate with internal security components (associated with Realm)

  • Realm

Domain object is used to verify permission information. It is a bridge between shiro and data. For example, our login verification and permission verification are Realm is defined.

3. Realm configuration

Define the user entity User, which can be defined according to your own business

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

@Data

@Accessors(chain = true)

public class User {

    /**

     * 用户id

     */

    private Long userId;

    /**

     * 用户名

     */

    private String username;

    /**

     * 密码

     */

    private String password;

    /**

     * 用户别称

     */

    private String name;

}

Copy after login

Rewrite the login verification doGetAuthenticationInfo and authorization doGetAuthorizationInfo methods in AuthorizingRealm, write us Customized verification logic.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

/**

 * 自定义登录授权

 *

 * @author ding

 */

public class UserRealm extends AuthorizingRealm {

    /**

     * 授权

     * 此处权限授予

     */

    @Override

    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        // 在这里为每一个用户添加vip权限

        info.addStringPermission("vip");

        return info;

    }

    /**

     * 认证

     * 此处实现我们的登录逻辑,如账号密码验证

     */

    @Override

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        // 获取到token

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        // 从token中获取到用户名和密码

        String username = token.getUsername();

        String password = String.valueOf(token.getPassword());

        // 为了方便,这里模拟获取用户

        User user = this.getUser();

        if (!user.getUsername().equals(username)) {

            throw new UnknownAccountException("用户不存在");

        } else if (!user.getPassword().equals(password)) {

            throw new IncorrectCredentialsException("密码错误");

        }

        // 校验完成后,此处我们把用户信息返回,便于后面我们通过Subject获取用户的登录信息

        return new SimpleAuthenticationInfo(user, password, getName());

    }

    /**

     * 此处模拟用户数据

     * 实际开发中,换成数据库查询获取即可

     */

    private User getUser() {

        return new User()

                .setName("admin")

                .setUserId(1L)

                .setUsername("admin")

                .setPassword("123456");

    }

}

Copy after login

4. Core configuration

ShiroConfig.java

/**

* Shiro has built-in filters that can implement interceptors related to interceptors

* Frequently used filters:

* anon: No need for authentication (login) to access

* authc: Authentication is required to access

* user: If you use the rememberMe function, you can directly access

* perms: The resource must obtain resource permissions before it can be accessed, format perms[permission 1,permission 2]

* role: This resource must obtain role permission before it can access

**/

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

/**

 * shiro核心管理器

 *

 * @author ding

 */

@Configuration

public class ShiroConfig {

    /**

     * 无需认证就可以访问

     */

    private final static String ANON = "anon";

    /**

     * 必须认证了才能访问

     */

    private final static String AUTHC = "authc";

    /**

     * 拥有对某个资源的权限才能访问

     */

    private final static String PERMS = "perms";

    /**

     * 创建realm,这里返回我们上一把定义的UserRealm

     */

    @Bean(name = "userRealm")

    public UserRealm userRealm() {

        return new UserRealm();

    }

    /**

     * 创建安全管理器

     */

    @Bean(name = "securityManager")

    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {

        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();

        //绑定realm对象

        securityManager.setRealm(userRealm);

        return securityManager;

    }

    /**

     * 授权过滤器

     */

    @Bean

    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager) {

        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();

        // 设置安全管理器

        bean.setSecurityManager(defaultWebSecurityManager);

        // 添加shiro的内置过滤器

        Map<String, String> filterMap = new LinkedHashMap<>();

        filterMap.put("/index", ANON);

        filterMap.put("/userInfo", PERMS + "[vip]");

        filterMap.put("/table2", AUTHC);

        filterMap.put("/table3", PERMS + "[vip2]");

        bean.setFilterChainDefinitionMap(filterMap);

        // 设置跳转登陆页

        bean.setLoginUrl("/login");

        // 无权限跳转

        bean.setUnauthorizedUrl("/unAuth");

        return bean;

    }

    /**

     * Thymeleaf中使用Shiro标签

     */

    @Bean

    public ShiroDialect shiroDialect() {

        return new ShiroDialect();

    }

}

Copy after login

5. Interface Write

IndexController.java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

/**

 * @author ding

 */

@Controller

public class IndexController {

    @RequestMapping({"/", "/index"})

    public String index(Model model) {

        model.addAttribute("msg", "hello,shiro");

        return "/index";

    }

    @RequestMapping("/userInfo")

    public String table1(Model model) {

        return "userInfo";

    }

    @RequestMapping("/table")

    public String table(Model model) {

        return "table";

    }

    @GetMapping("/login")

    public String login() {

        return "login";

    }

    @PostMapping(value = "/doLogin")

    public String doLogin(@RequestParam("username") String username, @RequestParam("password") String password, Model model) {

        //获取当前的用户

        Subject subject = SecurityUtils.getSubject();

        //用来存放错误信息

        String msg = "";

        //如果未认证

        if (!subject.isAuthenticated()) {

            //将用户名和密码封装到shiro中

            UsernamePasswordToken token = new UsernamePasswordToken(username, password);

            try {

                // 执行登陆方法

                subject.login(token);

            } catch (Exception e) {

                e.printStackTrace();

                msg = "账号或密码错误";

            }

            //如果msg为空,说明没有异常,就返回到主页

            if (msg.isEmpty()) {

                return "redirect:/index";

            } else {

                model.addAttribute("errorMsg", msg);

                return "login";

            }

        }

        return "/login";

    }

    @GetMapping("/logout")

    public String logout() {

        SecurityUtils.getSubject().logout();

        return "index";

    }

    @GetMapping("/unAuth")

    public String unAuth() {

        return "unAuth";

    }

}

Copy after login

6. Web page resources

Create templates folder in resources to store page resources

index.html

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

<!DOCTYPE html>

<html xmlns:th="http://www.thymeleaf.org">

<html xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">

<head>

    <meta charset="UTF-8">

    <title>Title</title>

</head>

<body>

<h2 id="首页">首页</h2>

<!-- 使用shiro标签 -->

<shiro:authenticated>

    <p>用户已登录</p> <a th:href="@{/logout}" rel="external nofollow" >退出登录</a>

</shiro:authenticated>

<shiro:notAuthenticated>

    <p>用户未登录</p>  

</shiro:notAuthenticated>

<br/>

<a th:href="@{/userInfo}" rel="external nofollow" >用户信息</a>

<a th:href="@{/table}" rel="external nofollow" >table</a>

</body>

</html>

Copy after login

login.html

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

<!DOCTYPE html>

<html lang="en" xmlns:th="http://www.thymeleaf.org">

<head>

    <meta charset="UTF-8">

    <title>登陆页</title>

</head>

<body>

<div>

    <p th:text="${errorMsg}"></p>

    <form action="/doLogin" method="post">

        <h3 id="登陆页">登陆页</h3>

        <h7>账号:admin,密码:123456</h7>

        <input type="text" id="username"  name="username" placeholder="admin">

        <input type="password" id="password" name="password"  placeholder="123456">

        <button type="submit">登陆</button>

    </form>

</div>

</body>

</html>

Copy after login

userInfo.html

1

2

3

4

5

6

7

8

9

10

11

12

13

14

<!DOCTYPE html>

<html lang="en" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">

<head>

    <meta charset="UTF-8">

    <title>table1</title>

</head>

<body>

<h2 id="用户信息">用户信息</h2>

<!-- 利用shiro获取用户信息 -->

用户名:<shiro:principal property="username"/>

<br/>

用户完整信息: <shiro:principal/>

</body>

</html>

Copy after login

table.hetml

1

2

3

4

5

6

7

8

9

10

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>table</title>

</head>

<body>

<h2 id="table">table</h2>

</body>

</html>

Copy after login

7. Effect demonstration

Start project browser input127.0.0.1:9999

How Springboot integrates Shiro to implement login and permission verification

When we click on the user information and table, the login page will automatically jump

How Springboot integrates Shiro to implement login and permission verification

After successful login

How Springboot integrates Shiro to implement login and permission verification

Get user information

What we get here is the user information returned by our previous doGetAuthenticationInfo method, here for demonstration All are returned. In actual production, the password cannot be returned.

How Springboot integrates Shiro to implement login and permission verification

The above is the detailed content of How Springboot integrates Shiro to implement login and permission verification. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How Springboot integrates Jasypt to implement configuration file encryption How Springboot integrates Jasypt to implement configuration file encryption Jun 01, 2023 am 08:55 AM

Introduction to Jasypt Jasypt is a java library that allows a developer to add basic encryption functionality to his/her project with minimal effort and does not require a deep understanding of how encryption works. High security for one-way and two-way encryption. , standards-based encryption technology. Encrypt passwords, text, numbers, binaries... Suitable for integration into Spring-based applications, open API, for use with any JCE provider... Add the following dependency: com.github.ulisesbocchiojasypt-spring-boot-starter2. 1.1Jasypt benefits protect our system security. Even if the code is leaked, the data source can be guaranteed.

How SpringBoot integrates Redisson to implement delay queue How SpringBoot integrates Redisson to implement delay queue May 30, 2023 pm 02:40 PM

Usage scenario 1. The order was placed successfully but the payment was not made within 30 minutes. The payment timed out and the order was automatically canceled. 2. The order was signed and no evaluation was conducted for 7 days after signing. If the order times out and is not evaluated, the system defaults to a positive rating. 3. The order is placed successfully. If the merchant does not receive the order for 5 minutes, the order is cancelled. 4. The delivery times out, and push SMS reminder... For scenarios with long delays and low real-time performance, we can Use task scheduling to perform regular polling processing. For example: xxl-job Today we will pick

How to use Redis to implement distributed locks in SpringBoot How to use Redis to implement distributed locks in SpringBoot Jun 03, 2023 am 08:16 AM

1. Redis implements distributed lock principle and why distributed locks are needed. Before talking about distributed locks, it is necessary to explain why distributed locks are needed. The opposite of distributed locks is stand-alone locks. When we write multi-threaded programs, we avoid data problems caused by operating a shared variable at the same time. We usually use a lock to mutually exclude the shared variables to ensure the correctness of the shared variables. Its scope of use is in the same process. If there are multiple processes that need to operate a shared resource at the same time, how can they be mutually exclusive? Today's business applications are usually microservice architecture, which also means that one application will deploy multiple processes. If multiple processes need to modify the same row of records in MySQL, in order to avoid dirty data caused by out-of-order operations, distribution needs to be introduced at this time. The style is locked. Want to achieve points

How to solve the problem that springboot cannot access the file after reading it into a jar package How to solve the problem that springboot cannot access the file after reading it into a jar package Jun 03, 2023 pm 04:38 PM

Springboot reads the file, but cannot access the latest development after packaging it into a jar package. There is a situation where springboot cannot read the file after packaging it into a jar package. The reason is that after packaging, the virtual path of the file is invalid and can only be accessed through the stream. Read. The file is under resources publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

Comparison and difference analysis between SpringBoot and SpringMVC Comparison and difference analysis between SpringBoot and SpringMVC Dec 29, 2023 am 11:02 AM

SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

How to implement Springboot+Mybatis-plus without using SQL statements to add multiple tables How to implement Springboot+Mybatis-plus without using SQL statements to add multiple tables Jun 02, 2023 am 11:07 AM

When Springboot+Mybatis-plus does not use SQL statements to perform multi-table adding operations, the problems I encountered are decomposed by simulating thinking in the test environment: Create a BrandDTO object with parameters to simulate passing parameters to the background. We all know that it is extremely difficult to perform multi-table operations in Mybatis-plus. If you do not use tools such as Mybatis-plus-join, you can only configure the corresponding Mapper.xml file and configure The smelly and long ResultMap, and then write the corresponding sql statement. Although this method seems cumbersome, it is highly flexible and allows us to

How SpringBoot customizes Redis to implement cache serialization How SpringBoot customizes Redis to implement cache serialization Jun 03, 2023 am 11:32 AM

1. Customize RedisTemplate1.1, RedisAPI default serialization mechanism. The API-based Redis cache implementation uses the RedisTemplate template for data caching operations. Here, open the RedisTemplate class and view the source code information of the class. publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations, BeanClassLoaderAware{//Declare key, Various serialization methods of value, the initial value is empty @NullableprivateRedisSe

How to get the value in application.yml in springboot How to get the value in application.yml in springboot Jun 03, 2023 pm 06:43 PM

In projects, some configuration information is often needed. This information may have different configurations in the test environment and the production environment, and may need to be modified later based on actual business conditions. We cannot hard-code these configurations in the code. It is best to write them in the configuration file. For example, you can write this information in the application.yml file. So, how to get or use this address in the code? There are 2 methods. Method 1: We can get the value corresponding to the key in the configuration file (application.yml) through the ${key} annotated with @Value. This method is suitable for situations where there are relatively few microservices. Method 2: In actual projects, When business is complicated, logic

See all articles