隨筆簡介
先想清楚登入需要什麼。最簡單的情況:使用者名稱、密碼,與資料庫比對,吻合就進個人頁面,否則回登入頁並提示帳號密碼錯誤。這個過程裡還帶著貫穿整個工作階段(session)的權限角色。
有了這個思路,事情就單純了:把資料庫的帳號密碼交給 Spring Security 比對,讓它負責跳轉,也讓它幫我們把權限角色與使用者名稱貫穿整個工作階段。我們實際上只需要提供正確的帳號密碼,再設定好 Security。
目錄:準備工作 → 登入頁面 → 個人頁面 → 啟動 Security → 配置權限 → 撰寫 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;
這裡要注意 roles 的設計:LEADER 同時也是 MEMBER,如此一來 LEADER 自然擁有 MEMBER 的權限。當然你也可以在應用層自行判斷。
1 <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
2 <%@ taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core"%>
3 <%@ taglib prefix="sf" uri="https://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="https://www.springframework.org/security/tags" %>
<%@ taglib prefix="sf" uri="https://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')">
<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>
@Order(2)
public class WebSecurityAppInit extends AbstractSecurityWebApplicationInitializer {
}
繼承 AbstractSecurityWebApplicationInitializer,Security 會自動完成準備工作。這裡的 @Order(2) 是因為先前 SpringMVC(同樣純注解配置)與 Security 一起啟動時出錯,加上它讓 Security 晚一點啟動即可避開;若不加也沒報錯,那就不用管。
@Configuration
@EnableWebSecurity
@ComponentScan("com.chuanzhi.workspace.service.impl.*")
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailService userDetailService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/me").hasAnyRole("MEMBER", "SUPER_ADMIN") // 個人首頁限定角色
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/").permitAll() // 默認路徑就是登陸頁面
.loginProcessingUrl("/log") // 登陸表單處理url
.failureForwardUrl("/?error=true") // 登陸失敗轉發
.defaultSuccessUrl("/me") // 登陸成功跳轉
.and()
.logout().logoutUrl("/logout").permitAll().logoutSuccessUrl("/?logout=true")
.and()
.rememberMe()
.tokenValiditySeconds(604800) // cookies 有效期一周
.rememberMeParameter("remember-me") // 激活記住我的參數名
.rememberMeCookieName("workspace"); // cookies 的名稱
}
@Override
public void configure(WebSecurity web) throws Exception {
super.configure(web);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailService);
}
}
這是 Spring 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 User user = repository.findUserByUsername(username);
13 if (user == null)
14 throw new UsernameNotFoundException("找不到該賬戶信息!");
15
16 List<GrantedAuthority> list = new ArrayList<GrantedAuthority>();
17 getRoles(user, list);
18
19 org.springframework.security.core.userdetails.User auth_user = new
20 org.springframework.security.core.userdetails.User(
21 user.getUsername(), user.getPassword(), list);
22 return auth_user;
23 }
24
25 /**
26 * 獲取所屬角色
27 */
28 public void getRoles(User user, List<GrantedAuthority> list) {
29 for (String role : user.getRoles().split(",")) {
30 // 前綴 ROLE_ 會被視為角色,例如 ROLE_MEMBER 即 MEMBER 角色
31 list.add(new SimpleGrantedAuthority("ROLE_" + role));
32 }
33 }
34 }
若希望「記住我」生效後,下次進入登入頁直接導向個人首頁,可以參考這個控制器:
1 @RequestMapping(value = "/")
2 public String login(Model model, User user,
3 @RequestParam(value = "error", required = false) boolean error,
4 @RequestParam(value = "logout", required = false) boolean logout,
5 HttpServletRequest request) {
6 model.addAttribute(user);
7 // 如果已經登陸跳轉到個人首頁
8 Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
9 if (authentication != null
10 && !authentication.getPrincipal().equals("anonymouSUSEr")
11 && authentication.isAuthenticated())
12 return "me";
13 if (error == true)
14 model.addAttribute("error", error);
15 if (logout == true)
16 model.addAttribute("logout", logout);
17 return "login";
18 }
延伸閱讀:Spring Security 學習筆記 https://www.linuxidc.com/Linux/2016-10/135820.htm ;Spring Security3.1高級詳細開發指南 https://www.linuxidc.com/Linux/2016-05/131482.htm ;數據庫認證 https://www.linuxidc.com/Linux/2014-02/97407.htm ;LDAP認證 https://www.linuxidc.com/Linux/2014-02/97406.htm ;OpenID認證 https://www.linuxidc.com/Linux/2014-02/97405.htm ;X.509認證 https://www.linuxidc.com/Linux/2014-02/97404.htm ;HTTP基本認證和摘要認證 https://www.linuxidc.com/Linux/2014-02/97403.htm ;HTTP表單驗證 https://www.linuxidc.com/Linux/2014-02/97402.htm ;You must provide a configuration attribute 異常處理 https://www.linuxidc.com/Linux/2015-02/113364.htm