Springboot2集成Shiro框架(四)凭证比较器详解

1、什么是凭证比较器

在第一章,shiro整体架构图上可以看到,shiro为我们提供了密码学工具,和哈希凭据匹配器 HashedCredentialsMatcher 类,下图可以看到此类继承了编解码支持器 CodecSupport 类和实现了 CredentialsMatcher 接口,实现了接口中 boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) 方法,这个方法就可以替我们实现密码比较,他会在调用自定义realm的身份认证方法后来执行!在这里插入图片描述

2、为什么要加密加盐

  • 之前的例子中,我们在自定义realm的 doGetAuthenticationInfo 方法中采用了自己加密和对比密码,不同则抛出 IncorrectCredentialsException 异常的方式对比密码,但是在继续深入学习shiro的过程中,发现了shiro已经为我们提供了自动密码比对工具,我们只要安装上去即可使用。之后会讲到他的执行原理和使用方法。
  • 那么为什么要对数据加密呢?这篇文章可以告诉你答案2018年国内外信息泄露案例汇编,现在数据库加密基本上是使用MD5加密方式,MD5加密过的密文只能被暴力破解,我们不仅仅是要防范外部黑客的攻击,还需要放置内部维护人员猜出密码,加密过后,即使数据库被泄露出去,但是暴露出去的人员的密码均是加密过的,这样即使是暴力破解,也给予了时间挽救。
  • 为什么要加盐呢,盐就是让你的密码更加的安全,更加的难以破解,在你的密码中加入特定的字段,然后在进行加密,这样即使密码相同的情况下,只要盐不相同,数据库储存的字段也不会相同,大大减少了很多用户使用同一密码,数据库泄漏一下破解很多用户账号的可能!

3、如何生成密文

shiro已经为我们提供了密码学工具,SimpleHash 类,我们只需要调用这个类的方法即可快速完成密码加密,查看关系图,猜测此类还提供sha加密方式(后认证过),
在这里插入图片描述

String hashAlgorithmName = "MD5";//加密方式
Object crdentials = "admin";//密码原值
ByteSource salt = ByteSource.Util.bytes("admin");//以账号作为盐值
int hashIterations = 1024;//加密次数
Object result = new SimpleHash(hashAlgorithmName,crdentials,salt,hashIterations);
System.out.println("admin:"+result);
//输出
>> admin:df655ad8d3229f3269fad2a8bab59b6c

用户注册时,可以使用此方法生成密文

4、了解shiro自带凭证比较器

我们跟踪登录流程发现用户调用login接口后,shiro框架会执行下列流程:

Created with Raphaël 2.2.0 用户登录,调用subject.login() 自定义realm中的身份验证方法 doGetAuthenticationInfo AuthenticatingRealm类中的getAuthenticationInfo方法 调用assertCredentialsMatch(token, info);比较密码 调用HashedCredentialsMatcher类的doCredentialsMatch()方法 密码正确? 登陆成功 结束 抛出IncorrectCredentialsException异常 yes no

下面为 HashedCredentialsMatcher 哈希凭据匹配器 的继承关系
在这里插入图片描述

4.1提供的的比较凭证的方法部分代码

//固有属性
	private String hashAlgorithm; // 加密算法的名称
    private int hashIterations; // 配置加密的次数
    private boolean hashSalted;//是否加盐
    private boolean storedCredentialsHexEncoded;// 是否存储为16进制
    //构造
    public HashedCredentialsMatcher() {
        this.hashAlgorithm = null;
        this.hashSalted = false;
        this.hashIterations = 1;
        this.storedCredentialsHexEncoded = true; //false means Base64-encoded
    }
	//设置凭证加密次数
    public void setHashIterations(int hashIterations) {
        if (hashIterations < 1) {//在此限制了最低加密次数为1次
            this.hashIterations = 1;
        } else {
            this.hashIterations = hashIterations;
        }
    }
    ...............
//实现对比凭证方法,token中包含用户输入信息,info则是realm中用户认证方法中返回的dbuser信息
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        Object tokenCredentials = getCredentials(token);
        Object accountCredentials = getCredentials(info);
        return equals(tokenCredentials, accountCredentials);
    }

5、使用shiro自带凭证比较器

  1. 需要在shiroconfig配置类中新增凭证比较器
    @Bean
    public SimpleCredentialsMatcher CredentialsMatcher() {
        HashedCredentialsMatcher hct = new HashedCredentialsMatcher();
        // 加密算法的名称
        hct.setHashAlgorithmName("MD5");
        // 配置加密的次数
        hct.setHashIterations(1024);
        // 是否存储为16进制
        hct.setStoredCredentialsHexEncoded(true);
        return hct;
    }
  1. 把凭证比较器放入自定义realm中,如果没有此步骤shiro不会进行凭证验证
    /**
     * 自定义身份认证 realm;
     * <p>
     * 必须写这个类,并加上 @Bean 注解,目的是注入 MyShiroRealm, 否则会影响 MyShiroRealm类 中其他类的依赖注入
     */
    @Bean
    public MyShiroRealm myShiroRealm() {
        MyShiroRealm myShiroRealm = new MyShiroRealm();
        // 设置凭证比较器
        myShiroRealm.setCredentialsMatcher(CredentialsMatcher());
        return myShiroRealm;
    }
  1. 修改用户信息,模拟用户注册生成的密码,更新至业务层
    我们采用guest用户来测试,使用用户名guest作为盐,把生成的密码放入service中,
        String hashAlgorithmName = "MD5";//加密方式
        Object crdentials = "guest";//密码原值
        ByteSource salt = ByteSource.Util.bytes("guest");//以账号作为盐值
        int hashIterations = 1024;//加密次数
        Object result = new SimpleHash(hashAlgorithmName,crdentials,salt,hashIterations);
        System.out.println("admin:"+result);
        >>admin:565dd969076eef0ac3f9d49aa61e9489
  1. 更新UserServiceImpl
 @Override
    public User findByUsername(String username) {
        User user = new User();
        user.setUsername(username);
        Set<String> roleList = new HashSet<>();
        Set<String> permissionsList = new HashSet<>();
        switch (username) {
        case "admin":
            roleList.add("admin");
            user.setPassword("admin");
            permissionsList.add("user:add");
            permissionsList.add("user:delete");
            break;
        case "consumer":
            roleList.add("consumer");
            user.setPassword("consumer");
            permissionsList.add("consumer:modify");
            break;
        default:
            roleList.add("guest");
            user.setPassword("565dd969076eef0ac3f9d49aa61e9489");
            break;
        }
        user.setRole(roleList);
        user.setPermission(permissionsList);
        return user;
    }
  1. 把自定义realm中的判断密码部分代码删除,此时,我们可以把这个方法理解为提供给主框架真实用户信息,作为凭证对比对象
   /**
     * 身份验证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("进入自定义登录验证方法!");
        if (userService == null) {
            userService = (UserService) SpringBeanFactoryUtil.getBeanByName("userServiceImpl");
        }
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String username = usernamePasswordToken.getUsername();// 用户输入用户名
        User user = userService.findByUsername(username);// 根据用户输入用户名查询该用户
        if (user == null) {
            throw new UnknownAccountException();// 用户不存在
        }
        String password = user.getPassword();// 数据库获取的密码
        // 主要的(用户名,也可以是用户对象(最好不放对象)),资格证书(数据库获取的密码),区域名称(当前realm名称)
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username, password, getName());
        //加盐,对比的时候会使用该参数对用户输入的密码按照密码比较器指定规则加盐,加密,再去对比数据库密文
        simpleAuthenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(username));
        return simpleAuthenticationInfo;
    }


5.1登录测试,可以登录

在这里插入图片描述

  • 此时我们断点到shiro的凭证对比器中查看,可以看到shiro内部已经使用 hashProvidedCredentials 方法对输入的密码进行了加密

在这里插入图片描述
在这里插入图片描述

  • 部分源码
//HashedCredentialsMatcher类 密码加密
	protected Object hashProvidedCredentials(AuthenticationToken token, AuthenticationInfo info) {
        Object salt = null;
        if (info instanceof SaltedAuthenticationInfo) {
            salt = ((SaltedAuthenticationInfo) info).getCredentialsSalt();
        } else {
            //retain 1.0 backwards compatibility:
            if (isHashSalted()) {
                salt = getSalt(token);
            }
        }
        return hashProvidedCredentials(token.getCredentials(), salt, getHashIterations());
    }
    @Override    //HashedCredentialsMatcher类
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        Object tokenHashedCredentials = hashProvidedCredentials(token, info);
        Object accountCredentials = getCredentials(info);
        return equals(tokenHashedCredentials, accountCredentials);
    }
	//密码对比方法SimpleCredentialsMatcher类
    protected boolean equals(Object tokenCredentials, Object accountCredentials) {
        .......
        if (isByteSource(tokenCredentials) && isByteSource(accountCredentials)) {
            ....
            byte[] tokenBytes = toBytes(tokenCredentials);
            byte[] accountBytes = toBytes(accountCredentials);
            return MessageDigest.isEqual(tokenBytes, accountBytes);
        } else {
            return accountCredentials.equals(tokenCredentials);
        }
    }

6、如何使用自定义密码比较器

  1. 在理解了shiro自带的凭证比较器后,自定义一个自己的凭证比较器思路应该也十分清晰了,我们只需要创建 MyCredentialsMatcher 类继承 SimpleCredentialsMatcher 类,重写其中的 doCredentialsMatch 方法即可

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.apache.shiro.crypto.hash.SimpleHash;

public class MyCredentialsMatcher extends SimpleCredentialsMatcher {

    /**
     * 重写密码验证器
     * 
     * @param token 用户输入的信息
     * @param info  数据库查询到的信息
     */
    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        System.out.println("进入自定义密码比较器");
        UsernamePasswordToken upt = (UsernamePasswordToken) token;
        String inputName = upt.getUsername();// 用户输入的用户名
        String inputPwd = new String(upt.getPassword());// 用户输入的密码
        String dbPassword = (String) info.getCredentials();// 数据库查询得到的加密后的密码
        // 对用户输入密码进行加密(加密方式,用户输入密码,盐值(用户名),加密次数)
        String encryptionPwd = new SimpleHash("MD5", inputPwd, inputName, 1024).toString();// 加密后的密码
        return equals(encryptionPwd, dbPassword);
    }

}
  1. 第二步,我们需要把注入realm的凭证比较器替换为我们自己的凭证比较器
    @Bean
    public SimpleCredentialsMatcher CredentialsMatcher() {
        MyCredentialsMatcher hct = new MyCredentialsMatcher();//自定义凭证比较器
        //HashedCredentialsMatcher hct = new HashedCredentialsMatcher();//系统提供凭证比较器
        // 加密算法的名称
        hct.setHashAlgorithmName("MD5");
        // 配置加密的次数
        hct.setHashIterations(1024);
        // 是否存储为16进制
        hct.setStoredCredentialsHexEncoded(true);
        return hct;
    }

6.1 测试

控制台打印出了执行了自定义密码
在这里插入图片描述

### 回答1: Spring Boot 集成 Shiro 框架可以实现在应用中实现安全认证、权限控制等功能。下面是大致的集成步骤: 1. 添加 Shiro 依赖 在 `pom.xml` 文件中添加 Shiro 的依赖。可以选择适合自己项目的版本号。 ```xml <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring-boot-starter</artifactId> <version>1.7.1</version> </dependency> ``` 2. 配置 Shiro 在 `application.properties` 或 `application.yml` 文件中添加 Shiro 的相关配置,如 Shiro 的过滤器、安全管理器、Realm 等。 ```yaml # 配置 Shiro 的过滤器 shiro: filter: anon: anon authc: authc # 配置 Shiro 的安全管理器和 Realm shiro: securityManager: realm: myRealm ``` 3. 实现 Realm Realm 是 Shiro 的核心组件之一,需要实现自己的 Realm 类,用于提供认证和授权数据。 ```java public class MyRealm extends AuthorizingRealm { // 认证 @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { // 实现认证逻辑 } // 授权 @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { // 实现授权逻辑 } } ``` 4. 使用 Shiro 在需要进行安全认证、权限控制的地方,可以使用 Shiro 提供的 API 进行操作。 ```java // 获取当前用户的信息 Subject subject = SecurityUtils.getSubject(); Object principal = subject.getPrincipal(); // 判断当前用户是否具有某个角色 boolean hasRole = subject.hasRole("admin"); // 判断当前用户是否具有某个权限 boolean hasPermission = subject.isPermitted("user:update"); ``` 这是一个大致的 Spring Boot 集成 Shiro 的步骤,具体实现方式可以根据自己的需求进行调整。 ### 回答2: Spring Boot 是一个快速开发框架Shiro 是一个安全框架,它们的集成可以帮助开发人员快速构建安全的 Web 应用程序。 为了将 Shiro 集成到 Spring Boot 中,首先需要在 Maven POM 文件中引入 Shiro 的依赖库。例如,以下 POM 文件中添加了 Shiro Spring Boot 的 Starter 依赖库: ``` <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring-boot-starter</artifactId> <version>1.5.0</version> </dependency> ``` 集成过程中,需要在应用程序中添加一个 Shiro 配置类,该类可以加载各种 Shiro 过滤器,用于对 URL 是否需要进行授权认证等操作,示例代码如下: ```java @Configuration public class ShiroConfig { @Bean public ShiroFilterFactoryBean shiroFilter(@Autowired SecurityManager securityManager){ ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean(); bean.setSecurityManager(securityManager); Map<String, String> chains = new HashMap<>(); chains.put("/login", "anon"); chains.put("/css/**", "anon"); chains.put("/js/**", "anon"); chains.put("/**", "authc"); bean.setFilterChainDefinitionMap(chains); return bean; } @Bean public SecurityManager securityManager(@Autowired UserRealm userRealm){ DefaultWebSecurityManager manager = new DefaultWebSecurityManager(); manager.setRealm(userRealm); return manager; } @Bean public UserRealm userRealm(){ return new UserRealm(); } } ``` 在这个例子中,我们为登录页、CSS、JS 等 URL 设置了“anon”过滤器,表示这些 URL 不需要进行认证,而其他 URL 都需要进行认证。此外,我们还提供了一个 UserRealm,用于提供用户的认证和授权。 最后,我们需要在应用程序中启用 Shiro,例如在启动主类里加入 @EnableShiro 注解: ```java @EnableShiro @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 这样,我们就完成了 Shiro集成。使用 Shiro,开发人员可以方便地进行用户认证和授权,保障 Web 应用程序的安全性。 ### 回答3: Spring Boot是一个非常流行的Java Web框架,它可以通过添加各种插件来轻松集成许多其他框架和库。Shiro是一个全面的安全框架,提供了身份验证、授权、密码编码等功能,与Spring Boot的集成也非常容易。 下面是一些简要的步骤来集成Spring Boot和Shiro框架: 1. 首先,需要在pom.xml文件中添加Shiro和Spring Boot Starter Web的依赖: ``` <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.4.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.3.2.RELEASE</version> </dependency> ``` 2. 然后,在应用程序的主类中添加@EnableWebSecurity注解,启用Spring Security的Web安全性支持,同时在configure(HttpSecurity http)方法中配置Shiro的安全过滤器链: ``` @Configuration @EnableWebSecurity public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .csrf() .disable() .authorizeRequests() .antMatchers("/login").permitAll() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/**").authenticated() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login").permitAll() .defaultSuccessUrl("/home.html") .and() .logout() .logoutUrl("/logout").permitAll() .deleteCookies("JSESSIONID") .logoutSuccessUrl("/login"); } @Bean public Realm realm() { return new MyRealm(); } @Bean public DefaultWebSecurityManager securityManager() { DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); securityManager.setRealm(realm()); return securityManager; } @Bean public ShiroFilterFactoryBean shiroFilter() { ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean(); shiroFilter.setSecurityManager(securityManager()); shiroFilter.setLoginUrl("/login"); shiroFilter.setSuccessUrl("/home.html"); shiroFilter.setUnauthorizedUrl("/403.html"); Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>(); filterChainDefinitionMap.put("/login", "anon"); filterChainDefinitionMap.put("/logout", "logout"); filterChainDefinitionMap.put("/admin/**", "authc, roles[admin]"); filterChainDefinitionMap.put("/**", "user"); shiroFilter.setFilterChainDefinitionMap(filterChainDefinitionMap); return shiroFilter; } } ``` 3. 编写自定义的Realm类,用于实现Shiro的身份验证和授权逻辑: ``` public class MyRealm extends AuthorizingRealm { @Autowired private UserService userService; @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); User user = (User) principals.getPrimaryPrincipal(); for (Role role : user.getRoles()) { authorizationInfo.addRole(role.getName()); for (Permission permission : role.getPermissions()) { authorizationInfo.addStringPermission(permission.getPermission()); } } return authorizationInfo; } @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { UsernamePasswordToken upToken = (UsernamePasswordToken) token; String username = upToken.getUsername(); User user = userService.findByUsername(username); if (user != null) { return new SimpleAuthenticationInfo(user, user.getPassword(), getName()); } else { throw new UnknownAccountException(); } } } ``` 4. 最后,在Controller中使用Shiro提供的Subject来实现身份验证和授权: ``` @Controller public class HomeController { @RequestMapping(value = "/home.html", method = RequestMethod.GET) public String home() { Subject currentUser = SecurityUtils.getSubject(); if (currentUser.isAuthenticated()) { return "home"; } else { return "redirect:/login"; } } @RequestMapping(value = "/admin/index.html", method = RequestMethod.GET) public String admin() { Subject currentUser = SecurityUtils.getSubject(); if (currentUser.isAuthenticated() && currentUser.hasRole("admin")) { return "admin"; } else { return "redirect:/login"; } } @RequestMapping(value = "/login", method = RequestMethod.GET) public String login() { return "login"; } } ``` 使用以上步骤实现了Spring Boot集成Shiro框架,完成了基本的身份验证和授权操作。实现后就可以进行测试,通过Shiro的身份验证和授权功能保证系统的安全性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值