栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot整合shiro步骤

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot整合shiro步骤

1.创建springboot工程,添加web

2.在maven工程的pom.xml文件中引入shiro-spring-boot-web-starter依赖
    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.apache.shiro
            shiro-spring-boot-web-starter
            1.9.0
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    
3.在application.properties中配置shiro基本配置项
shiro.web.enabled=true
shiro.loginUrl=/login
4.创建shiro配置类:ShiroConfig;并Realm和ShiroFilterChainDefinition 两个@Bean
import org.apache.shiro.realm.Realm;
import org.apache.shiro.realm.text.TextConfigurationRealm;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ShiroConfig {
    @Bean
    Realm realm(){
        TextConfigurationRealm textConfigurationRealm = new TextConfigurationRealm();
        textConfigurationRealm.setUserDefinitions("admin=123,admin n user=123,user");
        return textConfigurationRealm;
    }
    @Bean
    ShiroFilterChainDefinition shiroFilterChainDefinition(){
        DefaultShiroFilterChainDefinition definition = new DefaultShiroFilterChainDefinition();
        definition.addPathDefinition("/doLogin","anon");
        definition.addPathDefinition("/**","authc");
        return definition;
    }
}
6.编写LoginController类进行测试
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController {
    @GetMapping("/login")
    public String login(){
        return "to doLogin";
    }
    @PostMapping("/doLogin")
    public void doLogin(String username,String password){
        Subject subject = SecurityUtils.getSubject();
        try{
            subject.login(new UsernamePasswordToken(username,password));
            System.out.println("login success");
        }catch (AuthenticationException auth){
            System.out.println(auth.getMessage());
        }
    }
    @GetMapping("/hello")
    public String hello(){
        return "hello shiro";
    }
}
7.登录之前,访问http://localhost:8080/hello返回to doLogin

8.登录之后在访问则能够访问到正确的服务。


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1039612.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号