本文實例講述了Java開發之spring security實現基于MongoDB的認證功能。分享給大家供大家參考,具體如下:
spring security對基于數據庫的認證支持僅限于JDBC,而很多項目并非使用JDBC,比如Nosql數據庫很多使用的是 Mongo Java Driver,這樣就無法用默認的<jdbc-user-service>進行支持認證。
如果項目不是使用JDBC,沒么解決辦法就是:自己定義一個認證服務。
新建一個CustomUserDetailsService類
這個類實現了UserDetailsService接口。代碼如下:
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
26
27
28
29
30
31
32
|
public class CustomUserDetailsService implements UserDetailsService { @Autowired MongoDBHelper dbhelper; /* * 根據用戶名加載認證用戶 */ @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { //步驟一:從數據庫中查出用戶數據 MongoDatabase db = dbhelper.getDB("huanle"); MongoCollection<Document> users = db.getCollection("user"); Document filter = new Document(); filter.append("account",username); Document result = users.find(filter).first(); if(result==null) throw new UsernameNotFoundException(username+"不存在"); //步驟二:裝配到UserDetails,相當于生成了一個<user>標簽 UserDetails userDetails = new User(result.getString("account"), result.getString("password"), true, true, true, true,getAuthorities(result.getInteger("access")) ); return userDetails; } /** 根據用戶級別,獲得角色列表。比如用戶級別為1,表示該用戶是管理員,則返回ROLE_USER,ROLE_ADMIN * @param access 用戶級別 * @return 用戶角色列表 */ public Collection<GrantedAuthority> getAuthorities( int access){ List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>( 2 ); authList.add( new SimpleGrantedAuthority( "ROLE_USER" )); if (access== 1 ){ authList.add( new SimpleGrantedAuthority( "ROLE_ADMIN" )); } return authList; } } |
修改spring-security.xml文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
< http > < intercept-url pattern = "/user/**" access = "hasRole('USER')" /> < intercept-url pattern = "/admin/**" access = "hasRole('ADMIN')" /> < form-login login-page = "/login" login-processing-url = "/login" authentication-failure-url = "/login?error" default-target-url = "/" username-parameter = "phone" password-parameter = "password" /> < logout invalidate-session = "true" logout-url = "/loginout" logout-success-url = "/login" /> </ http > < authentication-manager > < authentication-provider user-service-ref = "customUserDetailsService" > </ authentication-provider > </ authentication-manager > <!-- 自定義認證服務 --> < beans:bean id = "customUserDetailsService" class = "com.huanle.utils.security.CustomUserDetailsService" ></ beans:bean > |
這里通過<form-login>標簽定義了登錄,其相關屬性說明如下:
屬性 | 說明 |
---|---|
login-page=”/login” | 登錄界面的位置 |
login-processing-url=”/login” | 登錄表單post到“/login” |
authentication-failure-url=”/login?error” | 登錄失敗,重定向到“/login?error” |
default-target-url=”/” | 登錄成功,重定向到“/” |
username-parameter=”phone” | 登錄表單中,名為phone的參數作為認證的username |
password-parameter=”password” | 登錄表單中,名為password的參數作為認證的password |
通過<authentication-provider user-service-ref="customUserDetailsService" >使用我們自定義的認證服務
最后,看一下login.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
<%@ page language= "java" contentType= "text/html; charset=UTF-8" pageEncoding= "UTF-8" %> <% @taglib prefix= "form" uri= "http://www.springframework.org/tags/form" %> <% @taglib prefix= "my" uri= "/WEB-INF/custom.tld" %> <!DOCTYPE html> <html> <head> <meta http-equiv= "Content-Type" content= "text/html; charset=UTF-8" > <title>用戶登錄</title> </head> <body> <form:form action= "/login" method= "post" commandName= "login" > <ul> <li>手機號:<form:input id= "phone" name= "phone" type= "text" path= "phone" /></li> <li>密碼:<form:input id= "password" name= "password" type= "text" path= "password" /></li> <li> <input style= " margin-right:30px; margin-left:70px" type= "submit" value= "登錄" /> </li> </ul> </form:form> </body> </html> |
可見,這個登錄頁面跟平常使用的并無區別,這都要歸功于username-parameter="phone"和password-parameter="password"這兩個配置。
總結
從上面的代碼可見,自定義的用戶認證服務CustomUserDetailsService的唯一任務就是:根據用戶名從數據庫獲取用戶數據,生成一個UserDetails實例。
這個UserDetails實例包含了用戶名和密碼,spring security從這個對象里獲得數據庫里的用戶數據,和從form里提交的用戶名、密碼進行比對,即可認證用戶。
希望本文所述對大家java程序設計有所幫助。
原文鏈接:http://blog.csdn.net/ruangong1203/article/details/51124220