电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術文章
文章詳情頁

SpringBoot Security前后端分離登錄驗證的實現

瀏覽:8日期:2023-04-25 09:43:31

最近一段時間在研究OAuth2的使用,想整個單點登錄,從網上找了很多demo都沒有實施成功,也許是因為壓根就不懂OAuth2的原理導致。有那么幾天,越來越沒有頭緒,又不能放棄,轉過頭來一想,OAuth2是在Security的基礎上擴展的,對于Security自己都是一無所知,干脆就先研究一下Security吧,先把Security搭建起來,找找感覺。

說干就干,在現成的SpringBoot 2.1.4.RELEASE環境下,進行Security的使用。簡單的Security的使用就不說了,目前的項目是前后端分離的,登錄成功或者失敗返回的數據格式必須JSON形式的,未登錄時也需要返回JSON格式的提示信息 ,退出時一樣需要返回JSON格式的數據。授權先不管,先返回JSON格式的數據,這一個搞定,也研究了好幾天,翻看了很多別人的經驗,別人的經驗有的看得懂,有的看不懂,關鍵時刻還需要自己研究呀。

下面,上代碼:

第一步,在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;/** * 參考網址: * 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配置文件,項目啟動時就加載了 * @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() //未登錄時,進行json格式的提示,很喜歡這種寫法,不用單獨寫一個又一個的類 .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() //必須授權才能范圍 .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','用戶名或密碼錯誤'); } 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() //沒有權限,返回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', '權限不足'); 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(); //開啟模擬請求,比如API POST測試工具的測試,不開啟時,API POST為報403錯誤 http.csrf().disable(); } @Override public void configure(WebSecurity web) { //對于在header里面增加token等類似情況,放行所有OPTIONS請求。 web.ignoring().antMatchers(HttpMethod.OPTIONS, '/**'); } @Bean public AuthenticationProvider authenticationProvider() { DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider(); //對默認的UserDetailsService進行覆蓋 authenticationProvider.setUserDetailsService(myCustomUserService); authenticationProvider.setPasswordEncoder(myPasswordEncoder); return authenticationProvider; } }

第三步,實現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;/** * 登錄專用類 * 自定義類,實現了UserDetailsService接口,用戶登錄時調用的第一類 * @author 程就人生 * */@Componentpublic class MyCustomUserService implements UserDetailsService { /** * 登陸驗證時,通過username獲取用戶的所有權限信息 * 并返回UserDetails放到spring的全局緩存SecurityContextHolder中,以供授權器使用 */ @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { //在這里可以自己調用數據庫,對username進行查詢,看看在數據庫中是否存在 MyUserDetails myUserDetail = new MyUserDetails(); myUserDetail.setUsername(username); myUserDetail.setPassword('123456'); return myUserDetail; }}

說明:這個類,主要是用來接收登錄傳遞過來的用戶名,然后可以在這里擴展,查詢該用戶名在數據庫中是否存在,不存在時,可以拋出異常。本測試為了演示,把數據寫死了。

第四步,實現PasswordEncoder接口

import org.springframework.security.crypto.password.PasswordEncoder;import org.springframework.stereotype.Component;/** * 自定義的密碼加密方法,實現了PasswordEncoder接口 * @author 程就人生 * */@Componentpublic class MyPasswordEncoder implements PasswordEncoder { @Override public String encode(CharSequence charSequence) { //加密方法可以根據自己的需要修改 return charSequence.toString(); } @Override public boolean matches(CharSequence charSequence, String s) { return encode(charSequence).equals(s); }}

說明:這個類主要是對密碼加密的處理,以及用戶傳遞過來的密碼和數據庫密碼(UserDetailsService中的密碼)進行比對。

第五步,實現UserDetails接口

import java.util.Collection;import org.springframework.security.core.GrantedAuthority;import org.springframework.security.core.userdetails.UserDetails;import org.springframework.stereotype.Component;/** * 實現了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; }}

說明:這個類是用來存儲登錄成功后的用戶數據,登錄成功后,可以使用下列代碼獲取:

MyUserDetails myUserDetails= (MyUserDetails) SecurityContextHolder.getContext().getAuthentication() .getPrincipal();

代碼寫完了,接下來需要測試一下,經過測試才能證明代碼的有效性,先用瀏覽器吧。

第一步測試,未登錄前訪問index,頁面直接重定向到默認的login頁面了,測試接口OK。

SpringBoot Security前后端分離登錄驗證的實現

圖-1

第二步測試,登錄login后,返回了json數據,測試結果OK。

SpringBoot Security前后端分離登錄驗證的實現

圖-2

第三步測試,訪問index,返回輸出的登錄數據,測試結果OK。

SpringBoot Security前后端分離登錄驗證的實現

圖-3

第四步,訪問logout,返回json數據,測試接口OK。

SpringBoot Security前后端分離登錄驗證的實現

圖-4

第五步,用API POST測試,用這個工具模擬ajax請求,看請求結果如何,首先訪問index,這個必須登錄后才能訪問。測試結果ok,返回了我們需要的JSON格式數據。

SpringBoot Security前后端分離登錄驗證的實現

圖-5

第六步,在登錄模擬對話框,設置環境變量,以保持登錄狀態。

SpringBoot Security前后端分離登錄驗證的實現

圖-6

**第七步,登錄測試,返回JSON格式的數據,測試結果OK。

SpringBoot Security前后端分離登錄驗證的實現

圖-7

第八步,在返回到index測試窗口,發送請求,返回當前用戶JSON格式的信息,測試結果OK。

SpringBoot Security前后端分離登錄驗證的實現

圖-8

第九步,測試退出,返回JSON格式數據,測試結果OK

SpringBoot Security前后端分離登錄驗證的實現

圖-9

第十步,退出后,再訪問index,出現問題,登錄信息還在,LOOK!

SpringBoot Security前后端分離登錄驗證的實現

圖-10

把頭部的header前面的勾去掉,也就是去掉cookie,這時正常了,原因很簡單,在退出時,沒有清除cookie,這個只能到正式的環境上去測了。API POST再怎么模擬還是和正式環境有區別的。

如果在API POST測試報403錯誤,那就需要把configuration配置文件里的

//開啟跨域訪問http.cors().disable();//開啟模擬請求,比如API POST測試工具的測試,不開啟時,API POST為報403錯誤http.csrf().disable();

到此這篇關于SpringBoot Security前后端分離登錄驗證的實現的文章就介紹到這了,更多相關SpringBoot Security登錄驗證內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Spring
相關文章:
主站蜘蛛池模板: 制丸机,小型中药制丸机,全自动制丸机价格-甘肃恒跃制药设备有限公司 | 非标压力容器_碳钢储罐_不锈钢_搪玻璃反应釜厂家-山东首丰智能环保装备有限公司 | 氧氮氢联合测定仪-联测仪-氧氮氢元素分析仪-江苏品彦光电 | 北京软件开发_软件开发公司_北京软件公司-北京宜天信达软件开发公司 | 电液推杆生产厂家|电动推杆|液压推杆-扬州唯升机械有限公司 | 光泽度计_测量显微镜_苏州压力仪_苏州扭力板手维修-苏州日升精密仪器有限公司 | 上海软件开发-上海软件公司-软件外包-企业软件定制开发公司-咏熠科技 | 广东高华家具-公寓床|学生宿舍双层铁床厂家【质保十年】 | 聚氨酯保温钢管_聚氨酯直埋保温管道_聚氨酯发泡保温管厂家-沧州万荣防腐保温管道有限公司 | 环氧树脂地坪漆_济宁市新天地漆业有限公司 | 山东太阳能路灯厂家-庭院灯生产厂家-济南晟启灯饰有限公司 | 档案密集柜_手动密集柜_智能密集柜_内蒙古档案密集柜-盛隆柜业内蒙古密集柜直销中心 | 沥青车辙成型机-车托式混凝土取芯机-混凝土塑料试模|鑫高仪器 | 根系分析仪,大米外观品质检测仪,考种仪,藻类鉴定计数仪,叶面积仪,菌落计数仪,抑菌圈测量仪,抗生素效价测定仪,植物表型仪,冠层分析仪-杭州万深检测仪器网 | 信阳市建筑勘察设计研究院有限公司| 带式过滤机厂家_价格_型号规格参数-江西核威环保科技有限公司 | 润滑脂-高温润滑脂-轴承润滑脂-食品级润滑油-索科润滑油脂厂家 | 瑞典Blueair空气净化器租赁服务中心-专注新装修办公室除醛去异味服务! | 钢格板|镀锌钢格板|热镀锌钢格板|格栅板|钢格板|钢格栅板|热浸锌钢格板|平台钢格板|镀锌钢格栅板|热镀锌钢格栅板|平台钢格栅板|不锈钢钢格栅板 - 专业钢格板厂家 | PTFE接头|聚四氟乙烯螺丝|阀门|薄膜|消解罐|聚四氟乙烯球-嘉兴市方圆氟塑制品有限公司 | 湖南长沙商标注册专利申请,长沙公司注册代理记账首选美创! | 合肥办公室装修 - 合肥工装公司 - 天思装饰 | 不发火防静电金属骨料_无机磨石_水泥自流平_修补砂浆厂家「圣威特」 | 玻璃钢格栅盖板|玻璃钢盖板|玻璃钢格栅板|树篦子-长沙川皖玻璃钢制品有限公司 | 沧州友城管业有限公司-内外涂塑钢管-大口径螺旋钢管-涂塑螺旋管-保温钢管生产厂家 | 小区健身器材_户外健身器材_室外健身器材_公园健身路径-沧州浩然体育器材有限公司 | 膏剂灌装旋盖机-眼药水灌装生产线-西林瓶粉剂分装机-南通博琅机械科技 | 挤出熔体泵_高温熔体泵_熔体出料泵_郑州海科熔体泵有限公司 | 面粉仓_储酒罐_不锈钢储酒罐厂家-泰安鑫佳机械制造有限公司 | 临时厕所租赁_玻璃钢厕所租赁_蹲式|坐式厕所出租-北京慧海通 | 爱德华真空泵油/罗茨泵维修,爱发科-比其尔产品供应东莞/杭州/上海等全国各地 | 上海刑事律师|刑事辩护律师|专业刑事犯罪辩护律师免费咨询-[尤辰荣]金牌上海刑事律师团队 | 武汉画册印刷厂家-企业画册印刷-画册设计印刷制作-宣传画册印刷公司 - 武汉泽雅印刷厂 | 酸度计_PH计_特斯拉计-西安云仪 纯水电导率测定仪-万用气体检测仪-低钠测定仪-米沃奇科技(北京)有限公司www.milwaukeeinst.cn | 江苏农村商业银行招聘网_2024江苏农商行考试指南_江苏农商行校园招聘 | 海日牌清洗剂-打造带电清洗剂、工业清洗剂等清洗剂国内一线品牌 海外整合营销-独立站营销-社交媒体运营_广州甲壳虫跨境网络服务 | 工业雾炮机_超细雾炮_远程抑尘射雾器-世纪润德环保设备 | 储气罐,真空罐,缓冲罐,隔膜气压罐厂家批发价格,空压机储气罐规格型号-上海申容压力容器集团有限公司 | 活性炭-蜂窝-椰壳-柱状-粉状活性炭-河南唐达净水材料有限公司 | 驾驶式洗地机/扫地机_全自动洗地机_工业洗地机_荣事达工厂官网 | 闭端端子|弹簧螺式接线头|防水接线头|插线式接线头|端子台|电源线扣+护线套|印刷电路板型端子台|金笔电子代理商-上海拓胜电气有限公司 |