Shiro练习小Demo(SpringBoot)

这个博客演示了如何在SpringBoot项目中结合Mybatis和Shiro进行实践操作。内容包括Shiro的相关组件配置,如自定义登录验证规则、授权类及总的配置文件。此外,博主提供了dao和service层用于获取用户角色权限的方法,并分享了项目的码云下载链接。
摘要由CSDN通过智能技术生成

本Demo是用SpringBoot+Mybatis+Shiro
省略创建SpringBoot的截图流程
导入jar包

 <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-core</artifactId>
            <version>1.4.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.4.0</version>
        </dependency>

整个项目结构

shiro一般都在service(业务层)内
CredentialMatcher类是自定义登陆验证规则
AuthRealm类是每次登陆授权时需要使用的类
shiroConfiguration类是shiro的总配置文件
从大到小的顺序是 shiroConfiguration→AuthRealm→CredentialMatcher

CredentialMatcher

package com.hjy.serivce;

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;

/**
 * 自定义登陆检验规则
 */
public class CredentialMatcher extends SimpleCredentialsMatcher {

    //自定义验证规则
    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        UsernamePasswordToken usernamePasswordToken=(UsernamePasswordToken) token;
        //session的密码
        String password =new String(usernamePasswordToken.getPassword());
        //数据库对应的密码
        String dePassword=info.getCredentials().toString();
        //返回对比结果
        return this.equals(password,dePassword);
    }
}

AuthRealm
PS:我的dao和service只写一个方法就是通过传用户名来查找对应用户角色权限信息

package com.hjy.serivce;

import com.hjy.entity.Permission;
import com.hjy.entity.Role;
import com.hjy.entity.Users;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.Author
非常感谢您的提问,我可以为您提供以下基于shiro安全认证的springboot程序的代码示例: 1. 添加依赖 ```xml <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring-boot-web-starter</artifactId> <version>1.6.0</version> </dependency> ``` 2. 配置shiro ```java @Configuration public class ShiroConfig { // 配置shiro过滤器 @Bean public FilterRegistrationBean<DelegatingFilterProxy> delegatingFilterProxy(){ FilterRegistrationBean<DelegatingFilterProxy> filterRegistrationBean = new FilterRegistrationBean<>(); filterRegistrationBean.setFilter(new DelegatingFilterProxy("shiroFilterFactoryBean")); filterRegistrationBean.addUrlPatterns("/*"); return filterRegistrationBean; } // 配置shiro @Bean(name = "shiroFilterFactoryBean") public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager){ ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); shiroFilterFactoryBean.setSecurityManager(securityManager); shiroFilterFactoryBean.setLoginUrl("/login"); shiroFilterFactoryBean.setUnauthorizedUrl("/error/403"); Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>(); filterChainDefinitionMap.put("/logout", "logout"); filterChainDefinitionMap.put("/static/**", "anon"); filterChainDefinitionMap.put("/login", "anon"); filterChainDefinitionMap.put("/error/**", "anon"); filterChainDefinitionMap.put("/**", "authc"); shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); return shiroFilterFactoryBean; } // 配置SecurityManager @Bean public SecurityManager securityManager(AuthRealm authRealm){ DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); securityManager.setRealm(authRealm); return securityManager; } // 配置Realm @Bean public AuthRealm authRealm(HashedCredentialsMatcher hashedCredentialsMatcher){ AuthRealm authRealm = new AuthRealm(); authRealm.setCacheManager(new MemoryConstrainedCacheManager()); authRealm.setCredentialsMatcher(hashedCredentialsMatcher); return authRealm; } // 配置凭证匹配器 @Bean public HashedCredentialsMatcher hashedCredentialsMatcher(){ HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher(); hashedCredentialsMatcher.setHashAlgorithmName("md5"); hashedCredentialsMatcher.setHashIterations(2); return hashedCredentialsMatcher; } } ``` 3. 实现自定义Realm ```java public class AuthRealm extends AuthenticatingRealm { @Autowired private UserService userService; // 验证用户身份 @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken; String username = token.getUsername(); User user = userService.getUserByUsername(username); if(user == null){ throw new UnknownAccountException(); } return new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(user.getSalt()), getName()); } // 授权 @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); User user = (User) principalCollection.getPrimaryPrincipal(); authorizationInfo.addRole(user.getRole()); authorizationInfo.addStringPermission(user.getPermission()); return authorizationInfo; } } ``` 4. 实现登录接口 ```java @RestController public class LoginController { @PostMapping("/login") public Result login(String username, String password){ Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken(username, password); try{ subject.login(token); }catch (UnknownAccountException e){ return Result.fail("用户名不存在"); }catch (IncorrectCredentialsException e){ return Result.fail("密码错误"); } return Result.success(); } @GetMapping("/logout") public Result logout(){ Subject subject = SecurityUtils.getSubject(); subject.logout(); return Result.success(); } } ``` 以上便是基于shiro安全认证的springboot程序的代码示例,希望能够对您有所帮助。如果您有其他问题,欢迎继续提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值