-
导入依赖
<!-- Subject 用户 SecurityManager 管理所有用户 Realm 连接数据库 --> <!--shiro整合spring的包--> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>xxx</version> </dependency>
-
编写自定义类
//自定义的UserRealm public class UserRealm extends AuthorizingRealm { //授权 @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { System.out.println("执行了=>授权doGetAuthorizationInfo"); return null; } //认证 @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { System.out.println("执行了=>认证doGetAuthorizationInfo"); return null; } }
-
编写配置类ShiroConfig
@Configuration public class ShiroConfig { //3. shiroFilterFactoryBean @Bean public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("getDefaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager) { ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean(); // 设置安全管理器 bean.setSecurityManager(defaultWebSecurityManager); return bean; } //2. DefaultWebSecurityManager @Bean public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) { DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); // 关联userRealm securityManager.setRealm(userRealm); return securityManager; } //1. 创建realm对象,需要自定义类 @Bean public UserRealm userRealm() { return new UserRealm(); } }
-
shiro实现登录拦截(就是你得先登录才能访问我的其他页面),在ShiroConfig中的getShiroFilterFactoryBean方法中添加如下配置
/* anon: 无需认证就可以访问 authc: 必须认证了才能访问 user: 必须拥有记住我功能才能用 perms: 拥有对某个资源的权限才能访问 role: 拥有某个角色权限 */ Map<String, String> filterMap = new LinkedHashMap<>(); //filterMap.put("/user/add","authc"); //filterMap.put("/user/update","authc"); filterMap.put("/user/*","authc"); bean.setFilterChainDefinitionMap(filterMap); //如果没有权限就跳转到登录页面 //设置登录的请求 bean.setLoginUrl("/toLogin");
-
Shiro实现用户认证(就是登录的过程,通过身份认证,登录,验证用户是不是拥有相应的身份)
- controller中编写相应内容
@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);//执行登录的方法,如果没有异常就说明ok了 return "index"; } catch (UnknownAccountException e) {//用户名不存在 model.addAttribute("msg","用户名错误"); return "login"; } catch (IncorrectCredentialsException e) {//密码不存在 model.addAttribute("msg","密码错误"); return "login"; } }
- 编写UserRealm中的认证
//认证 @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { System.out.println("执行了=>认证doGetAuthorizationInfo"); // 用户名、密码, 数据库中取 String name = "root"; String password = "123456"; UsernamePasswordToken userToken = (UsernamePasswordToken) token; if (!userToken.getUsername().equals(name)) { return null;//抛出异常 UnknownAccountException } // 密码认证,shiro做 return new SimpleAuthenticationInfo("",password,""); }