1.自定義realm,在shiro的配置類中加入以下bean
1
2
3
4
5
6
7
8
9
|
/** * 身份認證 realm */ @bean public myshirorealm myshirorealm(){ myshirorealm myshirorealm = new myshirorealm(); system.out.println( "myshirorealm 注入成功" ); return myshirorealm; } |
2.重寫方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
// 身份認證 @override protected authenticationinfo dogetauthenticationinfo(authenticationtoken authenticationtoken) throws authenticationexception { string username = (string) authenticationtoken.getprincipal(); system.out.println( "myshirorealm.....dogetauthenticationinfo" ); userinfo user= null ; try { user = iuserinfoservice.findbyusername(username); } catch (exception e){ e.printstacktrace(); } if (user== null ){ return null ; } // 進行驗證,將正確數(shù)據(jù)講給shiro處理 simpleauthenticationinfo authenticationinfo = new simpleauthenticationinfo( user, user.getpassword(), bytesource.util.bytes(user.getcredentialssalt()), // 加鹽后的密碼 getname() // 指定當前 realm 的類名 ); // 返回給安全管理器,由 securitymanager 比對密碼的正確性 return authenticationinfo; } |
需要注意的是simpleauthenticationinfo 類,我們需要把數(shù)據(jù)交給他,格式為(用戶,用戶密碼,鹽,當前realm的類名)
1
2
3
4
5
6
7
|
// 進行驗證,將正確數(shù)據(jù)講給shiro處理 simpleauthenticationinfo authenticationinfo = new simpleauthenticationinfo( user, user.getpassword(), bytesource.util.bytes(user.getcredentialssalt()), // 加鹽后的密碼 getname() // 指定當前 realm 的類名 ); |
3.你還需要告訴shiro你是經(jīng)過加密的,在config內(nèi)新建如下bean
1
2
3
4
5
6
7
8
9
10
|
@bean public hashedcredentialsmatcher hashedcredentialsmatcher(){ hashedcredentialsmatcher hashedcredentialsmatcher = new hashedcredentialsmatcher(); // 使用md5 算法進行加密 hashedcredentialsmatcher.sethashalgorithmname( "md5" ); // 設置散列次數(shù): 意為加密幾次 hashedcredentialsmatcher.sethashiterations( 2 ); return hashedcredentialsmatcher; } |
并注冊:
1
2
3
4
5
6
7
8
|
@bean public myshirorealm myshirorealm(){ myshirorealm myshirorealm = new myshirorealm(); // 配置 加密 (在加密后,不配置的話會導致登陸密碼失敗) myshirorealm.setcredentialsmatcher(hashedcredentialsmatcher()); //+++++++++++ system.out.println( "myshirorealm 注入成功" ); return myshirorealm; } |
總結
以上所述是小編給大家介紹的springboot整合shiro之加鹽md5加密的方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網(wǎng)站的支持!
原文鏈接:https://blog.csdn.net/qq_37163479/article/details/84752298