springboot整合shior框架

Shiro是一个Java安全框架,支持身份认证,授权和会话管理等功能。要将Shiro集成到Java Web应用程序中,您需要完成以下步骤:

  1. 在您的项目的依赖中添加Shiro库(shiro-core和shiro-web)

  2. 在您的web.xml中配置Shiro过滤器,以便在每个请求之前先执行Shiro认证和授权逻辑

  3. 在您的程序中编写Shiro Realm来处理用户身份验证和角色/权限授权逻辑

  4. 在您的程序中使用Shiro API来管理会话和执行其他安全相关操作

下面是一个简单的示例配置:

1.在pom.xml文件中添加以下依赖:

<dependency>
   <groupId>org.apache.shiro</groupId>
   <artifactId>shiro-core</artifactId>
   <version>1.7.1</version>
</dependency>
<dependency>
   <groupId>org.apache.shiro</groupId>
   <artifactId>shiro-web</artifactId>
   <version>1.7.1</version>
</dependency>

2.在web.xml中添加以下配置:

<filter>
   <filter-name>shiroFilter</filter-name>
   <filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class>
</filter>
​
<filter-mapping>
   <filter-name>shiroFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>

1.编写自定义的Shiro Realm类。这个类需要实现org.apache.shiro.realm.Realm接口,并重写其中的方法,包括获取用户信息,检查密码,获取用户的角色和权限列表等。

public class MyRealm implements Realm {
​
   @Override
   public String getName() {
      return "MyRealm";
   }
​
   @Override
   public boolean supports(AuthenticationToken token) {
      return token instanceof UsernamePasswordToken;
   }
​
   @Override
   public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
      String username = (String) token.getPrincipal();
      String password = new String((char[]) token.getCredentials());
​
      // 从数据库或其他源获取用户信息并验证密码
      if ("user".equals(username) && "password".equals(password)) {
         return new SimpleAuthenticationInfo(username, password, getName());
      } else {
         throw new AuthenticationException("用户名或密码不正确");
      }
   }
​
   @Override
   public AuthorizationInfo getAuthorizationInfo(PrincipalCollection principals) {
      String username = (String) principals.getPrimaryPrincipal();
​
      // 从数据库或其他源获取用户的角色和权限信息
      SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
      info.addRole("admin");
      info.addStringPermission("user:create");
      return info;
   }
}

1.然后您就可以在程序中使用Shiro API来进行身份认证和授权了,例如:

public void login(String username, String password) {
   // 将用户名和密码封装到UsernamePasswordToken中,然后调用Subject进行认证
   UsernamePasswordToken token = new UsernamePasswordToken(username, password);
   Subject currentUser = SecurityUtils.getSubject();
   currentUser.login(token);
}
​
public void checkPermission(String permission) {
   // 调用Subject的isPermitted方法检查当前用户是否具有指定的权限
   Subject currentUser = SecurityUtils.getSubject();
   if (currentUser.isPermitted(permission)) {
      // 允许操作
   } else {
      // 拒绝操作
   }
}
​
public void checkRole(String role) {
   // 调用Subject的hasRole方法检查当前用户是否具有指定的角色
   Subject currentUser = SecurityUtils.getSubject();
   if (currentUser.hasRole(role)) {
      // 允许操作
   } else {
      // 拒绝操作
   }
}

今天就到这里吧!小步快跑、大家一起加油哦!

猜你喜欢

转载自blog.csdn.net/weixin_70855192/article/details/130148647