Table of Contents
1.shiro security framework
1.1 What is permission management
1.2 What is identity authentication
1.3 What is authorization
1.4 What are the authentication and authorization frameworks
2. Use shiro to complete the authentication work
2.1 Key objects of authentication in shiro
2.2 Authentication process
2.3 Project code
2.3.1 Dependencies
2.3.2 Create ini file
2.3.3 Test code
2.4 Principle of authentication
3. Authorization
3.1 Modify the ini file
3.2 Modify the code
Home Java javaTutorial How to use Java shiro security framework

How to use Java shiro security framework

May 03, 2023 am 11:22 AM
java shiro

    1.shiro security framework

    Apache Shiro is a powerful and easy-to-use Java security framework that provides authentication, authorization, With functions such as encryption and session management, Shiro can provide comprehensive security management services for any application. And compared to other security frameworks, spring security, Shiro is much simpler.

    Shiro is an open source framework under Apache. It extracts the security authentication-related functions of the software system to implement user identity authentication, permission authorization, encryption, session management and other functions, forming a universal security authentication framework. .

    Shiro can easily develop good enough applications, which can be used not only in the JavaSE environment, but also in the JavaEE environment. Shiro can help us complete: authentication, authorization, encryption, session management, integration with the Web, caching, etc.

    1.1 What is permission management

    Basically, systems involving user participation must carry out permission management. Permission management belongs to the category of system security. Permission management realizes the control of user access to the system. According to Security rules or security policies control that users can access and only access the resources they are authorized to access.

    Permission management includes two parts: user identity authentication and authorization, referred to as authentication and authorization. For resources that require access control, users must first undergo identity authentication. After passing the authentication, the user can access the resource only after passing the authentication.

    1.2 What is identity authentication

    Identity authentication is the process of determining whether a user is a legitimate user. The most commonly used simple identity authentication method is for the system to determine whether the user's identity is correct by checking the user name and password entered by the user to see if they are consistent with the user's user name and password stored in the system. For systems that use fingerprints and other systems, you need to show your fingerprint; for card swiping systems such as hardware keys, you need to swipe your card.

    1.3 What is authorization

    Authorization, that is, access control, controls who can access which resources. After identity authentication, the subject needs to be assigned permissions to access system resources. Some resources cannot be accessed without permissions.

    1.4 What are the authentication and authorization frameworks

    shiro framework and spring security framework This framework is quite popular on the market now.

    2. Use shiro to complete the authentication work

    2.1 Key objects of authentication in shiro

    Subject: The user whose subject accesses the system. The subject can be a user, program, etc., for authentication are called subjects;

    Principal: Identity information----The account number is the identification of the subject for identity authentication. The identification must be unique, such as user name, mobile phone number, email address, etc., an A subject can have multiple identities, but there must be one primary identity (Primary Principal).

    credential: Credential information---Password is security information that only the subject knows, such as passwords, certificates, etc.

    2.2 Authentication process

    How to use Java shiro security framework

    2.3 Project code

    1. No database is needed for identity authentication first, --our ini file, window System file, which can store account numbers and passwords.

    (1) Create a maven java project

    2.3.1 Dependencies
     <dependency>
                <groupId>org.apache.shiro</groupId>
                <artifactId>shiro-core</artifactId>
                <version>1.9.0</version>
            </dependency>
    Copy after login
    2.3.2 Create ini file

    How to use Java shiro security framework

    2.3.3 Test code
    public class Test01 {
        public static void main(String[] args) {
            //1.获取SecurityManager对象
            DefaultSecurityManager securityManager=new DefaultSecurityManager();
            //2.读取ini文件
            IniRealm iniRealm=new IniRealm("classpath:shiro.ini");
            //3。设置securityManager的realm
            securityManager.setRealm(iniRealm);
            //4.设置securityManager上下文生效
            SecurityUtils.setSecurityManager(securityManager);
            //5.获取subject的主体对象
            Subject subject=SecurityUtils.getSubject();
            try{
                //UsernamePasswordToken作用是封装你输入的账号和密码 是客户自己输入的 用来进行比较与realm
                UsernamePasswordToken token=new UsernamePasswordToken("admin","123456");
                //抛出异常 比对shiro中realm和自己的对比,如果一致则登录成功,不一致则登录失败
                subject.login(token);
                System.out.println("登陆成功");
            }catch(Exception e){
                e.printStackTrace();
                System.out.println("登陆失败");
            }
        }
    }
    Copy after login

    2.4 Principle of authentication

    How to use Java shiro security framework

    Subject: Subject login information is submitted to SecurityManager --->Authenticator- --->Perform relevant authentication based on the data provided by your realm. realm---a class that interacts with data sources.

    3. Authorization

    How to use Java shiro security framework

    How to use Java shiro security framework

    3.1 Modify the ini file

    How to use Java shiro security framework

    3.2 Modify the code

    public class Test01 {
        public static void main(String[] args) {
            //1.获取SecurityManager对象
            DefaultSecurityManager securityManager=new DefaultSecurityManager();
            //2.读取ini文件
            IniRealm iniRealm=new IniRealm("classpath:shiro.ini");
            //3。设置securityManager的realm
            securityManager.setRealm(iniRealm);
            //4.设置securityManager上下文生效
            SecurityUtils.setSecurityManager(securityManager);
            //5.获取subject的主体对象
            Subject subject=SecurityUtils.getSubject();
            try{
                //UsernamePasswordToken作用是封装你输入的账号和密码 是客户自己输入的 用来进行比较与realm
                UsernamePasswordToken token=new UsernamePasswordToken("admin","123456");
                //抛出异常 比对shiro中realm和自己的对比,如果一致则登录成功,不一致则登录失败
                subject.login(token);
                System.out.println("登陆成功");
            }catch(Exception e){
                e.printStackTrace();
                System.out.println("登陆失败");
            }
            System.out.println("=========================登陆后===========================");
            boolean authenticated = subject.isAuthenticated();
            if(authenticated){
                //判断当前登录者是否具有user:query权限
                boolean permitted = subject.isPermitted("user:update");
                System.out.println(permitted);
                //从角色角度
                boolean role1 = subject.hasRole("role1");
                System.out.println(role1);
            }else {
                System.out.println("请先认证");
            }
        }
    }
    Copy after login

    The above is the detailed content of How to use Java shiro security framework. 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

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Article

    Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    Nordhold: Fusion System, Explained
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
    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)

    Hot Topics

    Java Tutorial
    1666
    14
    PHP Tutorial
    1273
    29
    C# Tutorial
    1252
    24
    Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

    Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

    PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

    PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

    PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

    PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

    PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

    PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

    PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

    PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

    PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

    PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

    PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

    The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

    PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 17, 2025 am 12:23 AM

    PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

    See all articles