其他分享
首页 > 其他分享> > shiro的使用

shiro的使用

作者:互联网

知识:

使用步骤

<dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.7.1</version>
</dependency>
public class UserRealm extends AuthorizingRealm {

    //授权与认证
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=>授权doGetAuthorizationInfo");
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了=>认证doGetAuthorizationInfo");

        //认证操作:用户名,密码
        String username="root";
        String password="123";

        UsernamePasswordToken userToken= (UsernamePasswordToken) token;
        if (!username.equals(userToken.getUsername())){
            return null;
        }

        //密码认证,shiro自己认证
        return new SimpleAuthenticationInfo("",password,"");
    }
}

认证操作

//授权信息配置
filterMap.put("/user/*","perms[user:add]");//表示一个user用户,有add权限
@Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了=>认证doGetAuthorizationInfo");

        //根据前端获取的用户名,密码,认证登陆
        User user = new User("root", "123", "12", "user:add");//模拟从数据库中获取用户信息
        String username="root";
        String password="123";

        //获取前端获取的用户和密码
        UsernamePasswordToken userToken= (UsernamePasswordToken) token;
        if (!username.equals(userToken.getUsername())){
            return null;
        }

        //登陆成功后,将user保存到session中
        Subject currentSubject = SecurityUtils.getSubject();
        Session session = currentSubject.getSession();
        session.setAttribute("username",user.getName());
        //密码认证,shiro自己认证
        return new SimpleAuthenticationInfo(user,password,"");
    }

 

标签:return,认证,user,使用,new,UserRealm,shiro
来源: https://www.cnblogs.com/youisme/p/14810489.html