隨筆簡介
首先想一下,登陸需要什麼,最簡單的情況下,用戶名,密碼,然後比對數據庫,如果吻合就跳轉到個人頁面,否則回到登陸頁面,並且提示用戶名密碼錯誤。這個過程中應該還帶有權限角色,並且貫穿整個會話。有了這個思路,我們只需要把數據庫的用戶名密碼交給spring security比對,再讓security進行相關跳轉,並且讓security幫我們把權限角色和用戶名貫穿整個會話,實際上,我們只需要提供正確的用戶名和密碼,以及配置下security。
目錄
1.啟動spring security
2.配置權限
3.編寫UserDetailService
首先准備數據庫表
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的內容,LEADER也是MEMBER,這樣做,LEADER就擁有MEMBER的權限,當然你也可以在應用裡面作判斷,這個後面會說到。
登陸頁面
1 <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
2 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
3 <%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
4 <html>
5 <head>
6 <title>登錄</title>
7 </head>
8 <body>
9 <div >
10
11 <sf:form action="${pageContext.request.contextPath}/log" method="POST" commandName="user"> <!-- spring表單標簽,用於模型綁定和自動添加隱藏的CSRF token標簽 -->
12 <h1 >登錄</h1>
13 <c:if test="${error==true}"><p >錯誤的帳號或密碼</p></c:if> <!-- 登陸失敗會顯示這句話 -->
14 <c:if test="${logout==true}"><p >已退出登錄</p></c:if> <!-- 退出登陸會顯示這句話 -->
15 <sf:input path="username" name="user.username" placeholder="輸入帳號" /><br />
16 <sf:password path="password" name="user.password" placeholder="輸入密碼" /><br />
17 <input id="remember-me" name="remember-me" type="checkbox"/> <!-- 是否記住我功能勾選框 -->
18 <label for="remember-me">一周內記住我</label>
19 <input type="submit" class="sumbit" value="提交" >
20 </sf:form>
21 </div>
22 </body>
23 </html>
個人頁面
<%@ 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標簽裡的內容-->
<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
@Order(2)
public class WebSecurityAppInit extends AbstractSecurityWebApplicationInitializer{
}
繼承AbstractSecurityWebApplicationInitializer,spring security會自動進行准備工作,這裡@Order(2)是之前我springmvc(也是純注解配置)和spring security一起啟動出錯,具體是什麼我忘了,加這個讓security啟動在後,可以避免這個問題,如果不寫@Order(2)沒有錯就不用管。
2.配置權限
@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") //登陸失敗進行轉發,這裡回到登陸頁面,參數error可以告知登陸狀態
.defaultSuccessUrl("/me") //登陸成功的url,這裡去到個人首頁
.and()
.logout().logoutUrl("/logout").permitAll().logoutSuccessUrl("/?logout=true") //按順序,第一個是登出的url,security會攔截這個url進行處理,所以登出不需要我們實現,第二個是登出url,logout告知登陸狀態
.and()
.rememberMe()
.tokenValiditySeconds(604800) //記住我功能,cookies有限期是一周
.rememberMeParameter("remember-me") //登陸時是否激活記住我功能的參數名字,在登陸頁面有展示
.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提供驗證用戶的信息,這裡我們就可以自定義自己的需求了,我這個就是根據username從數據庫獲取該用戶的信息,然後交給security進行後續處理
1 @Service(value = "userDetailService")
2 public class UserDetailService implements UserDetailsService {
3
4 @Autowired
5 private UserRepository repository;
6
7 public UserDetailService(UserRepository userRepository){
8 this.repository = userRepository; //用戶倉庫,這裡不作說明了
9 }
10
11 public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
12
13 User user = repository.findUserByUsername(username);
14 if (user==null)
15 throw new UsernameNotFoundException("找不到該賬戶信息!"); //拋出異常,會根據配置跳到登錄失敗頁面
16
17 List<GrantedAuthority> list = new ArrayList<GrantedAuthority>(); //GrantedAuthority是security提供的權限類,
18
19 getRoles(user,list); //獲取角色,放到list裡面
20
21 org.springframework.security.core.userdetails.User auth_user = new
22 org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),list); //返回包括權限角色的User給security
23 return auth_user;
24 }
25
26 /**
27 * 獲取所屬角色
28 * @param user
29 * @param list
30 */
31 public void getRoles(User user,List<GrantedAuthority> list){
32 for (String role:user.getRoles().split(",")) {
33 list.add(new SimpleGrantedAuthority("ROLE_"+role)); //權限如果前綴是ROLE_,security就會認為這是個角色信息,而不是權限,例如ROLE_MENBER就是MENBER角色,CAN_SEND就是CAN_SEND權限
34 }
35 }
36 }
如果你想在記住我功能有效情況下,在下次進入登陸頁面直接跳到個人首頁可以看一下這個控制器代碼
1 /**
2 * 登錄頁面
3 * @param
4 * @return
5 */
6 @RequestMapping(value = "/")
7 public String login(Model model,User user
8 ,@RequestParam(value = "error",required = false) boolean error
9 ,@RequestParam(value = "logout",required = false) boolean logout,HttpServletRequest request){
10 model.addAttribute(user);
11 //如果已經登陸跳轉到個人首頁
12 Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
13 if(authentication!=null&&
14 !authentication.getPrincipal().equals("anonymouSUSEr")&&
15 authentication.isAuthenticated())
16 return "me";
17 if(error==true)
18 model.addAttribute("error",error);
19 if(logout==true)
20 model.addAttribute("logout",logout);
21 return "login";
22 }
Spring Security 學習筆記 http://www.linuxidc.com/Linux/2016-10/135820.htm
Spring Security3.1高級詳細開發指南 PDF http://www.linuxidc.com/Linux/2016-05/131482.htm
Spring Security 學習之數據庫認證 http://www.linuxidc.com/Linux/2014-02/97407.htm
Spring Security 學習之LDAP認證 http://www.linuxidc.com/Linux/2014-02/97406.htm
Spring Security 學習之OpenID認證 http://www.linuxidc.com/Linux/2014-02/97405.htm
Spring Security 學習之X.509認證 http://www.linuxidc.com/Linux/2014-02/97404.htm
Spring Security 學習之HTTP基本認證和HTTP摘要認證 http://www.linuxidc.com/Linux/2014-02/97403.htm
Spring Security 學習之HTTP表單驗證 http://www.linuxidc.com/Linux/2014-02/97402.htm
Spring Security異常之You must provide a configuration attribute http://www.linuxidc.com/Linux/2015-02/113364.htm
Spring Security 的詳細介紹:請點這裡
Spring Security 的下載地址:請點這裡