Table of Contents
1. Knowledge you must know to use shiro
1. What is shiro?
2. Three commonly used core objects of shiro architecture
3. When used in springboot, it can be mainly regarded as two modules (request filtering module, authentication Authorization module)
2. Specific use
1. Write configuration class (config)
1.1. Shiro filter object (ShiroFilterFactoryBean)
1.2. Shiro security object (DefaultWebSecurity)
1.3. Create realm object (custom)
2. Create realm object
2.1. Customize realm class to inherit AuthorizingRealm class
2.2. Override the methods in AuthorizingRealm
Authorization:
3. Specific implementation
1. Realm implementation
2. Controller implementation
3. config Implementation
The above are some basic usages of shiro in springboot. I hope it will be helpful to everyone (the entities, roles, and permissions in the code can be replaced according to the results of your own database query).
Home Java javaTutorial How to quickly implement Shiro in springboot

How to quickly implement Shiro in springboot

May 11, 2023 pm 06:49 PM
springboot shiro

    1. Knowledge you must know to use shiro

    1. What is shiro?

    • 1. Apache Shiro is a Java security (permission) framework

    • 2. It can easily develop good enough applications, both It can be used in JavaEE or JavaSE

    • 3. Shiro can complete authentication, authorization, encryption, session management, web integration, caching, etc.

    2. Three commonly used core objects of shiro architecture

    • Subject: User

    • SecurityManager: Manage all users

    • Readim: Connection data

    3. When used in springboot, it can be mainly regarded as two modules (request filtering module, authentication Authorization module)

    1. Authentication and authorization module: The authentication and authorization module mainly includes two aspects, namely authentication and authorization. Authentication refers to determining the user's login status; authorization refers to obtaining the roles and permissions owned by the current user and handing them over to AuthoriztionInfo so that they can hand over relevant information to Shiro
    2. Request filtering module: Based on the permissions, roles and other information owned by the current user, it is judged whether it has the requested permission (that is, whether it can request the address currently being accessed). If the user has the permission to access the currently requested address, it will be allowed, otherwise it will be intercepted
    3. The above is the most basic implementation of permission authentication interception using the shiro framework. In addition, you can also learn according to your actual business situation by encrypting passwords, limiting login times (redis) and other functions. #4. Dependency

    <!--        后台拦截-->
            <dependency>
                <groupId>org.apache.shiro</groupId>
                <artifactId>shiro-spring</artifactId>
                <version>1.4.0</version>
            </dependency>
    Copy after login

    2. Specific use

    1. Write configuration class (config)

    1.1. Shiro filter object (ShiroFilterFactoryBean)

    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier(SecurityManager) DefaultWebSecurityManager securityManager){
       	ShiroFilterFactiryBean bean = new ShiroFilterFactoryBean()
    	//关联SecurityManager设置安全管理器	
     	bean.setSecurityManager(securityManager)
        
    	//添加内置过滤器
            /*
            	anon:无需过滤就可以访问
                authc:必须认证了才可访问(登录后才可访问)
                user:必须拥有"记住我"功能才可访问
                perms:拥有对某个资源的权限才可以访问
                role:拥有某个角色权限才可访问
            */
      	Map<String,String> filterMap = new LinkedHashMap<>();
        //拦截 
        //filterMap.put("页面地址","内置过滤器")
    	//filterMap.put("/user/name","anon")
    	//filterMap.put("/user/book","authc")
        
    	//具有user:add权限时才可以访问/user/name
        //perms中的“user:add”与数据库中对应权限要一致
        filterMap.put("/user/name","perms[user:add]")
        
    	//授权,正常情况下,没有授权会跳转到未授权页面
     	bean.setUnauthorizedUrl("未授权时跳转的页面")  
            
      	//创建一个过滤器链(其中内容通过Map存储)
     	bean.setFilterChainDefinitionMap(FilterMap); 
        //设置登录请求(登录的地址添加,当使用"authc"时,如果未登录,则跳转到登录页面)
        bean.setLoginUrl("/login")
    	return bean;
    }
    Copy after login
    1.2. Shiro security object (DefaultWebSecurity)
    //@Qualifier:引入bena对象
    @Bean(name="SecurityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("MyRealm") MyRealm myRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurotyManager();
        //关联MyRealm
        securityManager.setRealm(myRealm);
        return securityManager;
    }
    Copy after login
    1.3. Create realm object (custom)
    //将自定义的realm对象交给spring
    //@Bean(name="MyRealm")中name属性不加默认名称为方法名
    @Bean(name="MyRealm")
    public MyRealm MyRealm(){
     	return new MyRealm();
    }
    Copy after login
    2. Create realm object

    2.1. Customize realm class to inherit AuthorizingRealm class

    class MyRealm extends AuthorizingRealm
    Copy after login
    2.2. Override the methods in AuthorizingRealm
    Authorization:
    project AthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals){
        //1、权限信息对象info,用来存放查出的用户的所有的角色(role)及权限(permission)
     	SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //2、拿到当前登录的对象信息,通过认证方法SimpleAuthenticationInfo(第一个参数)已经进行存入 
        User user =(user)SecurityUtils.getSubject().getPrincipal();
        //3、将该对象的角色信息进行存入
        // 赋予角色
    	List<Role> roleList = roleService.listRolesByUserId(userId);
    	for (Role role : roleList) {
    		info.addRole(role.getName());
    	}
        //4、设置该用户的权限
        infO.addStringPermission(user.getPerms())
        //5、将该对象的权限信息进行存入(permissionSet一个权限信息的集合)
        info.setStringPermissions(permissionSet);
        return info;
    }
    Copy after login

    Authentication:

    project AuthenticationInfo doGetAuthorizationInfo(AuthenticationToken token){
        //1、拿到用户登陆的信息
        UsernamePasswordToken userToken =(UsernamePasswordToken) token;
        //2、通过用户名(userToken.getUsername)获取数据库中的对象user
        //如果获取对象user为空则该用户不从在,返回return null(抛出用户不存在异常)
        if (user == null) {
                throw new UnknownAccountException("账号不存在!");
            	//或直接 return null;
            }
        //3、密码认证,有shiro完成(AuthenticationInfo是一个接口,SimpleAuthenticationInfo是其接口的实现类)
        //也可对密码进行加密 如MD5 MD5盐值
        return new SimpleAuthenticationInfo("用户对象信息(user)","通过用户从数据库中获得的用户密码(user.password)","")
    }
    Copy after login

    3. Pass in the logged in user information ( Obtain the login request information through the controller)

    //获取当前用户
    Subject subject = SecurityUtils.getSubject();
    //封装用户的登录数据(username:用户登陆时传入的账号;password:用户登陆时传入的密码)
    UsernamePasswordToken token = new UsernamePasswordToken(username,password);
    //执行登录(如果有异常则登录失败,没有异常则登录成功,在Shiro中已经为我们封装了登录相关的异常,直接使用即可)
    try{
        subject.login(token);//执行登录成功后
        return "首页"
    }catch(UnknowAccountException e){//用户名不存在
        return "login"
    }catch(IncorrectCredentialsException e){//密码不存在
        return "login"
    }
    注意:该方法中登录失败后返回的是跳转的页面,故不可用@ResponseBody
    Copy after login

    3. Specific implementation

    1. Realm implementation

    package com.lingmeng.shiro;
     
    import com.lingmeng.pojo.entity.Admin;
    import com.lingmeng.pojo.entity.Permission;
    import com.lingmeng.pojo.entity.Role;
    import com.lingmeng.pojo.resp.BaseResp;
    import com.lingmeng.service.AdminService;
    import com.lingmeng.service.RoleService;
    import org.apache.shiro.SecurityUtils;
    import org.apache.shiro.authc.*;
    import org.apache.shiro.authz.AuthorizationInfo;
    import org.apache.shiro.authz.SimpleAuthorizationInfo;
    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;
     
    import java.util.HashSet;
    import java.util.Set;
     
    public class MyRealm extends AuthorizingRealm {
     
        @Autowired
        RoleService roleService;
     
        @Autowired
        AdminService adminService;
     
        //授权
        @Override
        protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            //获取用户信息
            Subject subject = SecurityUtils.getSubject();
            Admin admin =(Admin) subject.getPrincipal();
            //获取用户的权限及角色信息
            BaseResp baseResp = roleService.selectOne(admin.getUsername());
            Role role = (Role) baseResp.getData();
            //将获取的角色及权限进行存入
            if (role!=null){
                //角色存入
                info.addRole(role.getName());
                //权限信息进行存入
                Set<String> perms = new HashSet<>();
                for (Permission perm : role.getPerms()) {
                    perms.add(perm.getUrl());
                }
                info.setStringPermissions(perms);
            }
            return info;
        }
     
        //认证
        @Override
        protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
            //获取登录信息(登录的账号)
            String username =(String)authenticationToken.getPrincipal();
    //      UsernamePasswordToken userToken =(UsernamePasswordToken) authenticationToken;拿到登录时传入的账号和密码对象
            //从数据库中查询该对象的信息
            Admin admin = adminService.selectOne(username);
            if (admin==null){
                throw new UnknownAccountException("账号不存在");
            }
            return new SimpleAuthenticationInfo(admin,admin.getPassword(),this.getName());
        }
    }
    Copy after login

    2. Controller implementation

    package com.lingmeng.controller;
     
    import com.lingmeng.pojo.entity.Admin;
    import com.lingmeng.pojo.resp.BaseResp;
    import org.apache.shiro.SecurityUtils;
    import org.apache.shiro.authc.IncorrectCredentialsException;
    import org.apache.shiro.authc.UnknownAccountException;
    import org.apache.shiro.authc.UsernamePasswordToken;
    import org.apache.shiro.subject.Subject;
    import org.springframework.web.bind.annotation.*;
     
    @RestController
    public class AdminController {
     
        @PostMapping("background/login")
        public BaseResp  login(@RequestBody Admin admin){
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(admin.getUsername(), admin.getPassword());
            try{
                subject.login(token);
                return BaseResp.SUCCESS("登录成功",null,null);
            }catch (UnknownAccountException e){//账号不存在
                return BaseResp.FAIL(201,"账号不存在");
            }catch(IncorrectCredentialsException incorrectCredentialsException){//密码错误
                return BaseResp.FAIL(201,"密码错误") ;
            }
        }
     
        @GetMapping("/background/exitLogin")
        public BaseResp exitLogin(){
            Subject subject = SecurityUtils.getSubject();
            System.out.println(subject.getPrincipal());
            try{
                subject.logout();//退出登录
                return BaseResp.SUCCESS("退出登录",null,null);
            }catch(Exception e){
                return BaseResp.FAIL(202,"退出失败");
            }
        }
    }
    Copy after login

    3. config Implementation

    package com.lingmeng.config;
     
    import com.lingmeng.shiro.MyRealm;
    import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
    import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
     
    import java.util.LinkedHashMap;
    import java.util.Map;
    @Configuration
    public class ShiroConfig {
     
        @Bean
        public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager){
            ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
            bean.setSecurityManager(securityManager);
            //配置请求拦截并存入map中
             /*
            	anon:无需过滤就可以访问
                authc:必须认证了才可访问(登录后才可访问)
                user:必须拥有"记住我"功能才可访问
                perms:拥有对某个资源的权限才可以访问
                role:拥有某个角色权限才可访问
            */
            Map<String, String> map = new LinkedHashMap<>();
            map.put("/background/**","authc");
            map.put("background/login","anon");
     
     
            bean.setFilterChainDefinitionMap(map);
            //设置未授权跳转地址
            bean.setUnauthorizedUrl("");
            //设置登录地址
            bean.setLoginUrl("/background/login");
            return bean;
        }
     
        @Bean("securityManager")
        public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("myRealm") MyRealm myRealm){
            return new DefaultWebSecurityManager(myRealm);
        }
     
        @Bean()
        public MyRealm myRealm(){
            return new MyRealm();
        }
    }
    Copy after login

    The above are some basic usages of shiro in springboot. I hope it will be helpful to everyone (the entities, roles, and permissions in the code can be replaced according to the results of your own database query).

    The above is the detailed content of How to quickly implement Shiro in springboot. 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)
    2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    Repo: How To Revive Teammates
    4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    Hello Kitty Island Adventure: How To Get Giant Seeds
    4 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 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 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 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 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 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 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