zoukankan      html  css  js  c++  java
  • 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();
        }
  • 相关阅读:
    bzoj4010 [HNOI2015]菜肴制作
    PHP--------TP中的ajax请求
    二维数组去重
    手机号138-0013-8000格式存储
    spring4-2-bean配置-1-依赖注入
    spring4-1-Spring的简单介绍
    Result Grouping / Field Collapsing-结果分组
    vim自动补全
    vim配置-程序员【转】
    服务端程序设计和实现总结 【转】
  • 原文地址:https://www.cnblogs.com/rchao/p/10983355.html
Copyright © 2011-2022 走看看