springboot安全框架-shiro

springboot安全框架-shiro

1.创建项目添加依赖
 有了shiro-spring-boot-web-starter依赖,我们就不需要添加spring-boot-starter-web 
          <!-- shiro-->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring-boot-web-starter</artifactId>
            <version>1.4.0</version>
        </dependency>

        <!-- 引入thymeleaf依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <!---thymeleaf中使用shiro标签-->
        <dependency>
            <groupId>com.github.theborakompanioni</groupId>
            <artifactId>thymeleaf-extras-shiro</artifactId>
            <version>2.0.0</version>
        </dependency>
2.shiro配置
server.port=8036
server.servlet.context-path=/springboot-shiro
#shiro配置
shiro.enabled=true
shiro.web.enabled=true
shiro.loginUrl=/login
shiro.successUrl=/index
shiro.unauthorizedUrl=/unauthorized
#表示允许通过cookie进行会话跟踪
shiro.sessionManager.sessionIdCookieEnabled=true
#表示是否允许通过url参数进行会话跟踪
shiro.sessionManager.sessionIdUrlRewritingEnabled=true
3.java中配置shiro
@Configuration
public class ShiroConfig {
    @Bean
    public Realm realm(){
        TextConfigurationRealm realm = new TextConfigurationRealm();
        //设置账户和角色
        realm.setUserDefinitions("liushao=123,user\n admin=123,admin");
        //授予角色权限
        realm.setRoleDefinitions("admin=read,write\n user=read");
        return realm;
    }
    @Bean
    public ShiroDialect shiroDialect(){//支持thymeleaf中使用shiro
        return new ShiroDialect();
    }
    @Bean
    public ShiroFilterChainDefinition shiroFilterChainDefinition(){
        DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition();
        chainDefinition.addPathDefinition("/login","anon");//任何人都可以访问
        chainDefinition.addPathDefinition("/doLogin","anon");//
        chainDefinition.addPathDefinition("/logout","logout");//注销
        chainDefinition.addPathDefinition("/**","authc");//登陆后可以访问
        return chainDefinition;
    }
}
4.控制器和视图的绑定
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        //让控制器和页面对应上
        registry.addViewController("/login").setViewName("login");
        registry.addViewController("/index").setViewName("index");
      	registry.addViewController("/unauthorized").setViewName("unauthorized");
    }
}
5.全局异常处理
@ControllerAdvice
public class ExceptionController {

    public ModelAndView error(AuthorizationException e){
        ModelAndView view = new ModelAndView("unauthorized");
        //没有权限
        view.addObject("error",e.getMessage());
        return view;
    }
}
6.前端页面
6.1.login.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="doLogin" method="post">
    <input type="text" name="username"  />
    <input type="password" name="password" />
    <input type="submit" value="登录" />
</form>

<div th:text="${error}"></div>
</body>
</html>
6.2.index.html
<!DOCTYPE html>
<html lang="en" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>hello,<shiro:principal/></h1>
<h2><a href="logout">注销</a></h2>
<hr/>
<h3><a shiro:hasRole="admin" href="admin">管理员用户</a></h3>
<h3><a shiro:hasAnyRoles="admin,user" href="user">普通用户界面</a></h3>
</body>
</html>
6.3.unauthorized
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
未授权,非法访问
<h1 th:text="${error}"></h1>
</body>
</html>
6.4.admin.html &&user.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
管理员用户
</body>
</html>
====================================
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
普通用户
</body>
</html>
7控制器
@Controller
public class UserController {
    @PostMapping("/doLogin")//表单提交用了post
    public String doLogin(String username, String password, Model model){
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        //Subject对象看作一个用户,同样的它也有可能是一个第三方程序
        //它是一个抽象的概念,可以理解任何东西与任何系统的交互的东西
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
        }catch (Exception ex){
            model.addAttribute("error","用户名或密码错误");
            ex.printStackTrace();
            return "login";
        }
        return "redirect:index";
    }
    @RequiresRoles("admin")
    @GetMapping("/admin")
    public String admin(){
        return "admin";
    }
    /**
     * 具有其中一个角色即可访问user页面
     * @return
     */
    @RequiresRoles(value = {"admin","user"},logical = Logical.OR)
    @GetMapping("/user")
    public String user(){
        return "user";
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值