隨筆簡介
1、spring版本:4.3.2.RELEASE+spring security 版本:4.1.2.RELEASE(其它不做說明)
2、所展示內(nèi)容全部用注解配置
3、springmvc已經(jīng)配置好,不作說明
4、會涉及到springmvc,spel,el的東西,不熟悉的同學可以先去看一下這方面內(nèi)容,特別是springmvc
首先想一下,登陸需要什么,最簡單的情況下,用戶名,密碼,然后比對數(shù)據(jù)庫,如果吻合就跳轉到個人頁面,否則回到登陸頁面,并且提示用戶名密碼錯誤。這個過程中應該還帶有權限角色,并且貫穿整個會話。有了這個思路,我們只需要把數(shù)據(jù)庫的用戶名密碼交給spring security比對,再讓security進行相關跳轉,并且讓security幫我們把權限角色和用戶名貫穿整個會話,實際上,我們只需要提供正確的用戶名和密碼,以及配置下security。
目錄
準備工作
登陸頁面
個人頁面
開始配置spring security
1.啟動spring security
2.配置權限
3.編寫UserDetailService
首先準備數(shù)據(jù)庫表
1
2
3
4
5
6
7
|
CREATE TABLE ` user ` ( `username` varchar (255) NOT NULL , ` password ` char (255) NOT NULL , `roles` enum( 'MEMBER' , 'MEMBER,LEADER' , 'SUPER_ADMIN' ) NOT NULL DEFAULT 'MEMBER' , PRIMARY KEY (`username`), KEY `username` (`username`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; |
PS:這里注意的是roles的內(nèi)容,LEADER也是MEMBER,這樣做,LEADER就擁有MEMBER的權限,當然你也可以在應用里面作判斷,這個后面會說到。
登陸頁面
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form"%> < html > < head > < title >登錄</ title > </ head > < body > < div > < sf:form action = "${pageContext.request.contextPath}/log" method = "POST" commandName = "user" > <!-- spring表單標簽,用于模型綁定和自動添加隱藏的CSRF token標簽 --> < h1 >登錄</ h1 > < c:if test = "${error==true}" >< p style = "color: red" >錯誤的帳號或密碼</ p ></ c:if > <!-- 登陸失敗會顯示這句話 --> < c:if test = "${logout==true}" >< p >已退出登錄</ p ></ c:if > <!-- 退出登陸會顯示這句話 --> < sf:input path = "username" name = "user.username" placeholder = "輸入帳號" />< br /> < sf:password path = "password" name = "user.password" placeholder = "輸入密碼" />< br /> < input id = "remember-me" name = "remember-me" type = "checkbox" /> <!-- 是否記住我功能勾選框 --> < label for = "remember-me" >一周內(nèi)記住我</ label > < input type = "submit" class = "sumbit" value = "提交" > </ sf:form > </ div > </ body > </ html > |
個人頁面
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false"%> <%@taglib prefix="security" uri="http://www.springframework.org/security/tags" %> <%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form"%> < html > < head > < title >歡迎你,< security:authentication property = "principal.username" var = "username" />${username}</ title > <!-- 登陸成功會顯示名字,這里var保存用戶名字到username變量,下面就可以通過EL獲取 --> </ head > < body > < security:authorize access = "isAuthenticated()" >< h3 >登錄成功!${username}</ h3 ></ security:authorize > <!-- 登陸成功會顯示名字 --> < security:authorize access = "hasRole('MEMBER')" > <!-- MENBER角色就會顯示 security:authorize標簽里的內(nèi)容--> < p >你是MENBER</ p > </ security:authorize > < security:authorize access = "hasRole('LEADER')" > < p >你是LEADER</ p > </ security:authorize > < sf:form id = "logoutForm" action = "${pageContext.request.contextPath}/logout" method = "post" > <!-- 登出按鈕,注意這里是post,get是會登出失敗的 --> < a href = "#" onclick = "document.getElementById('logoutForm').submit();" >注銷</ a > </ sf:form > </ body > </ html > |
開始配置spring security
1.啟動spring security
1
2
3
|
@Order ( 2 ) public class WebSecurityAppInit extends AbstractSecurityWebApplicationInitializer{ } |
繼承AbstractSecurityWebApplicationInitializer,spring security會自動進行準備工作,這里@Order(2)是之前我springmvc(也是純注解配置)和spring security一起啟動出錯,具體是什么我忘了,加這個讓security啟動在后,可以避免這個問題,如果不寫@Order(2)沒有錯就不用管。
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
26
27
28
29
30
31
32
33
34
35
36
37
38
|
@Configuration @EnableWebSecurity @ComponentScan ( "com.chuanzhi.workspace.service.impl.*" ) public class WebSecurityConfig extends WebSecurityConfigurerAdapter{ @Autowired private UserDetailService userDetailService; //如果userDetailService沒有掃描到就加上面的@ComponentScan @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers( "/me" ).hasAnyRole( "MEMBER" , "SUPER_ADMIN" ) //個人首頁只允許擁有MENBER,SUPER_ADMIN角色的用戶訪問 .anyRequest().authenticated() .and() .formLogin() .loginPage( "/" ).permitAll() //這里程序默認路徑就是登陸頁面,允許所有人進行登陸 .loginProcessingUrl( "/log" ) //登陸提交的處理url .failureForwardUrl( "/?error=true" ) //登陸失敗進行轉發(fā),這里回到登陸頁面,參數(shù)error可以告知登陸狀態(tài) .defaultSuccessUrl( "/me" ) //登陸成功的url,這里去到個人首頁 .and() .logout().logoutUrl( "/logout" ).permitAll().logoutSuccessUrl( "/?logout=true" ) //按順序,第一個是登出的url,security會攔截這個url進行處理,所以登出不需要我們實現(xiàn),第二個是登出url,logout告知登陸狀態(tài) .and() .rememberMe() .tokenValiditySeconds( 604800 ) //記住我功能,cookies有限期是一周 .rememberMeParameter( "remember-me" ) //登陸時是否激活記住我功能的參數(shù)名字,在登陸頁面有展示 .rememberMeCookieName( "workspace" ); //cookies的名字,登陸后可以通過瀏覽器查看cookies名字 } @Override public void configure(WebSecurity web) throws Exception { super .configure(web); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailService); //配置自定義userDetailService } } |
3.編寫UserDetailService
spring security提供給我們的獲取用戶信息的Service,主要給security提供驗證用戶的信息,這里我們就可以自定義自己的需求了,我這個就是根據(jù)username從數(shù)據(jù)庫獲取該用戶的信息,然后交給security進行后續(xù)處理
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
33
34
35
36
|
@Service (value = "userDetailService" ) public class UserDetailService implements UserDetailsService { @Autowired private UserRepository repository; public UserDetailService(UserRepository userRepository){ this .repository = userRepository; //用戶倉庫,這里不作說明了 } public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = repository.findUserByUsername(username); if (user== null ) throw new UsernameNotFoundException( "找不到該賬戶信息!" ); //拋出異常,會根據(jù)配置跳到登錄失敗頁面 List<GrantedAuthority> list = new ArrayList<GrantedAuthority>(); //GrantedAuthority是security提供的權限類, getRoles(user,list); //獲取角色,放到list里面 org.springframework.security.core.userdetails.User auth_user = new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),list); //返回包括權限角色的User給security return auth_user; } /** * 獲取所屬角色 * @param user * @param list */ public void getRoles(User user,List<GrantedAuthority> list){ for (String role:user.getRoles().split( "," )) { list.add( new SimpleGrantedAuthority( "ROLE_" +role)); //權限如果前綴是ROLE_,security就會認為這是個角色信息,而不是權限,例如ROLE_MENBER就是MENBER角色,CAN_SEND就是CAN_SEND權限 } } } |
如果你想在記住我功能有效情況下,在下次進入登陸頁面直接跳到個人首頁可以看一下這個控制器代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
/** * 登錄頁面 * @param * @return */ @RequestMapping (value = "/" ) public String login(Model model,User user , @RequestParam (value = "error" ,required = false ) boolean error , @RequestParam (value = "logout" ,required = false ) boolean logout,HttpServletRequest request){ model.addAttribute(user); //如果已經(jīng)登陸跳轉到個人首頁 Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication!= null && !authentication.getPrincipal().equals( "anonymousUser" )&& authentication.isAuthenticated()) return "me" ; if (error== true ) model.addAttribute( "error" ,error); if (logout== true ) model.addAttribute( "logout" ,logout); return "login" ; } |
結果展示:
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。