权限soringboot-shiro

该博客主要介绍了如何在SpringBoot项目中集成Apache Shiro进行权限控制。配置了Shiro的相关bean,包括自定义Realm、安全Manager、过滤器工厂等,实现了登录验证、权限校验等功能。同时,提供了登录界面的前端代码示例。
摘要由CSDN通过智能技术生成

一、后台代码

①配置文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.slj</groupId>
    <artifactId>springboot-shior</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-shior</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring-boot-starter</artifactId>
            <version>1.7.0</version>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.3</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.21</version>
        </dependency>

    </dependencies>



</project>

②application.properties

③SpringbootShiroApplication

④shiro的配置类

package com.slj.springbootshior.config;

import com.slj.springbootshior.realm.MyRealm;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.DelegatingFilterProxy;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: springboot-shior
 * @description: shiro配置类
 * @author: 孙路军
 * @create: 2021-07-05 15:11
 **/
@Configuration
public class shiroConfig {
    //spring容器创建SecurityManager对象
    @Bean
    public DefaultWebSecurityManager securityManager(Realm realm){
        DefaultWebSecurityManager securityManager=new DefaultWebSecurityManager();
        securityManager.setRealm(realm);
        return securityManager;
    }

    //自定义realm类
    @Bean
    public Realm realm(CredentialsMatcher credentialsMatcher){
        MyRealm myRealm=new MyRealm();
        myRealm.setCredentialsMatcher(credentialsMatcher);//是指密码配置器
        return myRealm;
    }

    //创建一个密码匹配器
    @Bean
    public CredentialsMatcher credentialsMatcher(){
        HashedCredentialsMatcher credentialsMatcher=new HashedCredentialsMatcher();
        credentialsMatcher.setHashAlgorithmName("MD5");//指定加密方式
        credentialsMatcher.setHashIterations(1024);//加密的次数  1024
        return credentialsMatcher;
    }


    //shiro的过滤器工厂
    @Bean("shiroFilter")
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean=new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        shiroFilterFactoryBean.setLoginUrl("/toLogin");
        shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorized");


        Map<String,String> map=new HashMap<>();
        map.put("/login","anon");
        map.put("/**","authc");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        return shiroFilterFactoryBean;
    }

    //注入过滤器组件
    @Bean
    public FilterRegistrationBean<Filter> filter(){
        FilterRegistrationBean registrationBean=new FilterRegistrationBean();
        registrationBean.setName("shiroFilter");
        registrationBean.addUrlPatterns("/*");
        registrationBean.setFilter(new DelegatingFilterProxy());
        return registrationBean;
    }
}

⑤自定义realm类

package com.slj.springbootshior.realm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.slj.springbootshior.entry.Account;
import com.slj.springbootshior.mapper.UserMapper;
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.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @program: springboot-shior
 * @description: 自定义realm类
 * @author: 孙路军
 * @create: 2021-07-05 15:32
 **/
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserMapper userMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //得到账号
        String username = authenticationToken.getPrincipal().toString();

        //根据账号查询用户信息
        QueryWrapper wrapper =new QueryWrapper<>();
        wrapper.eq("username",username);
        Account account=userMapper.selectOne(wrapper);
        if(account!=null){
           ByteSource byteSource=ByteSource.Util.bytes(account.getSalt());

            SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(username,account.getPassword(),byteSource,this.getName());

            return info;
        }
        return null;
    }
}

⑥mapper

⑦entry实体类

⑧controller

二、前台代码

login登录界面的代码

<template>
    <div>
        <el-dialog
                title="提示"
                :visible.sync="insertDialogVisible"
                width="30%">
            <el-form  label-width="80px" :model="loginFrom" :rules="loginFormRules" ref="loginRef">
                <el-form-item label="账户"  prop="username">
                    <el-input  v-model="loginFrom.username" w></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="loginFrom.password" prop show-password></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
    <el-button @click="res">置空</el-button>
    <el-button type="primary" @click="confirmloginUser">确 定</el-button>
  </span>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        name: "login",
        data(){
            return {
                insertDialogVisible:true,
                //增加用户表单对象
                loginFrom:{},
                loginFormRules: {
                    password: [
                        {required: true, message: '密码不能为空', trigger: 'blur'}
                    ],
                    username:[
                        {required: true, message: '账户不能为空', trigger: 'blur'}
                    ]
                }
            }
        },
        methods:{
            res(){
                this.loginFrom={}
            },
            confirmloginUser(){
                var that=this;
                this.$refs.loginRef.validate((valid) => {
                    if (valid) {
                this.$http.post(`http://localhost:8003/login?username=${this.loginFrom.username}&password=${this.loginFrom.password}`).then(function(result){
                    console.log(result)
                      if(result.data=='登录成功'){
                            that.$message('登录成功');
                      }else{
                            that.$message('登录失败');
                      }
             })
              }
           });
            }
        }
    }
</script>

<style scoped>

</style>

③测试

无内容直接点击确定 触发校验

账户密码都正确

账户或密码不正确

震惊,又一个小细节   ,点击置空  会清空输入框内容

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值