安全框架Shiro

shiro认证:

package com.research.shiro;

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.Before;
import org.junit.Test;

/***
 * shiro认证请求过程
 */
public class AuthenticationTest {
    SimpleAccountRealm simpleAccountRealm = new SimpleAccountRealm();

    @Before
    public void addUser(){
        simpleAccountRealm.addAccount("liri","123456");
    }

    @Test
    public void testAuthentication(){
        //1.构建SecuityManager环境
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        defaultSecurityManager.setRealm(simpleAccountRealm);

        //2.主体提交认证请求
        SecurityUtils.setSecurityManager(defaultSecurityManager);
        Subject subject = SecurityUtils.getSubject();

        //登录
        UsernamePasswordToken token = new UsernamePasswordToken("liri","123456");
        subject.login(token);

        //true为登录成功
        System.out.println("isAuthenticated:"+subject.isAuthenticated());

        subject.logout();

        System.out.println("isAuthenticated:"+subject.isAuthenticated());
    }
}

 

Shiro授权

package com.research.shiro;

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.Before;
import org.junit.Test;

/***
 * 授权
 */
public class AuthorizationTest {
    //SimpleAccountRealm不支持添加权限,自定义Realm可以
    SimpleAccountRealm simpleAccountRealm = new SimpleAccountRealm();

    @Before
    public void addUser() {
        simpleAccountRealm.addAccount("liri", "123456", "admin", "user");
    }

    @Test
    public void testAuthentication() {
        //1.构建SecuityManager环境
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        defaultSecurityManager.setRealm(simpleAccountRealm);

        //2.主体提交认证请求
        SecurityUtils.setSecurityManager(defaultSecurityManager);
        Subject subject = SecurityUtils.getSubject();

        //登录
        UsernamePasswordToken token = new UsernamePasswordToken("liri", "123456");
        subject.login(token);

        //true为登录成功
        System.out.println("isAuthenticated:" + subject.isAuthenticated());

        //用户是否具备这样的角色
        subject.checkRole("admin");
        subject.checkRoles("user", "admin");


    }
}

Realm:域,Shiro 从从Realm获取安全数据(如用户、角色、权限),就是说SecurityManager要验证用户身份,那么它需要从Realm获取相应的用户进行比较以确定用户身份是否合法;
也需要从Realm得到用户相应的角色/权限进行验证用户是否能进行操作;可以把Realm看成DataSource , 即安全数据源。

自定义realm

package com.research.shiro.realm;

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.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.HashSet;
import java.util.Set;

public class CustomRealm extends AuthorizingRealm {


    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //从主体传过来的认证信息中获取用户名
        String userName = (String) principalCollection.getPrimaryPrincipal();
        //从数据库中获取角色数据
        Set<String> roles = getRolesByUsername(userName);
        //从数据库中获取权限数据
        Set<String> permissions = getPermissionsByUsername(userName);
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        //设置角色
        simpleAuthorizationInfo.setRoles(roles);
        //设置权限
        simpleAuthorizationInfo.setStringPermissions(permissions);
        return simpleAuthorizationInfo;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //从主体传过来的认证信息中获取用户名
        String userName = (String) authenticationToken.getPrincipal();
        //通过用户名到数据库中获取凭证
        String password = getPasswordByUserName(userName);
        if (password == null) {
            return null;
        }
        //realmName随便取名
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo
                ("sun",password,"customReal");
        //**************加盐**********************
        authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes("liri"));
        //****************************************
        return authenticationInfo;
    }

    //模拟数据库查询密码
    private String getPasswordByUserName(String userName) {
        //123456加密后+"liri"
        return "931c8cb3c2f2580b58c326022fc346f2";
    }
    //模拟数据库查询角色数据
    private Set<String> getRolesByUsername(String userName) {
        //...
        Set<String> sets = new HashSet<String>();
        sets.add("admin");
        sets.add("user");
        return sets;
    }
    //模拟数据库查询权限数据
    private Set<String> getPermissionsByUsername(String userName) {
        //...
        Set<String> sets = new HashSet<String>();
        sets.add("select");
        sets.add("add");
        return sets;
    }

    public static void main(String[] args) {
        Md5Hash md5Hash = new Md5Hash("123456","liri");
        System.out.println(md5Hash.toString());
    }
}
package com.research.shiro;

import com.research.shiro.realm.CustomRealm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.subject.Subject;
import org.junit.Test;

/***
 *自定义realm
 */
public class CustomRealTest {

    @Test
    public void testAuthentication() {
        //自定义realm
        CustomRealm customRealm = new CustomRealm();

        //1.构建SecuityManager环境
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        defaultSecurityManager.setRealm(customRealm);

        //************加密*******************
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashAlgorithmName("md5");
        //加密一次
        matcher.setHashIterations(1);
        customRealm.setCredentialsMatcher(matcher);
        //***********************************

        //2.主体提交认证请求
        SecurityUtils.setSecurityManager(defaultSecurityManager);
        Subject subject = SecurityUtils.getSubject();

        //登录
        UsernamePasswordToken token = new UsernamePasswordToken("sun", "123456");
        subject.login(token);

        //true为登录成功
        System.out.println("isAuthenticated:" + subject.isAuthenticated());

        subject.checkRole("admin");
        subject.checkPermissions("add", "select");
    }
}

 

jdbc realm

package com.research.shiro;

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.Test;

public class JdbcRealmTest {

    //数据源
    DruidDataSource dataSource = new DruidDataSource();
    {
        dataSource.setUrl("jdbc:mysql://39.106.63.239:13306/dbgirl");
        dataSource.setUsername("root");
        dataSource.setPassword("riLI");
    }
    @Test
    public void  testAuthentication(){
        JdbcRealm jdbcRealm = new JdbcRealm();
        jdbcRealm.setDataSource(dataSource);
        //开启权限查询
        jdbcRealm.setPermissionsLookupEnabled(true);

        String sql = "SELECT password FROM userbasicsinfo WHERE userName = ?";
        //认证的sql查询使用我们自己的sql查询
        jdbcRealm.setAuthenticationQuery(sql);

        //查询权限
        String roleSql = "SELECT role_name FROM user_role WHERE user_name = ?";
        jdbcRealm.setUserRolesQuery(roleSql);

        //查询角色
        String perSql = "SELECT permission FROM permission WHERE role_name=?";
        jdbcRealm.setPermissionsQuery(perSql);

        //1.构建SecuityManager环境
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        defaultSecurityManager.setRealm(jdbcRealm);

        //2.主体提交认证请求
        SecurityUtils.setSecurityManager(defaultSecurityManager);
        Subject subject = SecurityUtils.getSubject();

        //登录
        UsernamePasswordToken token = new UsernamePasswordToken("sun","123456");
        subject.login(token);

        //true为登录成功
        System.out.println("isAuthenticated:"+subject.isAuthenticated());

        //验证角色
        subject.checkRole("admin");
        //验证权限
        subject.checkPermission("select");
    }
}

 

版权声明:本文为Java_Mrsun原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/Java_Mrsun/article/details/82014588