整合Shiro第二种方式
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring-boot-web-starter</artifactId>
<version>1.5.3</version>
</dependency>
# 允许将session放到cookie中
shiro.sessionManager.sessionIdCookieEnabled=true
#是否允许将 sessionId 放到 Url 地址拦中
shiro.sessionManager.sessionIdUrlRewritingEnabled=true
#第三行表示访问未获授权的页面时,默认的跳转路径
shiro.unauthorizedUrl=/unauthorizedurl
#第四行表示开启 shiro
shiro.web.enabled=true
#第五行表示登录成功的跳转页面
shiro.successUrl=/index
#第六行表示登录页面
shiro.loginUrl=/login
@Configuration
public class ShiroConfig {
@Bean
Realm realm(){
TextConfigurationRealm realm = new TextConfigurationRealm();
realm.setUserDefinitions("admin=123,admin\n user=123,user");
realm.setRoleDefinitions("admin=read,write \n user=read");
return realm;
}
@Bean
ShiroFilterChainDefinition shiroFilterChainDefinition() {
DefaultShiroFilterChainDefinition definition = new DefaultShiroFilterChainDefinition();
definition.addPathDefinition("/dologin", "anon");
definition.addPathDefinition("/**", "authc");
return definition;
}
}
@RestController
public class HelloController {
@GetMapping("/login")
public String login() {
return "please login";
}
@PostMapping("/dologin")
public String dologin(String username,String password) {
Subject subject = SecurityUtils.getSubject();
try {
subject.login(new UsernamePasswordToken(username,password));
return "success";
} catch (AuthenticationException e) {
e.printStackTrace();
return e.getMessage();
}
}
@GetMapping("/welcome")
public String hello(){
return "hello";
}
}
这里的配置和前面的比较像,但是不再需要 ShiroFilterFactoryBean 实例了,替代它的是 ShiroFilterChainDefinition ,在这里定义 Shiro 的路径匹配规则即可。