1. 首页
  2. 软件开发
  3. Shiro——没有角色无法访问、获取角色进行验证、获取权限进行验证以及异常处理

Shiro——没有角色无法访问、获取角色进行验证、获取权限进行验证以及异常处理

  • 发布于 2024-08-17
  • 0 次阅读

在Shiro中,可以通过角色认证来控制用户对资源的访问权限。如果用户没有特定角色或权限,可以配置Shiro抛出相应的异常进行处理。

1. 创建自定义Realm

创建一个自定义的Realm,实现角色认证和权限获取逻辑。

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

public class CustomRealm extends AuthorizingRealm {
   

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
   
        String username = (String) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        
        // 从数据库中获取用户的角色信息和权限信息
        Set<String> roles = userService.getRolesByUsername(username);
        authorizationInfo.setRoles(roles);
        
        Set<String> permissions = userService.getPermissionsByUsername(username);
        authorizationInfo.setStringPermissions(permissions);
        
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
   
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String username = usernamePasswordToken.getUsername();
        String password = new String(usernamePasswordToken.getPassword());

        // 从数据库中查询用户信息
        User user = userService.getUserByUsername(username);
        if (user == null) {
   
            throw new UnknownAccountException("用户名不存在");
        }
        if (!password.equals(user.getPassword())) {
   
            throw new IncorrectCredentialsException("密码错误");
        }

        return new SimpleAuthenticationInfo(username, password, getName());
    }
}

2. 配置Shiro

在Shiro配置类中配置自定义Realm和异常处理器。

import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ShiroConfig {
   

    @Bean
    public SecurityManager securityManager(Realm customRealm) {
   
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(customRealm);
        securityManager.setAuthenticator(authenticator());
        return securityManager;
    }

    @Bean
    public CustomRealm customRealm() {
   
        return new CustomRealm();
    }

    @Bean
    public ModularityRealmAuthenticator authenticator() {
   
        ModularityRealmAuthenticator authenticator = new ModularityRealmAuthenticator();
        authenticator.setAuthenticationStrategy(new AtLeastOneSuccessfulStrategy());
        return authenticator;
    }

    @Bean
    public UserService userService() {
   
        return new UserService();
    }
}

3. Controller中进行角色和权限验证

在Controller中获取当前用户的角色和权限信息,并进行角色和权限验证。

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {
   

    @GetMapping("/admin")
    public String adminPage() {
   
        Subject currentUser = SecurityUtils.getSubject();
        
        // 验证用户是否具有admin角色
        if (currentUser.hasRole("admin")) {
   
            return "Welcome Admin!";
        } else {
   
            throw new UnauthorizedException("Unauthorized access");
        }
    }

    @GetMapping("/read")
    public String readPage() {
   
        Subject currentUser = SecurityUtils.getSubject();
        
        // 验证用户是否具有read权限
        if (currentUser.isPermitted("read")) {
   
            return "Read Page";
        } else {
   
            throw new UnauthorizedException("Unauthorized access");
        }
    }
}

通过以上代码示例,展示了如何在Shiro中实现角色认证、获取角色进行验证、获取权限进行验证以及异常处理的功能。

原文链接: https://blog.csdn.net/2401_82884096/article/details/138367464