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
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>
2.3.2 Create ini file
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("登陆失败"); } } }
2.4 Principle of authentication
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
3.1 Modify the ini file
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("请先认证"); } } }
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!

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

JavaisnotentirelyplatformindependentduetoJVMvariationsandnativecodeintegration,butitlargelyupholdsitsWORApromise.1)JavacompilestobytecoderunbytheJVM,allowingcross-platformexecution.2)However,eachplatformrequiresaspecificJVM,anddifferencesinJVMimpleme

TheJavaVirtualMachine(JVM)isanabstractcomputingmachinecrucialforJavaexecutionasitrunsJavabytecode,enablingthe"writeonce,runanywhere"capability.TheJVM'skeycomponentsinclude:1)ClassLoader,whichloads,links,andinitializesclasses;2)RuntimeDataAr

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

The five major features of Java are polymorphism, Lambda expressions, StreamsAPI, generics and exception handling. 1. Polymorphism allows objects of different classes to be used as objects of common base classes. 2. Lambda expressions make the code more concise, especially suitable for handling collections and streams. 3.StreamsAPI efficiently processes large data sets and supports declarative operations. 4. Generics provide type safety and reusability, and type errors are caught during compilation. 5. Exception handling helps handle errors elegantly and write reliable software.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6
Visual web development tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Mac version
God-level code editing software (SublimeText3)
