8-6Shiro安全验证

本文介绍了Apache Shiro,一个轻量级的安全框架,用于实现身份验证、授权、密码加密和会话管理。文章详细讲解了Shiro与Spring的集成,以及Authentication和Authorizing的核心概念,并提供了配置和 Realm 自定义的实践指导。
摘要由CSDN通过智能技术生成

1. 课程介绍
1. Shiro简介;(了解)
2. Shiro入门;(了解)
3. Shrio集成Spring;(掌握)
4. Authentication身份认证;(掌握)
5. Authorizing授权;(掌握)

一,shiro

Apache Shiro是一个强大且易用的架,有身份验证、授权、密码学和会话管理。使用Shiro的易于理解的API,您可以快速、轻松地获得任何应用程序,从最小的移动应用程序到最大的网络和企业应用程序。
Spring security 重量级安全框架Java安全框
Apache Shiro轻量级安全框架
Shiro:是一个apache的安全框架,还有spring security;
Shiro:能做:身份认证(登录)authentication,授权authorization,密码学,会话管理。
应用–》Subject(当前用户)—》Security Mananger管理–》Realm----》db
导入jar

<dependencies>
    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-core</artifactId>
        <version>1.4.0</version>
    </dependency>
    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
</dependencies>
[users]
# 用户 'root' 密码是 'secret' and the 'admin' 角色
root = secret, admin
# 用户 'guest' 密码 'guest' 和'guest'角色
guest = guest, guest
# user 'presidentskroob' with password '12345' ("That's the same combination on
# my luggage!!!" ;)), and role 'president'
presidentskroob = 12345, president
# 用户 'darkhelmet' with password 'ludicrousspeed' and 角色 'darklord' and 'schwartz'
darkhelmet = 123, darklord, schwartz
# 用户 'lonestarr' 密码 'vespa' and roles 'goodguy' and 'schwartz'
lonestarr = vespa, goodguy, schwartz

[roles]
# 'admin' role has all permissions, indicated by the wildcard '*'
admin = *
# 这个 'schwartz' 角色 能干lightsaber下面的所有事情:
schwartz = lightsaber:*
# goodguy这个角色 能干winnebago下面的drive权限,操作eagle5这个资源 user:delete:5
goodguy = winnebago:drive:eagle5

测试

 @Test
    public void test() throws Exception{
        //填入路径到工厂对象中去
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        //得到SecutiryManager 核心对象
        SecurityManager securityManager = factory.getInstance();
        //设置到shiro环境中去
        SecurityUtils.setSecurityManager(securityManager);
        //获得主体
        Subject subject = SecurityUtils.getSubject();
        //创建令牌
        UsernamePasswordToken token = new UsernamePasswordToken("darkhelmet", "123");
        try {
            subject.login(token);
            System.out.println("登陆成功");
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("该账号不存在");
        }catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            System.out.println("密码错误");
        }catch (AuthenticationException e) {
            e.printStackTrace();
            System.out.println("其他认证错误");
        }
        //角色判断
        if (subject.hasRole("admin")){
            System.out.println("这个角色有admin");
        }else{
            System.out.println("没有该角色");
        }
        //权限判断
        if (subject.isPermitted("lightsaber:*")){
            System.out.println("该角色有lightsaber权限");
        }else{
            System.out.println("没有权限");
        }
    }

自定义Realm

public class MyRealm extends AuthorizingRealm {
    //授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //得到用户名
        String primaryPrincipal = (String) principalCollection.getPrimaryPrincipal();
        //拿到权限去数据库查询
        Set<String> role = getRoleByPrincipal(primaryPrincipal);
        //拿到角色去数据库查询
        Set<String> permission = getPermissionByPrincipal(primaryPrincipal);


        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        //设置角色
        simpleAuthorizationInfo.setRoles(role);
        //设置权限
        simpleAuthorizationInfo.setStringPermissions(permission);

        return simpleAuthorizationInfo;
    }

    //通过用户拿到角色
    private Set<String> getRoleByPrincipal(String primaryPrincipal){
        Set<String> roles = new HashSet<String>();
        if("gongji".equals(primaryPrincipal)){
            roles.add("admin");
            return roles;
        }else{
            return null;
        }
    }
    //通过用户获取权限
    private Set<String> getPermissionByPrincipal(String primaryPrincipal){
        Set<String> permissions = new HashSet<String>();
        if("gongji".equals(primaryPrincipal)){
            permissions.add("admin");
            return permissions;
        }else{
            return null;
        }
    }

    //身份认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //得到令牌
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //主体
        Object principal = token.getPrincipal();
        System.out.println(principal);

        //获取用户名 zhangsan
        String username = token.getUsername();
        System.out.println(username);

        //通过用户名 去数据库查询数据 -- 查询用户的信息
        // 没有加密返回 String dbpwd= getPwdByUsername(username);
        String md5Pwd = getMD5PwdByUsername(username);
        //处理用户名问题 用户名是否存在的问题
        if(md5Pwd==null){
            //用户不存在
            return null;
        }
        //ByteSource
        ByteSource salt = ByteSource.Util.bytes("itsource");
        //下面进行密码的比对  shiro 底层它会自动进行比对 -- 处理密码问题
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username, md5Pwd,salt, getName());

        return simpleAuthenticationInfo;
    }

    //通过用户名去拿到密码
    public String getPwdByUsername(String username){
        if("gongji".equals(username)){
            return "123";
        }else{
            return null;
        }
    }
    //加密返回密码
    public String getMD5PwdByUsername(String username){
        if("gongji".equals(username)){
            return "d5a3fedf6c59c2ecbe7f7a6c1a22da37";
        }else{
            return null;
        }
    }

    public static void main(String[] args) {
        //MD5 本身是不可破解 ..不可逆  网上看到破解方式 都是穷举把
        //(1)普通加密+202cb962ac59075b964b07152d234b70 -123
        SimpleHash simpleHash = new SimpleHash("MD5","123" );
        //(2)加密+加次数
        SimpleHash simpleHash1 = new SimpleHash("MD5","123",null,10 );
        //5371007260db2b98e3f7402395c45f28
        //(3)加密123 加盐 + itsource +加次数 --d5a3fedf6c59c2ecbe7f7a6c1a22da37 -- 最安全
        SimpleHash simpleHash2 = new SimpleHash("MD5","123","itsource",10 );
        System.out.println(simpleHash.toString());
        System.out.println(simpleHash1.toString());
        System.out.println(simpleHash2.toString());
    }
}

Shiro中密码加密

 @Test
    public void testDiyRealm() throws Exception{

        //创建自定义myRealm
        MyRealm myRealm  = new MyRealm();
        //得到SecutiryManager 核心对象
        DefaultSecurityManager securityManager = new DefaultSecurityManager();
        securityManager.setRealm(myRealm);
        //设置到shiro的环境里面 才能运行
        SecurityUtils.setSecurityManager(securityManager);
        //密码匹配器
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashAlgorithmName("MD5");
        matcher.setHashIterations(10);
        //在realm设置匹配器
        myRealm.setCredentialsMatcher(matcher);

        //完成一些认证 拿到主体 -- 游客
        Subject subject = SecurityUtils.getSubject();

        //创建令牌
        UsernamePasswordToken token = new UsernamePasswordToken("gongji","123");
        try {
            subject.login(token);
            System.out.println("登陆成功");
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("用户不存在");
        }catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            System.out.println("密码错误..");
        }catch (AuthenticationException e) {
            e.printStackTrace();
            System.out.println("其他认证错误");
        }
        System.out.println(subject);
        //判断角色 --shiro底层 自动找到myRealm 返回AuthorizationInfo 信息 进行判断比较
        if(subject.hasRole("admin")){
            System.out.println("豪哥有:admin角色");
        }
        //判断主题是否有权限
        if(subject.isPermitted("driver:xx")){
            System.out.println("公鸡可以开车");
        }



        subject.logout();//退出


    }

二,Shiro集成Spring

配置导包

<!-- shiro的支持包 -->
 <dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-all</artifactId>
    <version>1.4.0</version>
    <type>pom</type>
</dependency>
  <!-- shiro与Spring的集成包 -->
  <dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring</artifactId>
    <version>1.4.0</version>
  </dependency>
<filter>
  <filter-name>shiroFilter</filter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  <init-param>
    <param-name>targetFilterLifecycle</param-name>
    <param-value>true</param-value>
  </init-param>
</filter>

<filter-mapping>
  <filter-name>shiroFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

三,Authentication(身份认证)和Authorizing(授权)

public class MyRealm extends AuthorizingRealm {

    //登陆认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
       
        //身份 username
        Object username = authenticationToken.getPrincipal();
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username1 = token.getUsername();

        //通过用户名得到密码
        String pwd = getPwdByUsername(username1);
        if(pwd == null){
            return null;
        }
        //添加颜值
        ByteSource salt = ByteSource.Util.bytes("itsource");
        //得到simpleAuthenticationInfo
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username,pwd,salt,getName());


        return simpleAuthenticationInfo;
    }

    public String getPwdByUsername(String username){
        if("bb".equals(username)){
            return "607ca42819a4452f620bf721b7558c18";
        }else{
            return null;
        }
    }

    public static void main(String[] args) {
        SimpleHash simpleHash = new SimpleHash("MD5", "520520", "itsource", 10);
        System.out.println(simpleHash);
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //得到主体/用户
        String username =(String)principalCollection.getPrimaryPrincipal();
        //根据用户 从数据库去拿到权限 加入到shiro里面
        Set<String> permissions = new HashSet<>();
        if(username.equals("bb")){
            permissions.add("user:*");
            permissions.add("employee:*");
        }

        SimpleAuthorizationInfo simpleAuthorizationInfo  = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addStringPermissions(permissions);

        //返回到shiro里面 就会进行权限的判断
        return simpleAuthorizationInfo;
    }
}

授权数据库查询

public class AisellFilterChainDefinitionMapBuilder {


    public Map buildFilterChaiDefinitionMap(){
        //map要顺序要求
        /**
         */

        Map mp = new LinkedHashMap();
        mp.put("/s/login.jsp","anon");
        mp.put("/login","anon");
        mp.put("/s/permission.jsp","perms[user:*]");
        mp.put("/**","authc");
        return mp;


    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值