SpringBoot Security前后端分離登錄驗(yàn)證的實(shí)現(xiàn)
最近一段時(shí)間在研究OAuth2的使用,想整個(gè)單點(diǎn)登錄,從網(wǎng)上找了很多demo都沒有實(shí)施成功,也許是因?yàn)閴焊筒欢甇Auth2的原理導(dǎo)致。有那么幾天,越來越?jīng)]有頭緒,又不能放棄,轉(zhuǎn)過頭來一想,OAuth2是在Security的基礎(chǔ)上擴(kuò)展的,對(duì)于Security自己都是一無所知,干脆就先研究一下Security吧,先把Security搭建起來,找找感覺。
說干就干,在現(xiàn)成的SpringBoot 2.1.4.RELEASE環(huán)境下,進(jìn)行Security的使用。簡(jiǎn)單的Security的使用就不說了,目前的項(xiàng)目是前后端分離的,登錄成功或者失敗返回的數(shù)據(jù)格式必須JSON形式的,未登錄時(shí)也需要返回JSON格式的提示信息 ,退出時(shí)一樣需要返回JSON格式的數(shù)據(jù)。授權(quán)先不管,先返回JSON格式的數(shù)據(jù),這一個(gè)搞定,也研究了好幾天,翻看了很多別人的經(jīng)驗(yàn),別人的經(jīng)驗(yàn)有的看得懂,有的看不懂,關(guān)鍵時(shí)刻還需要自己研究呀。
下面,上代碼:
第一步,在pom.xml中引入Security配置文件
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
第二步,增加Configuration配置文件
import java.io.PrintWriter;import java.util.HashMap;import java.util.Map;import javax.servlet.http.HttpServletResponse;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.http.HttpMethod;import org.springframework.security.authentication.AuthenticationProvider;import org.springframework.security.authentication.BadCredentialsException;import org.springframework.security.authentication.DisabledException;import org.springframework.security.authentication.dao.DaoAuthenticationProvider;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.builders.WebSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;import org.springframework.security.core.userdetails.UserDetailsService;import org.springframework.security.core.userdetails.UsernameNotFoundException;import com.fasterxml.jackson.databind.ObjectMapper;/** * 參考網(wǎng)址: * https://blog.csdn.net/XlxfyzsFdblj/article/details/82083443 * https://blog.csdn.net/lizc_lizc/article/details/84059004 * https://blog.csdn.net/XlxfyzsFdblj/article/details/82084183 * https://blog.csdn.net/weixin_36451151/article/details/83868891 * 查找了很多文件,有用的還有有的,感謝他們的辛勤付出 * Security配置文件,項(xiàng)目啟動(dòng)時(shí)就加載了 * @author 程就人生 * */@Configurationpublic class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private MyPasswordEncoder myPasswordEncoder; @Autowired private UserDetailsService myCustomUserService; @Autowired private ObjectMapper objectMapper; @Override protected void configure(HttpSecurity http) throws Exception { http .authenticationProvider(authenticationProvider()) .httpBasic() //未登錄時(shí),進(jìn)行json格式的提示,很喜歡這種寫法,不用單獨(dú)寫一個(gè)又一個(gè)的類 .authenticationEntryPoint((request,response,authException) -> { response.setContentType('application/json;charset=utf-8'); response.setStatus(HttpServletResponse.SC_FORBIDDEN); PrintWriter out = response.getWriter(); Map<String,Object> map = new HashMap<String,Object>(); map.put('code',403); map.put('message','未登錄'); out.write(objectMapper.writeValueAsString(map)); out.flush(); out.close(); }) .and() .authorizeRequests() .anyRequest().authenticated() //必須授權(quán)才能范圍 .and() .formLogin() //使用自帶的登錄 .permitAll() //登錄失敗,返回json .failureHandler((request,response,ex) -> { response.setContentType('application/json;charset=utf-8'); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); PrintWriter out = response.getWriter(); Map<String,Object> map = new HashMap<String,Object>(); map.put('code',401); if (ex instanceof UsernameNotFoundException || ex instanceof BadCredentialsException) { map.put('message','用戶名或密碼錯(cuò)誤'); } else if (ex instanceof DisabledException) { map.put('message','賬戶被禁用'); } else { map.put('message','登錄失敗!'); } out.write(objectMapper.writeValueAsString(map)); out.flush(); out.close(); }) //登錄成功,返回json .successHandler((request,response,authentication) -> { Map<String,Object> map = new HashMap<String,Object>(); map.put('code',200); map.put('message','登錄成功'); map.put('data',authentication); response.setContentType('application/json;charset=utf-8'); PrintWriter out = response.getWriter(); out.write(objectMapper.writeValueAsString(map)); out.flush(); out.close(); }) .and() .exceptionHandling() //沒有權(quán)限,返回json .accessDeniedHandler((request,response,ex) -> { response.setContentType('application/json;charset=utf-8'); response.setStatus(HttpServletResponse.SC_FORBIDDEN); PrintWriter out = response.getWriter(); Map<String,Object> map = new HashMap<String,Object>(); map.put('code',403); map.put('message', '權(quán)限不足'); out.write(objectMapper.writeValueAsString(map)); out.flush(); out.close(); }) .and() .logout() //退出成功,返回json .logoutSuccessHandler((request,response,authentication) -> { Map<String,Object> map = new HashMap<String,Object>(); map.put('code',200); map.put('message','退出成功'); map.put('data',authentication); response.setContentType('application/json;charset=utf-8'); PrintWriter out = response.getWriter(); out.write(objectMapper.writeValueAsString(map)); out.flush(); out.close(); }) .permitAll(); //開啟跨域訪問 http.cors().disable(); //開啟模擬請(qǐng)求,比如API POST測(cè)試工具的測(cè)試,不開啟時(shí),API POST為報(bào)403錯(cuò)誤 http.csrf().disable(); } @Override public void configure(WebSecurity web) { //對(duì)于在header里面增加token等類似情況,放行所有OPTIONS請(qǐng)求。 web.ignoring().antMatchers(HttpMethod.OPTIONS, '/**'); } @Bean public AuthenticationProvider authenticationProvider() { DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider(); //對(duì)默認(rèn)的UserDetailsService進(jìn)行覆蓋 authenticationProvider.setUserDetailsService(myCustomUserService); authenticationProvider.setPasswordEncoder(myPasswordEncoder); return authenticationProvider; } }
第三步,實(shí)現(xiàn)UserDetailsService接口
import org.springframework.security.core.userdetails.UserDetails;import org.springframework.security.core.userdetails.UserDetailsService;import org.springframework.security.core.userdetails.UsernameNotFoundException;import org.springframework.stereotype.Component;/** * 登錄專用類 * 自定義類,實(shí)現(xiàn)了UserDetailsService接口,用戶登錄時(shí)調(diào)用的第一類 * @author 程就人生 * */@Componentpublic class MyCustomUserService implements UserDetailsService { /** * 登陸驗(yàn)證時(shí),通過username獲取用戶的所有權(quán)限信息 * 并返回UserDetails放到spring的全局緩存SecurityContextHolder中,以供授權(quán)器使用 */ @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { //在這里可以自己調(diào)用數(shù)據(jù)庫(kù),對(duì)username進(jìn)行查詢,看看在數(shù)據(jù)庫(kù)中是否存在 MyUserDetails myUserDetail = new MyUserDetails(); myUserDetail.setUsername(username); myUserDetail.setPassword('123456'); return myUserDetail; }}
說明:這個(gè)類,主要是用來接收登錄傳遞過來的用戶名,然后可以在這里擴(kuò)展,查詢?cè)撚脩裘跀?shù)據(jù)庫(kù)中是否存在,不存在時(shí),可以拋出異常。本測(cè)試為了演示,把數(shù)據(jù)寫死了。
第四步,實(shí)現(xiàn)PasswordEncoder接口
import org.springframework.security.crypto.password.PasswordEncoder;import org.springframework.stereotype.Component;/** * 自定義的密碼加密方法,實(shí)現(xiàn)了PasswordEncoder接口 * @author 程就人生 * */@Componentpublic class MyPasswordEncoder implements PasswordEncoder { @Override public String encode(CharSequence charSequence) { //加密方法可以根據(jù)自己的需要修改 return charSequence.toString(); } @Override public boolean matches(CharSequence charSequence, String s) { return encode(charSequence).equals(s); }}
說明:這個(gè)類主要是對(duì)密碼加密的處理,以及用戶傳遞過來的密碼和數(shù)據(jù)庫(kù)密碼(UserDetailsService中的密碼)進(jìn)行比對(duì)。
第五步,實(shí)現(xiàn)UserDetails接口
import java.util.Collection;import org.springframework.security.core.GrantedAuthority;import org.springframework.security.core.userdetails.UserDetails;import org.springframework.stereotype.Component;/** * 實(shí)現(xiàn)了UserDetails接口,只留必需的屬性,也可添加自己需要的屬性 * @author 程就人生 * */@Componentpublic class MyUserDetails implements UserDetails { /** * */ private static final long serialVersionUID = 1L; //登錄用戶名 private String username; //登錄密碼 private String password; private Collection<? extends GrantedAuthority> authorities; public void setUsername(String username) { this.username = username; } public void setPassword(String password) { this.password = password; } public void setAuthorities(Collection<? extends GrantedAuthority> authorities) { this.authorities = authorities; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return this.authorities; } @Override public String getPassword() { return this.password; } @Override public String getUsername() { return this.username; } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; }}
說明:這個(gè)類是用來存儲(chǔ)登錄成功后的用戶數(shù)據(jù),登錄成功后,可以使用下列代碼獲取:
MyUserDetails myUserDetails= (MyUserDetails) SecurityContextHolder.getContext().getAuthentication() .getPrincipal();
代碼寫完了,接下來需要測(cè)試一下,經(jīng)過測(cè)試才能證明代碼的有效性,先用瀏覽器吧。
第一步測(cè)試,未登錄前訪問index,頁(yè)面直接重定向到默認(rèn)的login頁(yè)面了,測(cè)試接口OK。
圖-1
第二步測(cè)試,登錄login后,返回了json數(shù)據(jù),測(cè)試結(jié)果OK。
圖-2
第三步測(cè)試,訪問index,返回輸出的登錄數(shù)據(jù),測(cè)試結(jié)果OK。
圖-3
第四步,訪問logout,返回json數(shù)據(jù),測(cè)試接口OK。
圖-4
第五步,用API POST測(cè)試,用這個(gè)工具模擬ajax請(qǐng)求,看請(qǐng)求結(jié)果如何,首先訪問index,這個(gè)必須登錄后才能訪問。測(cè)試結(jié)果ok,返回了我們需要的JSON格式數(shù)據(jù)。
圖-5
第六步,在登錄模擬對(duì)話框,設(shè)置環(huán)境變量,以保持登錄狀態(tài)。
圖-6
**第七步,登錄測(cè)試,返回JSON格式的數(shù)據(jù),測(cè)試結(jié)果OK。
圖-7
第八步,在返回到index測(cè)試窗口,發(fā)送請(qǐng)求,返回當(dāng)前用戶JSON格式的信息,測(cè)試結(jié)果OK。
圖-8
第九步,測(cè)試退出,返回JSON格式數(shù)據(jù),測(cè)試結(jié)果OK
圖-9
第十步,退出后,再訪問index,出現(xiàn)問題,登錄信息還在,LOOK!
圖-10
把頭部的header前面的勾去掉,也就是去掉cookie,這時(shí)正常了,原因很簡(jiǎn)單,在退出時(shí),沒有清除cookie,這個(gè)只能到正式的環(huán)境上去測(cè)了。API POST再怎么模擬還是和正式環(huán)境有區(qū)別的。
如果在API POST測(cè)試報(bào)403錯(cuò)誤,那就需要把configuration配置文件里的
//開啟跨域訪問http.cors().disable();//開啟模擬請(qǐng)求,比如API POST測(cè)試工具的測(cè)試,不開啟時(shí),API POST為報(bào)403錯(cuò)誤http.csrf().disable();
到此這篇關(guān)于SpringBoot Security前后端分離登錄驗(yàn)證的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)SpringBoot Security登錄驗(yàn)證內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. ajax請(qǐng)求添加自定義header參數(shù)代碼2. ASP基礎(chǔ)知識(shí)VBScript基本元素講解3. 解決android studio引用遠(yuǎn)程倉(cāng)庫(kù)下載慢(JCenter下載慢)4. Kotlin + Flow 實(shí)現(xiàn)Android 應(yīng)用初始化任務(wù)啟動(dòng)庫(kù)5. Python requests庫(kù)參數(shù)提交的注意事項(xiàng)總結(jié)6. Gitlab CI-CD自動(dòng)化部署SpringBoot項(xiàng)目的方法步驟7. 利用CSS3新特性創(chuàng)建透明邊框三角8. 淺談SpringMVC jsp前臺(tái)獲取參數(shù)的方式 EL表達(dá)式9. axios和ajax的區(qū)別點(diǎn)總結(jié)10. python操作mysql、excel、pdf的示例
