1. 程式人生 > >SSM整合Shiro:實現登入認證

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";
    }