您的位置:首页 > 编程语言 > Java开发

spring boot 学习笔记— shirosrping boot整合shiro

2020-06-29 04:31 555 查看

spring boot — shirosrping boot 整合 shiro

一、搭建环境

必需依赖 spring boot 集成 shiro

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

创建配置类 ShiroConfig.java

以下都写在

ShiroConfig.java

注意:

ShiroConfig.java
使用
@Configuration
注解

  • Shiro过滤器配置
@Bean(name = "shiroFilter")
public ShiroFilterFactoryBean shiroFilter() {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager());
shiroFilterFactoryBean.setLoginUrl("/login");
shiroFilterFactoryBean.setUnauthorizedUrl("/notRole");
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
// <!-- authc:所有url都必须认证通过才可以访问; anon:所有url都都可以匿名访问-->
filterChainDefinitionMap.put("/webjars/**", "anon");
filterChainDefinitionMap.put("/login", "anon");

filterChainDefinitionMap.put("/admin/**", "authc");
filterChainDefinitionMap.put("/user/**", "authc");
//主要这行代码必须放在所有权限设置的最后,不然会导致所有 url 都被拦截 剩余的都需要认证
filterChainDefinitionMap.put("/**", "authc");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;

}
  • 创建SecurityManager 安全管理器
@Bean
public DefaultWebSecurityManager securityManager() {
DefaultWebSecurityManager defaultSecurityManager = new 		DefaultWebSecurityManager();
//将自定义realm 给SecurityManager  管理
defaultSecurityManager.setRealm(customRealm());
return defaultSecurityManager;
}
  • 创建自定义realm
@Bean
public CustomRealm customRealm( ) {
CustomRealm customRealm = new CustomRealm();
customRealm.setCredentialsMatcher(hashedCredentialsMatcher());//密码管理器
return customRealm;
}
  • 密码管理器配置
@Bean
public HashedCredentialsMatcher hashedCredentialsMatcher() {
//Shiro自带加密
HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
//散列算法使用md5
credentialsMatcher.setHashAlgorithmName("md5");
//散列次数,2表示md5加密两次
credentialsMatcher.setHashIterations(2);
//是否存储为16进制
credentialsMatcher.setStoredCredentialsHexEncoded(true);
return credentialsMatcher;
}
  • 使用thymeleaf shiro标签
@Bean(name = "shiroDialect")
public ShiroDialect shiroDialect(){
return new ShiroDialect();
}
  • 开启shiro注解 导入依赖
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
@Bean
public AuthorizationAttributeSourceAdvisor getAuthorizationAttributeSourceAdvisor(SecurityManager securityManager){
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
return authorizationAttributeSourceAdvisor;
}

创建自定义realm

public class CustomRealm extends AuthorizingRealm {
@Autowired
UserService userService;

@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
ActiveUser activeUser= (ActiveUser) principalCollection.getPrimaryPrincipal();
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//设置角色
info.addRoles(activeUser.getRoles());
//设置权限
info.addStringPermissions(activeUser.getFunctions());
return info;
}

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
String userName = (String) authenticationToken.getPrincipal();
**************************************************************************
//通过username 在数据库中查询到 user
User user= userService.findUsers(userName);
//用户列表
List<String> user_roles=new ArrayList<String>();
//权限列表
List<String> function_roles=new ArrayList<String>();
ActiveUser activeUser=null;
if(null!=user){
List<Role> roles=user.getRoleList();
//获取用户  权限列表
for(int i=0;i<roles.size();i++){
Role role=roles.get(i);
user_roles.add(role.getRole_name());
List<Function> functions=role.getFunctionList();
for (int j=0;j<functions.size();j++){
Function function=functions.get(j);
function_roles.add(function.getPermission());
}
}
activeUser=new ActiveUser(user,user_roles,function_roles);
***************************************************************************
ByteSource salt= ByteSource.Util.bytes(user.getSalt());
return new SimpleAuthenticationInfo(activeUser, user.getPassword(),salt,getName());
}else{
throw new AccountException("用户名不正确");
}

}
}

这里的相关只是参考shiro 入门

shiro在thymeleaf中的常用标签

  • 引入shiro 标签
<html xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
  • 验证当前用户是否为“访客”,即未认证(包含未记住)的用户
<p shiro:guest="">Please <a href="login.html">login</a></p>
  • 认证通过或已记住的用户
<p shiro:user="">
Welcome back John! Not John? Click <a href="login.html">here</a> to login.
</p>
  • 已认证通过的用户。不包含已记住的用户,这是与user标签的区别所在
<p shiro:authenticated="">
Hello, <span shiro:principal=""></span>, how are you today?
</p>
<a shiro:authenticated="" href="updateAccount.html">Update your contact information</a>
  • 输出当前用户信息,通常为登录帐号信息
<p>Hello, <shiro:principal/>, how are you today?</p>
  • 未认证通过用户,与authenticated标签相对应。与guest标签的区别是,该标签包含已记住用户
<p shiro:notAuthenticated="">
Please <a href="login.html">login</a> in order to update your credit card information.
</p>
  • 验证当前用户是否属于该角色
<a shiro:hasRole="admin" href="admin.html">Administer the system</a>

拥有该角色才显示a 标签

  • 与hasRole标签逻辑相反,当用户不属于该角色时验证通过
<p shiro:lacksRole="developer"><!-- 没有该角色 -->
Sorry, you are not allowed to developer the system.
</p>
  • 验证当前用户是否属于以下所有角色
<p shiro:hasAllRoles="developer, admin"><!-- 角色与判断 -->
You are a developer and a admin.
</p>
  • 验证当前用户是否属于以下任意一个角色
<p shiro:hasAnyRoles="admin, vip, developer"><!-- 角色或判断 -->
You are a admin, vip, or developer.
</p>
  • 验证当前用户是否拥有指定权限
<a shiro:hasPermission="userInfo:add" href="createUser.html">添加用户</a>
  • 与hasPermission标签逻辑相反,当前用户没有制定权限时,验证通过
<p shiro:lacksPermission="userInfo:del"><!-- 没有权限 -->
Sorry, you are not allowed to delete user accounts.
</p>
  • 验证当前用户是否拥有以下所有角色
<p shiro:hasAllPermissions="userInfo:view, userInfo:add"><!-- 权限与判断 -->
You can see or add users.
</p>
  • 验证当前用户是否拥有以下任意一个权限
<p shiro:hasAnyPermissions="userInfo:view, userInfo:del"><!-- 权限或判断 -->
You can see or delete users.
</p>

这里相关参考 shiro在thymeleaf中的常用标签

使用

@Controller
public class UserController {

@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(@RequestParam("username") String username, @RequestParam("password") String password) {
// 从SecurityUtils里边创建一个 subject
Subject subject = SecurityUtils.getSubject();
// 在认证提交前准备 token(令牌)
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
// 执行认证登陆
try {
subject.login(token);
} catch (AuthenticationException ae) {
return "error";
}//可以多个catch 详细判断
if (subject.isAuthenticated()) {
return "redirect:/index";

} else {
token.clear();
return "error";
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: