SSM集成Shiro进行权限控制:认证,授权!

1.spring-shiro.xml

spring集成shiro的相关配置




    
    
        
        
    

    
    

    
    
        
    
    
    

    
    
    
    

    
        
    

    
    

        
        
        
        
        
        
        
        
            
            
                /statics/**=anon
                /login.html=anon
                /welcom.html=authc
            
        

    

2.web.xml

 
    
        shiroFilter
        org.springframework.web.filter.DelegatingFilterProxy
        
            targetFilterLifecycle
            true
        
    
    
        shiroFilter
        /*
    

3.自定义Realm

 Realm 获取安全数据(如用户、角色、权限),并进行认证,授权

public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {

        String username= (String) SecurityUtils.getSubject().getPrincipal();
        Set roles=new HashSet();
        Set menus=new HashSet();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //通过用户id查询用户角色
        //通过用户id查询用户权限

        // 角色加入AuthorizationInfo认证对象
        info.setRoles(roles);
        // 权限加入AuthorizationInfo认证对象
        info.setStringPermissions(menus);
        return info;
    }

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //将token转换为usernamepasswordToken
        UsernamePasswordToken token= (UsernamePasswordToken) authenticationToken;
        //获取token中的登录账户
        String username = token.getUsername();
        //查询数据库,是否存在指定的用户名和密码的用户
        User user = userService.findByUsername(username);
        if (user==null){
            throw new UnknownAccountException("账户"+username+"不存在");
        }
        //如果查询到了,封装查询结果
        String principal = user.getUsername();
        String credentials  = user.getPassword();
        String realmName = this.getName();
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(principal, credentials, realmName);
        //返回给调用login(token)方法
        return info;
    }
}

4.controller

@RequestMapping("/login")
    public String login(User user){

        //创建subject实例对象
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()==false){
            UsernamePasswordToken token=new UsernamePasswordToken(user.getUsername(),user.getPassword());
            try{
                subject.login(token);
            }catch (AuthenticationException e){
                e.getMessage();
                e.printStackTrace();
                System.out.println("登录失败");
                return "login";
            }
        }
        return "index";

    }

 

你可能感兴趣的:(SSM)