一般我們把密碼存在數(shù)據(jù)庫里都是采用加密的方式地技,確保了即使數(shù)據(jù)庫泄漏炫狱,不法分子也無法登錄帳號态鳖。常見的加密算法有MD5,SHA1等篙议,本篇博客將給大家講解如何在Shiro中使用MD5算法給密碼加密。
POM
<?xml version="1.0" encoding="UTF-8"?>
<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.0</modelVersion>
<groupId>com.jk.shiroLearning</groupId>
<artifactId>chapter4</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.9</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.3</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.25</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>0.2.23</version>
</dependency>
</dependencies>
</project>
shiro-realm.ini
[main]
#自定義authorizer
authorizer=org.apache.shiro.authz.ModularRealmAuthorizer
securityManager.authorizer=$authorizer
#自定義realm 一定要放在securityManager.authorizer賦值之后(因?yàn)檎{(diào)用setRealms會將realms設(shè)置給authorizer擎宝,并給各個(gè)Realm設(shè)置permissionResolver和rolePermissionResolver)
realm=com.jk.realm.MyRealm
#配置加密匹配器
credentialsMatcher=org.apache.shiro.authc.credential.HashedCredentialsMatcher
#加密算法
credentialsMatcher.hashAlgorithmName=MD5
#加密次數(shù)
credentialsMatcher.hashIterations=1024
realm.credentialsMatcher=$credentialsMatcher
securityManager.realms=$realm
配置比以前多了加密匹配器的部分
自定義Realm
public class MyRealm extends AuthorizingRealm {
//授權(quán),調(diào)用checkRole/checkPermission/hasRole/isPermitted都會執(zhí)行該方法
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
//可通過不同principal賦予不同權(quán)限
if (principals.getPrimaryPrincipal().equals("jack")){
//授予角色role1
authorizationInfo.addRole("role1");
authorizationInfo.addRole("role2");
//授予對user任何行為任何實(shí)例的權(quán)限
authorizationInfo.addObjectPermission(new WildcardPermission("user:*"));
//等同于
//authorizationInfo.addStringPermission("user:*");
}
return authorizationInfo;
}
//認(rèn)證
@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);
//加密次數(shù)
int hashIterations = 1024;
Object password = new SimpleHash(hashAlgorithName,credentials,salt,hashIterations);
return new SimpleAuthenticationInfo(username, password, getName());
}
}
在一般開發(fā)過程中我們不會直接用MD5加密,還要加上一個(gè)鹽值绍申,這個(gè)鹽值一般是唯一的噩咪。
驗(yàn)證登錄
public class UseMD5 {
public static void main(String[]args){
//1、獲取SecurityManager工廠极阅,此處使用Ini配置文件初始化SecurityManager
Factory<SecurityManager> factory =
new IniSecurityManagerFactory("classpath:shiro-realm.ini");
//2胃碾、得到SecurityManager實(shí)例 并綁定給SecurityUtils
org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
//3、得到Subject及創(chuàng)建用戶名/密碼身份驗(yàn)證Token(即用戶身份/憑證)
Subject subject = SecurityUtils.getSubject();
//登錄信息傳密碼明文
UsernamePasswordToken token = new UsernamePasswordToken("jack", "123456");
try {
//4筋搏、登錄仆百,即身份驗(yàn)證
subject.login(token);
//驗(yàn)證是否有user1的create權(quán)限
System.out.println(subject.isPermitted("user1:create:*"));
//驗(yàn)證是否有role1角色
System.out.println(subject.hasRole("role1"));
} catch (AuthenticationException e) {
//5、身份驗(yàn)證失敗
e.printStackTrace();
}
//6奔脐、退出
subject.logout();
}
}
登錄時(shí)我們傳的是明文123456俄周,校驗(yàn)時(shí)比較的是用MD5加鹽用戶名加密1024次后的值
開發(fā)中我們一般會采用數(shù)據(jù)庫儲存用戶名,加密后密碼還要鹽值髓迎,峦朗,需要使用到JdbcRealm
首先執(zhí)行sql語句創(chuàng)建數(shù)據(jù)庫并插入數(shù)據(jù)
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:*');
shiro-jdbc.ini
[main]
authorizer=org.apache.shiro.authz.ModularRealmAuthorizer
securityManager.authorizer=$authorizer
#自定義realm 一定要放在securityManager.authorizer賦值之后(因?yàn)檎{(diào)用setRealms會將realms設(shè)置給authorizer,并給各個(gè)Realm設(shè)置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
#加密次數(shù)
credentialsMatcher.hashIterations=1024
jdbcRealm.credentialsMatcher=$credentialsMatcher
securityManager.realms=$jdbcRealm
這個(gè)也是比之前的多了配置加密匹配器
校驗(yàn)登錄
public class UseJdbcMD5 {
public static void main(String[]args){
//1排龄、獲取SecurityManager工廠波势,此處使用Ini配置文件初始化SecurityManager
Factory<SecurityManager> factory =
new IniSecurityManagerFactory("classpath:shiro-jdbc.ini");
//2、得到SecurityManager實(shí)例 并綁定給SecurityUtils
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
//3橄维、得到Subject及創(chuàng)建用戶名/密碼身份驗(yàn)證Token(即用戶身份/憑證)
Subject subject = SecurityUtils.getSubject();
//登錄信息傳密碼明文
UsernamePasswordToken token = new UsernamePasswordToken("jack", "123456");
try {
//4尺铣、登錄,即身份驗(yàn)證
subject.login(token);
//驗(yàn)證是否有user1的create權(quán)限
System.out.println(subject.isPermitted("user1:create:*"));
//驗(yàn)證是否有role1角色
System.out.println(subject.hasRole("role1"));
} catch (AuthenticationException e) {
//5争舞、身份驗(yàn)證失敗
e.printStackTrace();
}
//6凛忿、退出
subject.logout();
}
}