1、依赖
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.10.0</version>
</dependency>
2、配置类
public class UserRealm extends AuthorizingRealm {
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
return null;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
return null;
}
}
@Configuration
public class ShiroConfig {
//shiroFilterFactoryBean
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager){
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
bean.setSecurityManager(securityManager);
//内置拦截器
//anon 无需认证
//authc 必须认证
//user 必须有记住我功能
//perms 拥有对某个资源权限才能访问
//role 具有某种角色
//登录拦截
Map<String, String> filterMap = new HashMap<>();
filterMap.put("/level1", "authc");
filterMap.put("/level2", "anon");
bean.setFilterChainDefinitionMap(filterMap);
//设置登录的请求
bean.setLoginUrl("/login");
return bean;
}
//DefaultWebSecurityManager
//安全管理器
@Bean("securityManager")
public DefaultWebSecurityManager securityManager(@Qualifier("userRealm") UserRealm userRealm){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(userRealm);
return securityManager;
}
//realm对象
@Bean("userRealm")
public UserRealm userRealm(){
return new UserRealm();
}
}
用户认证
@RequestMapping("/login")
public String login(String username, String password, Model model){
//获取当前的用户
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
try{
subject.login(token);
return "index";
} catch (UnknownAccountException e){
model.addAttribute("msg", "用户名不存在");
return "login";
} catch (IncorrectCredentialsException e){
model.addAttribute("msg", "密码错误");
return "login";
}
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
String username = token.getUsername();
String user = "root";
String pwd = "1234";
if(!username.equals(user)){
return null;
}
return new SimpleAuthenticationInfo("",pwd,"");
}
标签:return,String,securityManager,使用,new,login,public,shiro
From: https://www.cnblogs.com/yanshiheng/p/16991013.html