Spring Boot中整合Shiro实现安全认证控制

紫色蔷薇 2023-02-24 ⋅ 19 阅读

在一个Web应用程序中,安全认证是一项至关重要的任务。它涉及到用户的登录、身份验证和权限控制等方面。Spring Boot提供了与Shiro框架的集成,使得在应用程序中实现安全认证更加方便和灵活。

1. 引入依赖

首先,在项目的pom.xml文件中添加Shiro和Spring Boot的相关依赖:

<dependencies>
  ...
  <dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring-boot-starter</artifactId>
    <version>1.7.1</version>
  </dependency>
  ...
</dependencies>

2. 配置Shiro

在Spring Boot应用程序的配置文件中,添加以下Shiro配置:

spring:
  shiro:
    # 配置Shiro的Realm
    realm: com.example.MyRealm
    
    # 配置登录页面的URL
    loginUrl: /login
    
    # 配置不需要进行权限认证的URL
    # 可以使用Ant风格的路径匹配模式
    anon:
      - /public/**
      
    # 配置拦截到未授权请求时跳转的URL
    unauthorizedUrl: /unauthorized

3. 自定义Realm

创建一个自定义的Realm类,继承AuthorizingRealm类,并实现相关的认证和授权方法:

public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    // 用户认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal();
        User user = userService.getUserByUsername(username);
        if (user == null) {
            throw new UnknownAccountException("用户不存在");
        }
        return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), getName());
    }

    // 用户授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String) principalCollection.getPrimaryPrincipal();
        Set<Role> roles = userService.getUserRolesByUsername(username);
        Set<String> permissions = new HashSet<>();
        for (Role role : roles) {
            permissions.addAll(role.getPermissions());
        }
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(roles.stream().map(Role::getName).collect(Collectors.toSet()));
        authorizationInfo.setStringPermissions(permissions);
        return authorizationInfo;
    }
}

4. 编写Controller

在Spring Boot应用程序中编写一个Controller,用于处理登录、注销和其他受权限控制的请求:

@Controller
public class UserController {

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @PostMapping("/login")
    public String doLogin(String username, String password) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        subject.login(token);
        return "redirect:/home";
    }

    @GetMapping("/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login";
    }

    @GetMapping("/home")
    public String home() {
        return "home";
    }

    @GetMapping("/admin")
    @RequiresPermissions("admin")
    public String admin() {
        return "admin";
    }
}

5. 编写登录页面

resources/templates目录下创建一个login.html文件,作为登录页面的模板:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>
<h1>Login</h1>
<form action="/login" method="post">
    <input type="text" name="username" placeholder="Username" required>
    <br>
    <input type="password" name="password" placeholder="Password" required>
    <br>
    <input type="submit" value="Login">
</form>
</body>
</html>

6. 编写未授权页面

resources/templates目录下创建一个unauthorized.html文件,作为未授权页面的模板:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Unauthorized</title>
</head>
<body>
<h1>Unauthorized</h1>
<p>You don't have permission to access this page.</p>
</body>
</html>

7. 运行应用程序

现在,您可以编译并运行Spring Boot应用程序。访问http://localhost:8080/login即可进入登录页面,输入正确的用户名和密码后,将导航到主页/home

如果访问http://localhost:8080/admin,您将被重定向到未授权页面/unauthorized,因为该URL需要admin权限才能访问。

结论

通过整合Spring Boot和Shiro,我们可以轻松地实现安全认证和权限控制。在此博客中,我们了解了如何配置Shiro、使用自定义的Realm类以及编写相应的Controller和页面。希望这个博客能够帮助您在Spring Boot应用程序中实现安全认证控制。


全部评论: 0

    我有话说: