SpringBoot集成 Shiro

备份自用

  1. pom.xml
        <!--        shiro-->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.3.2</version>
        </dependency>
  1. ShiroConfig
package com.school.service.config;

import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Shiro配置类
 */
@Configuration
public class ShiroConfig {

    @Bean(name = "shiroFilter")
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        shiroFilterFactoryBean.setLoginUrl("/school/goToLogin");//设置登录页面
        shiroFilterFactoryBean.setUnauthorizedUrl("/school/goToLogin");//权限不足跳转页面,这个在Default过滤器中设置无效,具体看 https://blog.csdn.net/bicheng4769/article/details/86680955
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
        // <!-- authc:所有url都必须认证通过才可以访问; anon:所有url都都可以匿名访问-->
        filterChainDefinitionMap.put("/service/school/**", "anon");
        filterChainDefinitionMap.put("/swagger-ui.html", "anon");
        filterChainDefinitionMap.put("/swagger-resources", "anon");
        filterChainDefinitionMap.put("/v2/api-docs", "anon");
        filterChainDefinitionMap.put("/webjars/springfox-swagger-ui/**", "anon");
        filterChainDefinitionMap.put("/configuration/security", "anon");
        filterChainDefinitionMap.put("/configuration/ui", "anon");

        filterChainDefinitionMap.put("/service/article/**", "authc");
        filterChainDefinitionMap.put("/service/chat/**", "authc");
        filterChainDefinitionMap.put("/service/diary/**", "authc");
        filterChainDefinitionMap.put("/service/file/**", "authc");
        filterChainDefinitionMap.put("/service/problem/**", "authc");
        filterChainDefinitionMap.put("/service/team-article/**", "authc");
        filterChainDefinitionMap.put("/service/team/**", "authc");
        filterChainDefinitionMap.put("/service/user/**", "authc");
        filterChainDefinitionMap.put("/service/user-friend/**", "authc");
        filterChainDefinitionMap.put("/service/user-info/**", "authc");
        filterChainDefinitionMap.put("/service/widget/**", "authc");

        //主要这行代码必须放在所有权限设置的最后,不然会导致所有 url 都被拦截 剩余的都需要认证
        filterChainDefinitionMap.put("/**", "anon");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactoryBean;
    }

    @Bean
    public SecurityManager securityManager(){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(myRealm());
        return defaultWebSecurityManager;
    }

    @Bean
    public MyRealm myRealm (){
        MyRealm myRealm = new MyRealm();
        return myRealm;
    }


}
  1. 自定义Realm
package com.school.service.config;

import com.school.service.entity.User;
import com.school.service.service.IUserService;
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.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

/**
 * 自定义Realm
 */
public class MyRealm extends AuthorizingRealm {

    @Autowired
    IUserService userService;

    @Override //权限认证,发放权限
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Set<String> stringSet = new HashSet<>();
        stringSet.add("user:show");
        stringSet.add("user:admin");
        info.setStringPermissions(stringSet);
        return info;
    }

    @Override //身份认证,验证登录
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("-------身份认证方法--------");
        String userCode = (String) authenticationToken.getPrincipal();
        String userPwd = new String((char[]) authenticationToken.getCredentials());
        //根据用户名从数据库获取密码
        User user = userService.getByUserCode(userCode);
        String password = null;
        if (user != null)
            password = user.getPassword();
        if (userCode == null || user == null) {
            throw new AccountException("用户名不正确");
        } else if (!userPwd.equals(password )) {
            throw new AccountException("密码不正确");
        }
        return new SimpleAuthenticationInfo(userCode, password,getName());
    }
}
  1. 注册时密码加盐加密

注册的时候将密码加密存储到数据库。

/**
     * 获取加密密码
     * @param password
     * @return
     */
    private static String hashAlgorithmName = "MD5"; //加密方式
    private static final int hashIterations = 2; //加密的次数
    private static final String salt = new SecureRandomNumberGenerator().nextBytes().toHex(); //盐
//  private static final String salt = "6LCi5pmo5ZWK";
    public static String getMD5Passwoed(String password){
        //加密
        SimpleHash simpleHash = new SimpleHash(hashAlgorithmName, password, salt, hashIterations);
        return simpleHash.toString();
    }

登录时

String getPassword = getMD5Passwoed(password);
// 在认证提交前准备 token(令牌)
UsernamePasswordToken token = new UsernamePasswordToken(userCode, getPassword);

注册时

String encryptionPassword = getMD5Passwoed(password);//获取加密密码
//保存到数据库
posted @ 2021-11-15 20:45  两小无猜  阅读(64)  评论(0编辑  收藏  举报