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

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

Spring security自定義用戶認(rèn)證流程詳解

瀏覽:78日期:2023-09-16 18:44:46

1.自定義登錄頁(yè)面

(1)首先在static目錄下面創(chuàng)建login.html

  注意:springboot項(xiàng)目默認(rèn)可以訪問(wèn)resources/resources,resources/staic,resources/public目錄下面的靜態(tài)文件

<!DOCTYPE html><html lang='en'><head> <meta charset='UTF-8'> <title>登錄頁(yè)面</title></head><body><form action='/auth/login' method='post'> 用戶名:<input type='text' name='username'> <br/> 密&emsp;碼:<input type='password' name='password'> <br/> <input type='submit' value='登錄'></form></body></html>

(2)在spring securiy配置類中做如下配置

@Override protected void configure(HttpSecurity http) throws Exception { http.formLogin()// 指定自定義登錄頁(yè)面.loginPage('/login.html')// 登錄url.loginProcessingUrl('/auth/login').and().authorizeRequests()// 添加一個(gè)url匹配器,如果匹配到login.html,就授權(quán).antMatchers('/login.html').permitAll().anyRequest().authenticated().and()// 關(guān)閉spring security默認(rèn)的防csrf攻擊.csrf().disable(); }

(3)測(cè)試

(4)存在的問(wèn)題

<1>作為可以復(fù)用的登錄模塊,我們應(yīng)該提供個(gè)性化的登錄頁(yè)面,也就是說(shuō)不能寫(xiě)死只跳轉(zhuǎn)到login.html。

此問(wèn)題比較好解決,使用可配置的登錄頁(yè)面,默認(rèn)使用login.html即可。

<2> 請(qǐng)求跳轉(zhuǎn)到login.html登錄頁(yè)面,貌似沒(méi)有什么問(wèn)題,但作為restful風(fēng)格的接口,一般響應(yīng)的都是json數(shù)據(jù)格式,尤其是app請(qǐng)求。

解決思想:用戶發(fā)起數(shù)據(jù)請(qǐng)求 --> security判斷是否需要身份認(rèn)證 ----->跳轉(zhuǎn)到一個(gè)自定義的controller方法 ------>在該方法內(nèi)判斷是否是html發(fā)起的請(qǐng)求,如果是,就跳轉(zhuǎn)到login.html,如果不是,響應(yīng)一個(gè)json格式的數(shù)據(jù),說(shuō)明錯(cuò)誤信息。

自定義Controller

@Slf4j@RestControllerpublic class LoginController { /** * 請(qǐng)求緩存 */ private RequestCache requestCache = new HttpSessionRequestCache(); /** * 重定向工具類 */ private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); /** * 如果配置的登錄頁(yè)就使用配置的登錄面,否則使用默認(rèn)的登錄頁(yè)面 */// @Value('${xxxx:defaultLoginPage}')// private String standardLoginPage; private String standardLoginPage = '/login.html'; // 登錄頁(yè) /** * 用戶身份認(rèn)證方法 */ @GetMapping('/user/auth') @ResponseStatus(code = HttpStatus.UNAUTHORIZED) // 返回狀態(tài) public ResponseData login(HttpServletRequest request, HttpServletResponse response) throws IOException { SavedRequest savedRequest = requestCache.getRequest(request, response); if (savedRequest != null) { String targetUrl = savedRequest.getRedirectUrl(); log.info('請(qǐng)求是:' + targetUrl); // 如果請(qǐng)求是以html結(jié)尾 if (StringUtils.endsWithIgnoreCase(targetUrl, '.html')) {redirectStrategy.sendRedirect(request, response, standardLoginPage); } } return new ResponseData('該請(qǐng)求需要登錄,js拿到我的響應(yīng)數(shù)據(jù)后,是否需要跳轉(zhuǎn)到登錄頁(yè)面你自己看著辦吧?'); }}

spring security給該controller的login方法授權(quán)

@Override protected void configure(HttpSecurity http) throws Exception { http.formLogin()// 先進(jìn)controller中去.loginPage('/user/auth')// 指定自定義登錄頁(yè)面.loginPage('/login.html')// 登錄url.loginProcessingUrl('/auth/login').and().authorizeRequests()// 該controller需要授權(quán).antMatchers('/user/auth').permitAll()// 添加一個(gè)url匹配器,如果匹配到login.html,就授權(quán).antMatchers('/login.html').permitAll().anyRequest().authenticated().and()// 關(guān)閉spring security默認(rèn)的防csrf攻擊.csrf().disable(); }

這樣子就行了!!! 

2. 自定義登錄成功處理(返回json)

(1)實(shí)現(xiàn)AuthenticationSuccessHandler.java

import com.fasterxml.jackson.databind.ObjectMapper;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.http.MediaType;import org.springframework.security.core.Authentication;import org.springframework.security.web.authentication.AuthenticationSuccessHandler;import org.springframework.stereotype.Component;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;@Slf4j@Componentpublic class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler { @Autowired private ObjectMapper objectMapper; /** * Called when a user has been successfully authenticated. * @param request * @param response * @param authentication * @throws IOException * @throws ServletException */ @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { log.info('登錄成功!!!'); // 將登錄成功的信息寫(xiě)到前端 response.setContentType(MediaType.APPLICATION_JSON_VALUE); response.getWriter().write(objectMapper.writeValueAsString(authentication)); }}

(2)修改security配置類

@Autowired private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler; @Override protected void configure(HttpSecurity http) throws Exception { http.formLogin()// 先進(jìn)controller中去.loginPage('/user/auth')// 指定自定義登錄頁(yè)面.loginPage('/login.html')// 登錄url.loginProcessingUrl('/auth/login').successHandler(myAuthenticationSuccessHandler).and().authorizeRequests()// 該controller需要授權(quán).antMatchers('/user/auth').permitAll()// 添加一個(gè)url匹配器,如果匹配到login.html,就授權(quán).antMatchers('/login.html').permitAll().anyRequest().authenticated().and()// 關(guān)閉spring security默認(rèn)的防csrf攻擊.csrf().disable(); }

(3)測(cè)試

Spring security自定義用戶認(rèn)證流程詳解

說(shuō)明:authentication對(duì)象中包含的信息,會(huì)因?yàn)榈卿浄绞降牟煌l(fā)生改變

3.自定義登錄失敗處理(返回json)

實(shí)現(xiàn)AuthenticationFailureHandler.java接口即可,跟登錄成敗處理配置一樣。

4.自定義登錄成功處理邏輯

 以上的登錄成功或失敗的返回的都是json,但是在某些情況下,就是存在著登錄成功或者失敗進(jìn)行頁(yè)面跳轉(zhuǎn)(spring security默認(rèn)的處理方式),那么這種返回json的方式就不合適了。所以,我們應(yīng)該做得更靈活,做成可配置的。

 對(duì)于登錄成功邏輯而言只需要對(duì)MyAuthenticationSuccessHandler.java稍做修改就行,代碼如下所示:

/** * SavedRequestAwareAuthenticationSuccessHandler spring security 默認(rèn)的成功處理器 */@Slf4j@Componentpublic class MyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { @Autowired private ObjectMapper objectMapper; /** * 配置的登錄方式 */// @Value('${xxx:默認(rèn)方式}') private String loginType = 'JSON'; /** * Called when a user has been successfully authenticated. */ @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { log.info('登錄成功!!!'); // 如果配置的登錄方式是JSON,就返回json數(shù)據(jù) if ('JSON'.equals(loginType)) { // 將登錄成功的信息寫(xiě)到前端 response.setContentType(MediaType.APPLICATION_JSON_VALUE); response.getWriter().write(objectMapper.writeValueAsString(authentication)); } else { // 否則就使用默認(rèn)的跳轉(zhuǎn)方式 super.onAuthenticationSuccess(request,response,authentication); } }}

5.自定義登錄失敗處理邏輯

同登錄成功類似,具體代碼如下:

import com.fasterxml.jackson.databind.ObjectMapper;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.http.HttpStatus;import org.springframework.http.MediaType;import org.springframework.security.core.AuthenticationException;import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;import org.springframework.stereotype.Component;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;@Slf4j@Componentpublic class MySimpleUrlAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler { @Autowired private ObjectMapper objectMapper; /** * 配置的登錄方式 */// @Value('${xxx:默認(rèn)方式}') private String loginType = 'JSON'; @Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { log.info('登錄失敗!!!'); // 如果配置的登錄方式是JSON,就返回json數(shù)據(jù) if ('JSON'.equals(loginType)) { // 將登錄成功的信息寫(xiě)到前端 response.setStatus(HttpStatus.UNAUTHORIZED.value()); response.setContentType(MediaType.APPLICATION_JSON_VALUE); response.getWriter().write(objectMapper.writeValueAsString(exception)); } else { // 否則就使用默認(rèn)的跳轉(zhuǎn)方式,跳轉(zhuǎn)到一個(gè)錯(cuò)誤頁(yè)面 super.onAuthenticationFailure(request,response,exception); } }}

@Autowired private MySimpleUrlAuthenticationFailureHandler mySimpleUrlAuthenticationFailureHandler; @Override protected void configure(HttpSecurity http) throws Exception { http.formLogin()// 先進(jìn)controller中去.loginPage('/user/auth')// 指定自定義登錄頁(yè)面.loginPage('/login.html')// 登錄url.loginProcessingUrl('/auth/login').successHandler(myAuthenticationSuccessHandler).failureHandler(mySimpleUrlAuthenticationFailureHandler).and().authorizeRequests()// 該controller需要授權(quán).antMatchers('/user/auth').permitAll()// 添加一個(gè)url匹配器,如果匹配到login.html,就授權(quán).antMatchers('/login.html').permitAll().anyRequest().authenticated().and()// 關(guān)閉spring security默認(rèn)的防csrf攻擊.csrf().disable(); }

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。

標(biāo)簽: Spring
相關(guān)文章:
主站蜘蛛池模板: ★塑料拖链__工程拖链__电缆拖链__钢制拖链 - 【上海闵彬】 | HEYL硬度计量泵-荧光法在线溶解氧仪-净时测控技术(上海)有限公司 | 氢氧化钙设备_厂家-淄博工贸有限公司 | 玉米加工设备,玉米深加工机械,玉米糁加工设备.玉米脱皮制糁机 华豫万通粮机 | 建大仁科-温湿度变送器|温湿度传感器|温湿度记录仪_厂家_价格-山东仁科 | 钢格板_钢格栅_格栅板_钢格栅板 - 安平县鑫拓钢格栅板厂家 | 示波器高压差分探头-国产电流探头厂家-南京桑润斯电子科技有限公司 | 武汉画册印刷厂家-企业画册印刷-画册设计印刷制作-宣传画册印刷公司 - 武汉泽雅印刷厂 | 湖南自考_湖南自学考试| 粉末包装机,拆包机厂家,价格-上海强牛包装机械设备有限公司 | 温控器生产厂家-提供温度开关/热保护器定制与批发-惠州市华恺威电子科技有限公司 | Eiafans.com_环评爱好者 环评网|环评论坛|环评报告公示网|竣工环保验收公示网|环保验收报告公示网|环保自主验收公示|环评公示网|环保公示网|注册环评工程师|环境影响评价|环评师|规划环评|环评报告|环评考试网|环评论坛 - Powered by Discuz! | pbt头梳丝_牙刷丝_尼龙毛刷丝_PP塑料纤维合成毛丝定制厂_广州明旺 | 冷油器-冷油器换管改造-连云港灵动列管式冷油器生产厂家 | 深圳激光打标机_激光打标机_激光焊接机_激光切割机_同体激光打标机-深圳市创想激光科技有限公司 深圳快餐店设计-餐饮设计公司-餐饮空间品牌全案设计-深圳市勤蜂装饰工程 | 济南宣传册设计-画册设计_济南莫都品牌设计公司 | 泥沙分离_泥沙分离设备_泥砂分离机_洛阳隆中重工机械有限公司 | 吸音板,隔音板,吸音材料,吸音板价格,声学材料 - 佛山诺声吸音板厂家 | 国际线缆连接网 - 连接器_线缆线束加工行业门户网站 | 全自动在线分板机_铣刀式在线分板机_曲线分板机_PCB分板机-东莞市亿协自动化设备有限公司 | 雾度仪_雾度计_透光率雾度仪价格-三恩时(3nh)光电雾度仪厂家 | 定硫仪,量热仪,工业分析仪,马弗炉,煤炭化验设备厂家,煤质化验仪器,焦炭化验设备鹤壁大德煤质工业分析仪,氟氯测定仪 | 地图标注-手机导航电子地图如何标注-房地产商场地图标记【DiTuBiaoZhu.net】 | 广西绿桂涂料--承接隔热涂料、隔音涂料、真石漆、多彩仿石漆等涂料工程双包施工 | 防爆电机生产厂家,YBK3电动机,YBX3系列防爆电机,YBX4节防爆电机--河南省南洋防爆电机有限公司 | 【法利莱住人集装箱厂家】—活动集装箱房,集装箱租赁_大品牌,更放心 | 振动筛,震动筛,圆形振动筛,振动筛价格,振动筛厂家-新乡巨宝机电 蒸汽热收缩机_蒸汽发生器_塑封机_包膜机_封切收缩机_热收缩包装机_真空机_全自动打包机_捆扎机_封箱机-东莞市中堡智能科技有限公司 | 北钻固控设备|石油钻采设备-石油固控设备厂家 | 北京成考网-北京成人高考网 | 超声骨密度仪-动脉硬化检测仪器-人体成分分析仪厂家/品牌/价格_南京科力悦 | 水性绝缘漆_凡立水_绝缘漆树脂_环保绝缘漆-深圳维特利环保材料有限公司 | 27PR跨境电商导航 | 专注外贸跨境电商| 锯边机,自动锯边机,双面涂胶机-建业顺达机械有限公司 | 精密线材测试仪-电线电缆检测仪-苏州欣硕电子科技有限公司 | 雄松华章(广州华章MBA)官网-专注MBA/MPA/MPAcc/MEM辅导培训 | 传动滚筒,改向滚筒-淄博建凯机械科技有限公司 | 灌装封尾机_胶水灌装机_软管灌装封尾机_无锡和博自动化机械制造有限公司 | 标准光源箱|对色灯箱|色差仪|光泽度仪|涂层测厚仪_HRC大品牌生产厂家 | 螺旋叶片_螺旋叶片成型机_绞龙叶片_莱州源泽机械制造有限公司 | 小程序开发公司_APP开发多少钱_软件开发定制_微信小程序制作_客户销售管理软件-济南小溪畅流网络科技有限公司 | 脉冲布袋除尘器_除尘布袋-泊头市净化除尘设备生产厂家 |