• springboot 简单使用shiro登录


    首先引入需要的pom

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

     配置application.properties

    #登录界面
    shiro.loginUrl=/login 
    #无权限界面
    shiro.unauthorizedUrl=/403
    #成功界面
    shiro.successUrl=/index

    自定义UserRealm

    public class UserRealm extends AuthorizingRealm {
    
        @Autowired
        private UserService userService;
    
        @Override
        protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
            if(principalCollection == null){
                throw new AuthenticationException("PrincipalCollection参数不能为空。");
            }
            TUser user = (TUser) getAvailablePrincipal(principalCollection);
            if(ObjectUtils.isEmpty(user)){
                throw new AuthenticationException("用户不存在");
            }
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            if(ObjectUtils.isEmpty(user.getRole())){
                info.setRoles(new HashSet<String>(){{add("public");}});
            }else{
                info.setRoles(new HashSet<String>(){{add(user.getRole());}});
            }
            return info;
        }
    
        @Override
        protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
            UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
            String username = token.getUsername();
            if(StringUtils.isEmpty(username)){
                throw new UnknownAccountException();
            }
            TUser user = userService.fetchByUsername(username);
            if(ObjectUtils.isEmpty(user)){
                throw new UnknownAccountException();
            }
    
            if(user.getDisabled()){
                throw new LockedAccountException();
            }
    
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,user.getPassword(),ByteSource.Util.bytes(user.getSalt()),getName());
            return info;
        }
    }

    添加用户时密码加密方法

    public String md5(String password,String salt){
            //加密方式
            String algorithmName = "MD5";
            //盐值
            ByteSource byteSalt = ByteSource.Util.bytes(salt);
            //加密次数
            int hashIterations = 6;
            SimpleHash result = new SimpleHash(algorithmName, password, byteSalt, hashIterations);
            //Md2Hash Md5Hash Sha1Hash Sha256Hash Sha384Hash Sha512Hash 最后都是调用SimpleHash加密
            //Md5Hash r = new Md5Hash(password,byteSalt,hashIterations);
            return result.toHex();
    }
    配置 ShiroConfig
    @Configuration
    public class ShiroConfig {
    
        @Bean
        public Realm realm(){
            UserRealm userRealm = new UserRealm();
            userRealm.setCredentialsMatcher(hashedCredentialsMatcher());
            return userRealm;
        }
        /**
          *  配置url
          *  anon 任何人都能访问
          *  authc 认证成功后才能访问
          */
        @Bean
        public ShiroFilterChainDefinition shiroFilterChainDefinition(){
            DefaultShiroFilterChainDefinition chain = new DefaultShiroFilterChainDefinition();
            Map<String,String> pathDefinitions = new HashMap<>();
            pathDefinitions.put("/loginDo","anon");
            pathDefinitions.put("/**","authc");
            chain.addPathDefinitions(pathDefinitions);
            return chain;
        }
    
    
        /**
         * 密码验证
         * @return
         */
        @Bean
        public HashedCredentialsMatcher hashedCredentialsMatcher(){
            HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
            credentialsMatcher.setHashAlgorithmName("MD5");
            credentialsMatcher.setHashIterations(6);
            credentialsMatcher.setStoredCredentialsHexEncoded(true);
            return credentialsMatcher;
        }
    
    }

    登录controller

        @PostMapping("/loginDo")
        @ResponseBody
        public Result loginDo(String username, String password, boolean rememberMe) {
            if(StringUtils.isEmpty(username)){
                return Result.error("请输入用户名");
            }
    
            if(StringUtils.isEmpty(password)){
                return Result.error("请输入密码");
            }
            try {
                Subject subject = SecurityUtils.getSubject();
                subject.login(new UsernamePasswordToken(username, password, rememberMe));
            } catch (UnknownAccountException e1) {
                return Result.error("用户名或密码错误");
            } catch (LockedAccountException e2) {
                return Result.error("用户已被锁定");
            } catch (AuthenticationException e3) {
                return Result.error("登录失败");
            }
            return Result.success();
        }
  • 相关阅读:
    PowerDesigner学习 ---- 系列文章
    PowerDesigner基础使用 ---- 入门学习
    PowerDesigner ---- 数据库设计(概念模型CDM和物理模型PDM)
    PowerDesigner V16.5 安装及汉化
    在树莓派是安装并配置NTP服务
    RESTful Web API 理解
    Linux或树莓派3——挂载U盘、移动硬盘并设置rwx权限
    开启树莓派自带的VNC功能
    c#代码获取web.config配置文件里面设置的 <compilation debug="true"节点
    WebService的web客户端同步、异步、多线程向服务端传入参数的数据交互方式
  • 原文地址:https://www.cnblogs.com/rchao/p/10983355.html
Copyright © 2020-2023  润新知