简单三步理解Shiro权限验证/登录

通过请求方式来判断是初始请求还是验证请求
一、

@RequestMapping(value = "/login", method = RequestMethod.GET)
    public String showLoginPage() {
        return "user/login";
    }
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String submitLoginForm(User user, HttpServletRequest request,
            Model model) {
        String errorClassName = (String) request
                .getAttribute("shiroLoginFailure");
        String authticationError = null;
        if (UnknownAccountException.class.getName().equals(errorClassName)) {
            authticationError = "用户名/密码错误";
        } else if (IncorrectCredentialsException.class.getName().equals(
                errorClassName)) {
            authticationError = "用户名/密码错误";
        } else if (errorClassName != null) {
            authticationError = "未知错误:" + errorClassName;
        }
        model.addAttribute("authticationError", authticationError);
        return showLoginPage();
    }


Shiro配置文件中进行请求拦截管理
二、

------------------------------------------------------第一种配置方式---------------------------------------------------
 
     id="credentialsMatcher" class="com.zhu.prototype.shiro.credential.PlainPasswordMatcher">
    
     id="jdbcRealm" class="org.apache.shiro.realm.jdbc.JdbcRealm">
         name="credentialsMatcher" ref="credentialsMatcher">
         name="authenticationQuery" value="select password from user where username = ?">
         name="dataSource" ref="dataSource">
    
    
     id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
         name="realms">
            
                 bean="jdbcRealm" />
            
        
    
    
     id="formAuthenticationFilter" class="org.apache.shiro.web.filter.authc.FormAuthenticationFilter">
         name="usernameParam" value="username" />
         name="passwordParam" value="password" />
         name="loginUrl" value="/login" />       --------------------- 释放login请求
         name="successUrl" value="/news/newsList">    -----------------------验证成功时释放的请求
    


------------------------------------------------------第二种配置方式(chang---------------------------------------------------

xml version = "1.0" encoding = "UTF-8" ?>
< beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd"
     default-lazy-init = "true" >
 
     < description >Shiro安全配置 description >
    
    
     < bean id = "securityManager" class = "org.apache.shiro.web.mgt.DefaultWebSecurityManager" >
         < property name = "realm" ref = "shiroDbRealm" />
         < property name = "cacheManager" ref = "shiroEhcacheManager" />
     bean >
 
    
     < bean id = "shiroDbRealm" class = "scau.mis.sexyone.service.member.impl.ShiroDbRealm" depends-on = "staffDao,roleDao" >
         < property name = "accountService" ref = "accountService" />
     bean >
     
    
     < bean id = "shiroFilter" class = "org.apache.shiro.spring.web.ShiroFilterFactoryBean" >
         < property name = "securityManager" ref = "securityManager" /
         < property name = "loginUrl" value = "/login" />---------释放login请求
         < property name = "successUrl" value = "/" />-----------释放验证成功时的请求
         < property name = "filterChainDefinitions" >
             < value >
                 /logout = logout
                 /account/** = user
                 /** = authc
             value >
         property >
     bean >
 
    
     < bean id = "shiroEhcacheManager" class = "org.apache.shiro.cache.ehcache.EhCacheManager" >
         < property name = "cacheManagerConfigFile" value = "classpath:security/ehcache-shiro.xml" />
     bean >
     
    
     < bean id = "lifecycleBeanPostProcessor" class = "org.apache.shiro.spring.LifecycleBeanPostProcessor" />
     
    
     < bean class = "org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on = "lifecycleBeanPostProcessor" >
         < property name = "proxyTargetClass" value = "true" />
     bean >
     < bean class = "org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor" >
         < property name = "securityManager" ref = "securityManager" />
     bean >
beans >




三、

public class ShiroDbRealm extends AuthorizingRealm{
 
     protected AccountService accountService;
     @Autowired
     public void setAccountService(AccountService accountService) {
         this .accountService = accountService;
     }
     /**
      *授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
      */
     @Override
     protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
         ShiroUser shiroUser = (ShiroUser) principals.getPrimaryPrincipal();
         Staff staff = accountService.findUserByLoginName(shiroUser.loginName);
         SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
         for (Role role : staff.getRoles()) {
             //基于Role的权限信息
             info.addRole(role.getName());
             //基于Permission的权限信息
             info.addStringPermissions(role.getPermissionList());
         }
         return info;
     }
     
     /**
      * 登录时调用
      */
     @Override
     protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
         UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
         Staff staff= null ;
         staff = accountService.findUserByLoginName(token.getUsername());
         System.out.println( "username" +token.getUsername());
         System.out.println( "password" + new String(token.getPassword()));
         if (staff != null ) {
             if (staff.getStatus().equals( "disabled" )) {
                 throw new DisabledAccountException();
             }
 
//          byte[] salt = Encodes.decodeHex(staff.getSalt());
             return new SimpleAuthenticationInfo(
                     new ShiroUser(staff.getLoginname(), staff.getName()),
                     staff.getPassword(),
//                  ByteSource.Util.bytes(salt),
                     getName());
         } else {
             return null ;
         }
     }
}





如果抛出IncorrectCredentialsException (错误的凭证) ---------多数是没有密码

你可能感兴趣的:(帮助博文)