分享知识-快乐自己:注册用户密码加密、登录验证及权限验证

***********************以下内容仅作为参考使用:*********************************

1、用户注册时,将用户设置的密码加密后存入数据库中(显然密码不能简单地用md5加密一次或者干脆不加密,这些都是会暴露用户隐私的,甚至是触动用户的利益):

加密密码:

//生成盐(部分,需要存入数据库中)
String random=new SecureRandomNumberGenerator().nextBytes().toHex();
         
//将原始密码加盐(上面生成的盐),并且用md5算法加密三次,将最后结果存入数据库中
 String result = new Md5Hash("password",random,3).toString();

2、登录验证及权限验证(继承AuthorizingRealm,覆盖其中的方法):

@Component
public class MyRealM extends AuthorizingRealm {

    @Autowired
    private LoginService loginService;

    /**
     * 获取用户角色和权限,用于权限认证
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        String username = principals.getPrimaryPrincipal().toString();

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //获取角色(从数据库中取出时使用逗号分隔的)
        UserInfo user = loginService.getUserByName(username);
        String[] roleArray = user.getUserrole().split(",");

        Set<String> roles = new HashSet<String>();
        for (String roleid : roleArray) {
            roles.add(loginService.getRoles(roleid));
        }

        //获取权限(根据角色查询权限表)
        Set<String> permissions = new HashSet<String>();
        for (String roleid : roleArray) {
            permissions.addAll(loginService.getPermissions(roleid));
        }
        info.setRoles(roles);
        info.setStringPermissions(permissions);
        return info;
    }

    /**
     * 设置用户登录认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取输入的用户账号,并通过账号获取相关信息
        String username = token.getPrincipal().toString();
        UserInfo user = loginService.getUserByName(username);
        if (user != null) {
            //将查询到的用户账号和密码存放到 authenticationInfo用于后面的权限判断。第三个参数传入用户输入的用户名。
            SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getUsername(), user.getPwd(), getName());
            //设置盐,用来核对密码
            authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(user.getRandom()));
          
            return authenticationInfo;
        } else {
            return null;
        }
    }
}

3、shiro增加的配置:

  <!-- 配置自定义Realm,设定核对密码时在加盐后,要用MD5算法对用户输入的密码加密3次用于核对 -->
    <bean id="myRealM" class="com.test.shiro.MyRealM">
        <property name="credentialsMatcher" >
            <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
                <property name="hashAlgorithmName" value="MD5"></property>
                <property name="hashIterations" value="3"></property>
            </bean>
        </property>
    </bean>
<!-- 安全管理器 --> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm" ref="myRealM"/> </bean>
<!--Shiro过滤器--> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <!-- Shiro的核心安全接口,这个属性是必须的 --> <property name="securityManager" ref="securityManager"/> <!-- 身份认证失败,则跳转到登录页面的配置(首页加载页) --> <property name="loginUrl" value="/sourceA/pageA"/>

      <!--登陆成功页面-->
         <property name="successUrl" value="/list.jsp"/>

        <!-- 权限认证失败,则跳转到指定页面 -->
        <property name="unauthorizedUrl" value="/sourceA/error"/>
        <!-- Shiro连接约束配置,即过滤链的定义 -->
        <property name="filterChainDefinitions">
            <value>
                 <!--anon 表示匿名访问,不需要认证以及授权 -->
                /sourceB=anon
                 <!--authc表示需要认证,没有进行身份认证是不能进行访问的-->
                /sourceA*=authc
                 <!--roles[内容] 表示需要内容所示的角色才能访问该路径-->
                /sourceA=roles[user]
                 <!--perms[内容] 表示需要内容所示的权限才能访问该路径-->
                /sourceC/**=perms["sourceC"]
                /sourceD/**=authc,perms["sourceD"]
          <!--除定义的可以访问路径以外都需要进行认证-->
          /** = authc </value> </property> </bean>

4、登录,调用用户登录验证(权限及角色验证在用户访问某路径时进行拦截):

//用户信息bean      
UserInfo info = new UserInfo();
info.setPwd("password");
info.setUsername("username");

Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(info.getUsername(), info.getPwd());

try {

    //验证
    subject.login(token);
   
    //登陆成功后的处理逻辑:      
    System.out.println("登陆成功");
   
} catch (Exception e) {
    //登陆失败后的处理逻辑:
    System.out.println("用户名或密码错误");
   
}

5、登出

Subject subject = SecurityUtils.getSubject();
if (subject.isAuthenticated()) {
    subject.logout();
}

 点我可参考其他网址:

转载于:https://www.cnblogs.com/mlq2017/p/10158995.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值