快速掌握shiro安全框架(二)之springboot集成shiro

博客介绍了Spring Boot集成Shiro安全框架的步骤。包括在pom中添加依赖,创建realm文件夹及MyRealm.class文件,创建ShiroConfig配置类和LoginController.class,修改mysql表中密码,最后在浏览器输入特定链接验证集成是否成功。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、首先在pom中添加shiro所需jar包依赖

<!--shiro所需JAR包 -->
 <dependency>
     <groupId>org.apache.shiro</groupId>
     <artifactId>shiro-spring-boot-web-starter</artifactId>
     <version>1.9.0</version>
 </dependency>

2、在目录中创建realm文件夹,在文件夹中创建MyRealm.class文件

package com.wxg.springbootshiro.realm;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.wxg.springbootshiro.entity.User;
import com.wxg.springbootshiro.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
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;
import org.springframework.stereotype.Component;

@Component
public class MyRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    //自定义授权方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }
    //自定义登录认证方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1、获取用户登录名
        String name = authenticationToken.getPrincipal().toString();
        //2、查询数据库用户信息
        User one = userService.lambdaQuery().eq(User::getName, name).one();
        //3、非空判断,封装返回
        if(ObjectUtils.isNotEmpty(one)){
            //第一个参数为用户token信息,第二个参数为数据库密码,第三个为加盐信息,第四个为用户名信息
            SimpleAuthenticationInfo salt = new SimpleAuthenticationInfo(authenticationToken.getPrincipal(), one.getPwd(), ByteSource.Util.bytes("salt"), name);
            return salt;
        }
        return null;
    }
}

3、创建配置包config,在包中创建ShiroConfig配置类

package com.wxg.springbootshiro.config;

import com.wxg.springbootshiro.realm.MyRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class ShiroConfig {

    @Autowired
    MyRealm myRealm;

    @Bean
    public DefaultWebSecurityManager defaultSecurityManager(){
        //1.创建DefaultWebSecurityManager对象
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        //2.创建加密对象,设置参数
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
            //2.1设置md5加密
        hashedCredentialsMatcher.setHashAlgorithmName("md5");
            //2.2设置加密轮为三次
        hashedCredentialsMatcher.setHashIterations(3);
        //3.将加密对象加入到realm中
        myRealm.setCredentialsMatcher(hashedCredentialsMatcher);
        //4.将realm加入到DefaultWebSecurityManager对象
        defaultWebSecurityManager.setRealm(myRealm);
        //5.返回
        return defaultWebSecurityManager;
    }

    //配置 Shiro 内置过滤器拦截范围
    @Bean
    public DefaultShiroFilterChainDefinition
    shiroFilterChainDefinition(){
        DefaultShiroFilterChainDefinition definition = new
                DefaultShiroFilterChainDefinition();
        //设置不认证可以访问的资源

        definition.addPathDefinition("/myController/userLogin","anon");
        definition.addPathDefinition("/login","anon");
        //设置需要进行登录认证的拦截范围
        definition.addPathDefinition("/**","authc");
        return definition;
    }
}

4、创建一个登录控制器LoginController.class

package com.wxg.springbootshiro.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/myController")
public class LoginController {

    @GetMapping("/userLogin")
    @ResponseBody
    public String userLogin(String name,String pwd){
        //获取subject对象
        Subject subject=SecurityUtils.getSubject();
        //将用户信息封装到token请求中
        AuthenticationToken token = new UsernamePasswordToken(name,pwd);
        //登录
        try {
            subject.login(token);
            System.out.println("登录成功");
            return "登录成功!";
        } catch (AuthenticationException e) {
            e.printStackTrace();
            System.out.println("登录失败");
            return "登录失败!";
        }
    }
}

5、修改mysql表中张三的密码,密码根据以下代码生成

public static void main(String[] args) {
    //参数1为:要加密的字符串,参数2为:加密加盐的值,参数3为:加密遍历的次数
    Md5Hash simpleHash = new Md5Hash("z3", "salt", 3);
    //获取加密后的字符串
    String s = simpleHash.toHex().toString();
    System.out.println(s);
}

6、验证是否集成成功,在浏览器输入http://localhost:8080/myController/userLogin?name=张三&pwd=z3

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值