一般我们把密码存在数据库里都是采用加密的方式,确保了即使数据库泄漏,不法分子也无法登录帐号。常见的加密算法有MD5,SHA1等,本篇博客将给大家讲解如何在Shiro中使用MD5算法给密码加密。
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.jk.shiroLearninggroupId>
<artifactId>chapter4artifactId>
<version>1.0-SNAPSHOTversion>
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.9version>
dependency>
<dependency>
<groupId>commons-logginggroupId>
<artifactId>commons-loggingartifactId>
<version>1.1.3version>
dependency>
<dependency>
<groupId>org.apache.shirogroupId>
<artifactId>shiro-coreartifactId>
<version>1.2.2version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.25version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>0.2.23version>
dependency>
dependencies>
project>
[main]
#自定义authorizer
authorizer=org.apache.shiro.authz.ModularRealmAuthorizer
securityManager.authorizer=$authorizer
#自定义realm 一定要放在securityManager.authorizer赋值之后(因为调用setRealms会将realms设置给authorizer,并给各个Realm设置permissionResolver和rolePermissionResolver)
realm=com.jk.realm.MyRealm
#配置加密匹配器
credentialsMatcher=org.apache.shiro.authc.credential.HashedCredentialsMatcher
#加密算法
credentialsMatcher.hashAlgorithmName=MD5
#加密次数
credentialsMatcher.hashIterations=1024
realm.credentialsMatcher=$credentialsMatcher
securityManager.realms=$realm
配置比以前多了加密匹配器的部分
public class MyRealm extends AuthorizingRealm {
//授权,调用checkRole/checkPermission/hasRole/isPermitted都会执行该方法
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
//可通过不同principal赋予不同权限
if (principals.getPrimaryPrincipal().equals("jack")){
//授予角色role1
authorizationInfo.addRole("role1");
authorizationInfo.addRole("role2");
//授予对user任何行为任何实例的权限
authorizationInfo.addObjectPermission(new WildcardPermission("user:*"));
//等同于
//authorizationInfo.addStringPermission("user:*");
}
return authorizationInfo;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String username = (String)token.getPrincipal(); //得到用户名
//加密算法
String hashAlgorithName="MD5";
//加密明文
String credentials="123456";
//加密盐值
ByteSource salt = null;
//加密盐值
//盐值通常取唯一的,我们这用用户名作为盐值
//ByteSource salt= ByteSource.Util.bytes(username);
//加密次数
int hashIterations = 1024;
Object password = new SimpleHash(hashAlgorithName,credentials,salt,hashIterations);
return new SimpleAuthenticationInfo(username, password, getName());
}
}
在一般开发过程中我们不会直接用MD5加密,还要加上一个盐值,这个盐值一般是唯一的。
public class UseMD5 {
public static void main(String[]args){
//1、获取SecurityManager工厂,此处使用Ini配置文件初始化SecurityManager
Factory factory =
new IniSecurityManagerFactory("classpath:shiro-realm.ini");
//2、得到SecurityManager实例 并绑定给SecurityUtils
org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
//3、得到Subject及创建用户名/密码身份验证Token(即用户身份/凭证)
Subject subject = SecurityUtils.getSubject();
//登录信息传密码明文
UsernamePasswordToken token = new UsernamePasswordToken("jack", "123456");
try {
//4、登录,即身份验证
subject.login(token);
//验证是否有user1的create权限
System.out.println(subject.isPermitted("user1:create:*"));
//验证是否有role1角色
System.out.println(subject.hasRole("role1"));
} catch (AuthenticationException e) {
//5、身份验证失败
e.printStackTrace();
}
//6、退出
subject.logout();
}
}
登录时我们传的是明文123456,校验时比较的是用MD5加盐用户名加密1024次后的值
开发中我们一般会采用数据库储存用户名,加密后密码还要盐值,,需要使用到JdbcRealm
drop database if exists shiro;
create database shiro;
use shiro;
create table users (
id bigint auto_increment,
username varchar(100),
password varchar(100),
password_salt varchar(100),
constraint pk_users primary key(id)
) charset=utf8 ENGINE=InnoDB;
create unique index idx_users_username on users(username);
create table user_roles(
id bigint auto_increment,
username varchar(100),
role_name varchar(100),
constraint pk_user_roles primary key(id)
) charset=utf8 ENGINE=InnoDB;
create unique index idx_user_roles on user_roles(username, role_name);
create table roles_permissions(
id bigint auto_increment,
role_name varchar(100),
permission varchar(100),
constraint pk_roles_permissions primary key(id)
) charset=utf8 ENGINE=InnoDB;
create unique index idx_roles_permissions on roles_permissions(role_name, permission);
insert into users(username, password, password_salt) values('jack', 'fc1709d0a95a6be30bc5926fdb7f22f4', 'jack');
insert into user_roles(username, role_name) values('jack', 'role1');
insert into user_roles(username, role_name) values('jack', 'role2');
insert into roles_permissions(role_name, permission) values('role1', 'user1:*');
insert into roles_permissions(role_name, permission) values('role1', 'user2:*');
insert into roles_permissions(role_name, permission) values('role2', 'user3:*');
[main]
authorizer=org.apache.shiro.authz.ModularRealmAuthorizer
securityManager.authorizer=$authorizer
#自定义realm 一定要放在securityManager.authorizer赋值之后(因为调用setRealms会将realms设置给authorizer,并给各个Realm设置permissionResolver和rolePermissionResolver)
jdbcRealm=org.apache.shiro.realm.jdbc.JdbcRealm
dataSource=com.alibaba.druid.pool.DruidDataSource
dataSource.driverClassName=com.mysql.jdbc.Driver
dataSource.url=jdbc:mysql://localhost:3306/shiro
dataSource.username=root
dataSource.password=root
jdbcRealm.dataSource=$dataSource
jdbcRealm.permissionsLookupEnabled=true
#配置加密匹配器
credentialsMatcher=org.apache.shiro.authc.credential.HashedCredentialsMatcher
#加密算法
credentialsMatcher.hashAlgorithmName=MD5
#加密次数
credentialsMatcher.hashIterations=1024
jdbcRealm.credentialsMatcher=$credentialsMatcher
securityManager.realms=$jdbcRealm
这个也是比之前的多了配置加密匹配器
public class UseJdbcMD5 {
public static void main(String[]args){
//1、获取SecurityManager工厂,此处使用Ini配置文件初始化SecurityManager
Factory factory =
new IniSecurityManagerFactory("classpath:shiro-jdbc.ini");
//2、得到SecurityManager实例 并绑定给SecurityUtils
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
//3、得到Subject及创建用户名/密码身份验证Token(即用户身份/凭证)
Subject subject = SecurityUtils.getSubject();
//登录信息传密码明文
UsernamePasswordToken token = new UsernamePasswordToken("jack", "123456");
try {
//4、登录,即身份验证
subject.login(token);
//验证是否有user1的create权限
System.out.println(subject.isPermitted("user1:create:*"));
//验证是否有role1角色
System.out.println(subject.hasRole("role1"));
} catch (AuthenticationException e) {
//5、身份验证失败
e.printStackTrace();
}
//6、退出
subject.logout();
}
}