Spring?Security自定義登錄頁(yè)面認(rèn)證過(guò)程常用配置
一、自定義登錄頁(yè)面
雖然Spring Security給我們提供了登錄頁(yè)面,但是對(duì)于實(shí)際項(xiàng)目中,大多喜歡使用自己的登錄頁(yè)面。所以Spring Security中不僅僅提供了登錄頁(yè)面,還支持用戶自定義登錄頁(yè)面。實(shí)現(xiàn)過(guò)程也比較簡(jiǎn)單,只需要修改配置類即可。
1.編寫登錄頁(yè)面
別寫登錄頁(yè)面,登錄頁(yè)面中
的action不編寫對(duì)應(yīng)控制器也可以。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>內(nèi)容</title>
</head>
<body>
<form action="/login" method="post">
<input type="text" name="username"/>
<input type="password" name="password"/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
2.修改配置類
? 修改配置類中主要是設(shè)置哪個(gè)頁(yè)面是登錄頁(yè)面。配置類需要繼承WebSecurityConfigurerAdapter,并重寫configure方法。
? successForwardUrl()登錄成功后跳轉(zhuǎn)地址
? loginPage() 登錄頁(yè)面
? loginProcessingUrl 登錄頁(yè)面表單提交地址,此地址可以不真實(shí)存在。
? antMatchers():匹配內(nèi)容
? permitAll():允許
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// 表單認(rèn)證
http.formLogin()
.loginProcessingUrl("/login")
//當(dāng)發(fā)現(xiàn)/login時(shí)認(rèn)為是登錄,需要執(zhí)行
UserDetailsServiceImpl
.successForwardUrl("/toMain") //此處是post請(qǐng)求
.loginPage("/login.html");
// url 攔截
http.authorizeRequests()
.antMatchers("/login.html").permitAll() //login.html不需要被認(rèn)證
.anyRequest().authenticated();//所有的請(qǐng)求都必須被認(rèn)證。必須登錄后才能訪問(wèn)。
//關(guān)閉csrf防護(hù)
http.csrf().disable();
}
@Bean
public PasswordEncoder getPe(){
return new BCryptPasswordEncoder();
}
}
3.編寫控制器
編寫控制器,當(dāng)用戶登錄成功后跳轉(zhuǎn)toMain控制器。編寫完成控制器后編寫main.html。頁(yè)面中隨意寫上一句話表示main.html頁(yè)面內(nèi)容即可。而之前的/login控制器方法是不執(zhí)行的,所以可以刪除了。
@Controller
public class LoginController {
// 該方法不會(huì)被執(zhí)行
// @RequestMapping("/login")
// public String login(){
// System.out.println("執(zhí)行了login方法");
// return "redirect:main.html";
// }
@PostMapping("/toMain")
public String toMain(){
return "redirect:/main.html";
}
}
二、 認(rèn)證過(guò)程其他常用配置
1.失敗跳轉(zhuǎn)
表單處理中成功會(huì)跳轉(zhuǎn)到一個(gè)地址,失敗也可以跳轉(zhuǎn)到一個(gè)地址中。
1.1編寫頁(yè)面
在src/main/resources/static下新建fail.html并編寫如下內(nèi)容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
操作失敗,請(qǐng)重新登錄. <a href="/login.html" rel="external nofollow" >跳轉(zhuǎn)</a>
</body>
</html>
1.2修改表單配置
在配置方法中表單認(rèn)證部分添加failureForwardUrl()方法,表示登錄失敗跳轉(zhuǎn)的url。此處依然是POST請(qǐng)求,所以跳轉(zhuǎn)到可以接收POST請(qǐng)求的控制器/fail中。
// 表單認(rèn)證
http.formLogin()
.loginProcessingUrl("/login") //當(dāng)發(fā)現(xiàn)/login時(shí)認(rèn)為是登錄,需要執(zhí)行UserDetailsServiceImpl
.successForwardUrl("/toMain") //此處是post請(qǐng)求
.failureForwardUrl("/fail") //登錄失敗跳轉(zhuǎn)地址
.loginPage("/login.html");
1.3添加控制器方法
在控制器類中添加控制器方法,方法映射路徑/fail。此處要注意:由于是POST請(qǐng)求訪問(wèn)/fail。所以如果返回值直接轉(zhuǎn)發(fā)到fail.html中,及時(shí)有效果,控制臺(tái)也會(huì)報(bào)警告,提示fail.html不支持POST訪問(wèn)方式。
@PostMapping("/fail")
public String fail(){
return "redirect:/fail.html";
}
1.4設(shè)置fail.html不需要認(rèn)證
認(rèn)證失敗跳轉(zhuǎn)到fail.html頁(yè)面中,所以必須配置fail.html不需要被認(rèn)證。需要修改配置類中內(nèi)容
// url 攔截
http.authorizeRequests()
.antMatchers("/login.html").permitAll() //login.html不需要被認(rèn)證
.antMatchers("/fail.html").permitAll() //fail.html不需要被認(rèn)證
.anyRequest().authenticated();//所有的請(qǐng)求都必須被認(rèn)證。必須登錄后才能訪問(wèn)。
2.設(shè)置請(qǐng)求賬戶和密碼的參數(shù)名
2.1源碼簡(jiǎn)介
當(dāng)進(jìn)行登錄時(shí)會(huì)執(zhí)行UsernamePasswordAuthenticationFilter過(guò)濾器。
usernamePasrameter:賬戶參數(shù)名
passwordParameter:密碼參數(shù)名
postOnly=true:默認(rèn)情況下只允許POST請(qǐng)求。

2.2修改配置
// 表單認(rèn)證
http.formLogin()
.loginProcessingUrl("/login") //當(dāng)發(fā)現(xiàn)/login時(shí)認(rèn)為是登錄,需要執(zhí)行UserDetailsServiceImpl
.successForwardUrl("/toMain") //此處是post請(qǐng)求
.failureForwardUrl("/fail") //登錄失敗跳轉(zhuǎn)地址
.loginPage("/login.html")
.usernameParameter("myusername")
.passwordParameter("mypassword");
2.3修改頁(yè)面
? 修改login.html
<form action = "/login" method="post">
用戶名:<input type="text" name="myusername"/><br/>
密碼:<input type="password" name="mypassword"/><br/>
<input type="submit" value="登錄"/>
</form>
3.自定義登錄成功處理器
3.1源碼分析
使用successForwardUrl()時(shí)表示成功后轉(zhuǎn)發(fā)請(qǐng)求到地址。內(nèi)部是通過(guò)successHandler()方法進(jìn)行控制成功后交給哪個(gè)類進(jìn)行處理

ForwardAuthenticationSuccessHandler內(nèi)部就是最簡(jiǎn)單的請(qǐng)求轉(zhuǎn)發(fā)。由于是請(qǐng)求轉(zhuǎn)發(fā),當(dāng)遇到需要跳轉(zhuǎn)到站外或在前后端分離的項(xiàng)目中就無(wú)法使用了。

當(dāng)需要控制登錄成功后去做一些事情時(shí),可以進(jìn)行自定義認(rèn)證成功控制器。
3.2代碼實(shí)現(xiàn)
3.2.1自定義類
新建類com.msb.handler.MyAuthenticationSuccessHandler編寫如下:
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
//Principal 主體,存放了登錄用戶的信息
User user = (User)authentication.getPrincipal();
System.out.println(user.getUsername());
System.out.println(user.getPassword());//密碼輸出為null
System.out.println(user.getAuthorities());
//重定向到百度。這只是一個(gè)示例,具體需要看項(xiàng)目業(yè)務(wù)需求
httpServletResponse.sendRedirect("http://www.baidu.com");
}
}
3.2.2修改配置項(xiàng)
使用successHandler()方法設(shè)置成功后交給哪個(gè)對(duì)象進(jìn)行處理
// 表單認(rèn)證
http.formLogin()
.loginProcessingUrl("/login") //當(dāng)發(fā)現(xiàn)/login時(shí)認(rèn)為是登錄,需要執(zhí)行UserDetailsServiceImpl
.successHandler(new MyAuthenticationSuccessHandler())
//.successForwardUrl("/toMain") //此處是post請(qǐng)求
.failureForwardUrl("/fail") //登錄失敗跳轉(zhuǎn)地址
.loginPage("/login.html");
4.自定義登錄失敗處理器
4.1源碼分析

ForwardAuthenticationFailureHandler中也是一個(gè)請(qǐng)求轉(zhuǎn)發(fā),并在request作用域中設(shè)置 SPRING_SECURITY_LAST_EXCEPTION的key,內(nèi)容為異常對(duì)象。

4.2代碼實(shí)現(xiàn)
4.2.1新建控制器
新建com.msb.handler.MyForwardAuthenticationFailureHandler實(shí)現(xiàn)AuthenticationFailureHandler。
在方法中添加重定向語(yǔ)句
public class MyForwardAuthenticationFailureHandler implements AuthenticationFailureHandler {
@Override
public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
httpServletResponse.sendRedirect("/fail.html");
}
}
4.2.2修改配置類
? 修改配置類中表單登錄部分。設(shè)置失敗時(shí)交給失敗處理器進(jìn)行操作。failureForwardUrl和failureHandler不可共存。
// 表單認(rèn)證
http.formLogin()
.loginProcessingUrl("/login") //當(dāng)發(fā)現(xiàn)/login時(shí)認(rèn)為是登錄,需要執(zhí)行UserDetailsServiceImpl
.successHandler(new MyAuthenticationSuccessHandler())
//.successForwardUrl("/toMain") //此處是post請(qǐng)求
.failureHandler(new MyForwardAuthenticationFailureHandler())
// .failureForwardUrl("/fail") //登錄失敗跳轉(zhuǎn)地址
.loginPage("/login.html");以上就是Spring Security自定義登錄頁(yè)面認(rèn)證過(guò)程常用配置的詳細(xì)內(nèi)容,更多關(guān)于Spring Security登錄認(rèn)證配置的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
使用JPA自定義VO類型轉(zhuǎn)換(EntityUtils工具類)
這篇文章主要介紹了使用JPA自定義VO類型轉(zhuǎn)換(EntityUtils工具類),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-11-11
Java操作PDF文件實(shí)現(xiàn)簽訂電子合同詳細(xì)教程
這篇文章主要介紹了如何在PDF中加入電子簽章與電子簽名的過(guò)程,包括編寫Word文件、生成PDF、為PDF格式做表單、為表單賦值、生成文檔以及上傳到OBS中的步驟,需要的朋友可以參考下2025-01-01
mybatis配置mapper-locations的坑及解決
這篇文章主要介紹了mybatis配置mapper-locations的坑及解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-06-06
基于Springboot一個(gè)注解搞定數(shù)據(jù)字典的實(shí)踐方案
這篇文章主要介紹了基于Springboot一個(gè)注解搞定數(shù)據(jù)字典問(wèn)題,大致的方向是自定義注解,在序列化的時(shí)候進(jìn)行數(shù)據(jù)處理,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-06-06
SpringBoot實(shí)現(xiàn)RabbitMQ監(jiān)聽消息的四種方式
本文介紹了在Spring Boot中實(shí)現(xiàn)RabbitMQ監(jiān)聽消息的幾種方式,包括使用@RabbitListener注解、MessageListenerAdapter、配置連接工廠和隊(duì)列等方式,感興趣的可以了解一下2024-07-07

