springboot整合shiro

该博客介绍了如何在SpringBoot项目中整合Shiro进行权限管理。配置包括引入Shiro依赖、创建Shiro配置类、自定义Realm以及登录控制层。在ShiroConfig中设置了SecurityManager、Realm和过滤器链,自定义Realm实现了用户认证逻辑,登录控制器处理用户登录请求。通过这个配置,实现了基于MD5的密码验证和登录功能。
摘要由CSDN通过智能技术生成

1.首先引入shiro和springboot整合的依赖:

2.书写shiro配置类
package com.springbootshiro.shiro1.config;

import com.springbootshiro.shiro1.realm.MyRealm;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.crypto.hash.Md5Hash;
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 sun.security.provider.MD5;
import javax.servlet.Filter;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    //1.spring容器创建SecurityManager对象
    @Bean
    public DefaultWebSecurityManager securityManager(Realm realm){
        //创建一个SecurityManager对象
        DefaultWebSecurityManager securityManager=new DefaultWebSecurityManager();
        securityManager.setRealm(realm);//自定义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");//指定加密方式  MD5
        credentialsMatcher.setHashIterations(1024);//加密的次数 1024
        return credentialsMatcher;
    }

    //shiro的过滤器工厂
    @Bean("shiroFilter")
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean=new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        shiroFilterFactoryBean.setLoginUrl("/login");
        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;
    }
}

3.书写自定义Realm

package com.springbootshiro.shiro1.realm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.springbootshiro.shiro1.entry.Account;
import com.springbootshiro.shiro1.mapper.UserMapper;
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;

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<Account> 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;
    }
}

4.登录控制层
package com.springbootshiro.shiro1.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@CrossOrigin
public class LoginController {
    @PostMapping("login")
    public String login(String username,String password){
        Subject subject= SecurityUtils.getSubject();
        UsernamePasswordToken token=new UsernamePasswordToken(username,password);
        try{
            subject.login(token);
            return "登陆成功";
        }catch (Exception e){
            return "登录失败";
        }
    }

    @GetMapping("toLogin")
    public String toLogin(){
        return "请先登录";
    }

    public static void main(String[] args) {
        Md5Hash md5Hash=new Md5Hash("123456","yjq",1024);
        System.out.println(md5Hash);
    }
}

简单测试了springboot-shiro的登录,结果如下:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值