SSM集成Shiro:實現登錄認證

      折騰了好多天,遇到了好多傻逼問題。也在網上找了許多教程。對着人家源碼敲都出問題,最後果斷刪掉之前寫的代碼,重新按照自己的意思來寫。果然,只有自己想的纔是適合自己的啊!結果就實現了認證功能。

重點:要先理解shiro的基礎,我發現一個博客寫的不錯,可以在這看看:點擊打開鏈接   

         實現環境:自己搭建的一個SSM框架下集成Shiro

流程:(當然最重要的是先要配置環境,這個自行百度吧)

1.設計數據庫:一張用戶信息表,最好在往數據庫裏添加數據的時候,密碼那塊用MD5+salt加密,Shiro也提供了這個加密功能, 只要不被人家發現你的salt,原則上是破解不了的。

  2.編寫Mybatis查詢的xml文件和常見Dao接口

3.在service層實現數據查詢

4.自定義一個realm,在這裏實現登錄認證

5.在web層實現將用戶輸入的賬號和密碼保存到Shrio的token中,並調用login()方法將數據傳到AuthenticationToken

6.編寫前端頁面


下面開始貼代碼:(只貼關於登錄驗證那塊的代碼,其餘的servie層,Dao層的寫法就不說了,有點mvc和框架基礎的人都知道該怎麼寫的)


自定義的realm:實現根據token的內容往數據庫查找到相應的信息,然後調用認證方法執行認證操作

public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private ShiroUserService userService;

    //登錄認證
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        String username= (String) authenticationToken.getPrincipal();
        User user=userService.queryUser(username);
        if(user==null){
            return null;
        }
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username,user.getPassword(),
                ByteSource.Util.bytes(user.getSalt()),this.getName());
        return simpleAuthenticationInfo;
    }

    //授權
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }


}


web層寫法:在這裏將用戶名和密碼傳到token裏並執行login方法

 @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String login(HttpServletRequest request, Model model){
        CustomException customException=null;
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        if((username!=null && password!=null)){
            UsernamePasswordToken token=new UsernamePasswordToken(username,password);
            Subject subject= SecurityUtils.getSubject();
            try{
                subject.login(token);
            }catch (AuthenticationException e){
                customException=new CustomException(e.getMessage());
            }
            if( subject.isAuthenticated()){
                subject.logout();
                System.out.println("認證成功");
                model.addAttribute("username",username);
                return "/loginsuccess";
            }else {
                model.addAttribute("exception",customException.getMessage());
                return "/refuse";
            }
        }
        return "login";
    }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章