shiro 基本知识测试

shiro 基本知识测试

<!--shiro核心包-->
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-core</artifactId>
    <version>1.4.0</version>
</dependency>

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.10</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.46</version>
</dependency>


<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

AuhtorizationTest

package com.mozq.shiro.shiro01;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.SimpleAccount;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.SimpleAccountRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.junit.Test;

public class AuhtorizationTest {

    @Test
    public void testAuhtorization(){
        //创建权限管理器,给定Realm提供认证和授权信息
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        SimpleAccountRealm simpleAccountRealm = new SimpleAccountRealm();
        simpleAccountRealm.addAccount("liubei", "123","砂场老板","砂场负责人");

        defaultSecurityManager.setRealm(simpleAccountRealm);
        SecurityUtils.setSecurityManager(defaultSecurityManager);

        //获取主体
        Subject subject = SecurityUtils.getSubject();

        //登录
        subject.login(new UsernamePasswordToken("liubei", "123"));

        //检查权限
        subject.checkRoles("砂场老板1");
//        subject.checkRoles("砂场老板","砂场负责人");
    }
}

AuthenticationTest

package com.mozq.shiro.shiro01;


import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.SimpleAccountRealm;
import org.apache.shiro.subject.Subject;
import org.junit.Test;

public class AuthenticationTest {

    @Test
    public void AuthenticationTest(){
        //创建权限管理器,给定Realm提供认证和授权信息
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        SimpleAccountRealm simpleAccountRealm = new SimpleAccountRealm();
        simpleAccountRealm.addAccount("liubei", "123");
        simpleAccountRealm.addAccount("sunquan", "123");

        defaultSecurityManager.setRealm(simpleAccountRealm);
        SecurityUtils.setSecurityManager(defaultSecurityManager);

        //获取主体
        Subject subject = SecurityUtils.getSubject();

        //登录
        subject.login(new UsernamePasswordToken("liubei", "123"));
        subject.login(new UsernamePasswordToken("sunquan", "123"));

        System.out.println("subject.isAuthenticated():" + subject.isAuthenticated());
        //退出
        subject.logout();
        System.out.println("subject.isAuthenticated():" + subject.isAuthenticated());

    }
}

IniRealmTest

package com.mozq.shiro.shiro01;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.subject.Subject;
import org.junit.Test;

public class IniRealmTest {

    @Test
    public void testIniRealm(){
        //创建权限管理器,给定Realm提供认证和授权信息
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        IniRealm iniRealm = new IniRealm("classpath:user.ini");
        defaultSecurityManager.setRealm(iniRealm);
        SecurityUtils.setSecurityManager(defaultSecurityManager);

        //获取主体
        Subject subject = SecurityUtils.getSubject();

        //认证
        subject.login(new UsernamePasswordToken("刘备", "123"));
        System.out.println("subject.isAuthenticated():" + subject.isAuthenticated());
        //授权
        subject.checkRoles("砂场老板");
        subject.checkRoles("砂场老板", "砂场负责人");
    }

}
# user.ini
[users]
刘备=123,砂场老板
sunquan=234,砂场负责人
[roles]
砂场老板=customer:select,order:select

JdbcRealmTest

package com.mozq.shiro.shiro01;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.subject.Subject;
import org.junit.Before;
import org.junit.Test;

public class JdbcRealmTest {

    private DruidDataSource dataSource = new DruidDataSource();

    @Before
    public void setDataSource(){
        dataSource.setUrl("jdbc:mysql:///perms");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
    }

    @Test
    public void testJdbcRealm(){
        //创建权限管理器,给定Realm提供认证和授权信息
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        JdbcRealm jdbcRealm = new JdbcRealm();
        jdbcRealm.setDataSource(dataSource);
        jdbcRealm.setPermissionsLookupEnabled(true);//开启权限查询,默认不会开启
        //参数用户名,结果用户密码
        jdbcRealm.setAuthenticationQuery("select password from user where username=?");
        //参数用户名,结果角色名称
        jdbcRealm.setUserRolesQuery(
                "select R.role_name\n" +
                "from role R\n" +
                "left join user_role UR\n" +
                "on R.id=UR.role_id\n" +
                "left join user U\n" +
                "on UR.user_id=U.id\n" +
                "where U.username=?"
        );
        //参数角色名称,结果权限名称
        jdbcRealm.setPermissionsQuery(
               "select P.permission_name\n" +
                       "from permission P\n" +
                       "left join role_permission RP\n" +
                       "on RP.permission_id=P.id\n" +
                       "left join role R\n" +
                       "on RP.role_id=R.id\n" +
                       "where R.role_name=?"
        );
        defaultSecurityManager.setRealm(jdbcRealm);

        SecurityUtils.setSecurityManager(defaultSecurityManager);

        //获取主体
        Subject subject = SecurityUtils.getSubject();

        //认证
        subject.login(new UsernamePasswordToken("刘备", "123"));
        System.out.println("subject.isAuthenticated():" + subject.isAuthenticated());
        //授权
        subject.checkRoles("砂场老板");
//        subject.checkRoles("砂场老板", "砂场负责人");

        subject.checkPermission("customer:select");
    }

}

CustomRealm

package com.mozq.shiro.shiro01;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class CustomRealm extends AuthorizingRealm {

    private Map<String, String> users = new HashMap<>();
    {
        users.put("刘备","123");
        users.put("孙权","123");
    }
    private String  getPasswordByUsername(String username){
        return users.get(username);
    }
    private Set<String> getRolesByUsername(String username){
        Set<String> roles = new HashSet<>();
        if("刘备".equals(username)){
            roles.add("砂场老板");
            return roles;
        }
        return roles;
    }
    private Set<String> getPermsByUsername(String username){
        Set<String> perms = new HashSet<>();
        if("刘备".equals(username)){
            perms.add("user:add");
            perms.add("user:delete");
            return perms;
        }
        return perms;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = (String) principals.getPrimaryPrincipal();
        Set<String> roles = getRolesByUsername(username);
        Set<String> perms = getPermsByUsername(username);

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRoles(roles);
        simpleAuthorizationInfo.addStringPermissions(perms);
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = String.valueOf(token.getPrincipal());
        String password = String.valueOf((char[]) token.getCredentials());
        System.out.println(username + ":" + password);

        String rightPassword = getPasswordByUsername(username);
        if(rightPassword != null && rightPassword.equals(password)){
            return new SimpleAuthenticationInfo(username, password, "customRealm");
        }
        return null;
    }

}

CustomRealmTest

package com.mozq.shiro.shiro01;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;
import org.junit.Test;

import java.util.HashSet;

public class CustomRealmTest {

    @Test
    public void testCustomRealm(){
        //创建权限管理器,给定Realm提供认证和授权信息
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        CustomRealm customRealm = new CustomRealm();
        defaultSecurityManager.setRealm(customRealm);
        SecurityUtils.setSecurityManager(defaultSecurityManager);

        //获取主体
        Subject subject = SecurityUtils.getSubject();

        //认证
        subject.login(new UsernamePasswordToken("刘备", "123"));
//        subject.login(new UsernamePasswordToken("孙权", "123"));
        System.out.println("subject.isAuthenticated():" + subject.isAuthenticated());
        //授权
        subject.checkRoles("砂场老板");
//        subject.checkRoles("砂场老板", "砂场负责人");
        subject.checkPermissions("user:add", "user:delete");
    }


    @Test
    public void testAddAll(){
        HashSet<String> roles = new HashSet<>();
        roles.addAll(null);//java.lang.NullPointerException
    }
}

@startuml

interface Realm
abstract class CachingRealm
abstract class AuthenticatingRealm
abstract class AuthorizingRealm
class SimpleAccountRealm
class TextConfigurationRealm
class IniRealm
class PropertiesRealm
class JdbcRealm

Realm <|.. CachingRealm
CachingRealm <|-- AuthenticatingRealm
AuthenticatingRealm <|-- AuthorizingRealm
AuthorizingRealm <|-- SimpleAccountRealm
SimpleAccountRealm <|-- TextConfigurationRealm
TextConfigurationRealm <|-- IniRealm
TextConfigurationRealm <|-- PropertiesRealm

AuthorizingRealm <|-- JdbcRealm

@enduml
posted @ 2019-10-23 23:20  没有理由不会呀  阅读(329)  评论(0编辑  收藏  举报