整合权限认证
package com.aa.test.config; import com.aa.test.shiro.MyRealm; import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition; import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class ShiroConfig { @Autowired private MyRealm myRealm; @Bean public DefaultWebSecurityManager securityManager(){ DefaultWebSecurityManager defaultWebSecurityManager=new DefaultWebSecurityManager(); defaultWebSecurityManager.setRealm(myRealm); return defaultWebSecurityManager; } //自定义shiro过滤器 public ShiroFilterChainDefinition filterChainDefinition(){ DefaultShiroFilterChainDefinition filterChainDefinition=new DefaultShiroFilterChainDefinition(); //代表的是这个路径不认证也可以访问 filterChainDefinition.addPathDefinition("/login","anon"); //代表的是除了上面这个可以放行,其他的必须认证之后才能放行 filterChainDefinition.addPathDefinition("/**","authc"); return filterChainDefinition; } }
package com.aa.test.shiro; import com.aa.test.pojo.User; import com.aa.test.service.UserService; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.realm.AuthenticatingRealm; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class MyRealm extends AuthorizingRealm { @Autowired private UserService userService; //授权 @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { return null; } //认证 @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { //获取用户信息 Object principal = token.getPrincipal(); //根据用户名获取数据库中用户信息 User user = userService.selUserInfoService((String) principal); if(user!=null){ AuthenticationInfo info = new SimpleAuthenticationInfo(principal, user.getPwd(), user.getUname()); return info; } return null; } }
//使用shiro认证 @RequestMapping("userLogin2") public String userLogin2(String uname,String pwd){ Subject subject = SecurityUtils.getSubject(); AuthenticationToken token = new UsernamePasswordToken(uname, pwd); try { subject.login(token); return "redirect:main"; }catch (Exception e){ e.printStackTrace(); } return "redirect:login"; }