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

2.2修改配置
// 表單認證
http.formLogin()
.loginProcessingUrl("/login") //當發(fā)現(xiàn)/login時認為是登錄,需要執(zhí)行UserDetailsServiceImpl
.successForwardUrl("/toMain") //此處是post請求
.failureForwardUrl("/fail") //登錄失敗跳轉(zhuǎn)地址
.loginPage("/login.html")
.usernameParameter("myusername")
.passwordParameter("mypassword");
2.3修改頁面
? 修改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()時表示成功后轉(zhuǎn)發(fā)請求到地址。內(nèi)部是通過successHandler()方法進行控制成功后交給哪個類進行處理

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

當需要控制登錄成功后去做一些事情時,可以進行自定義認證成功控制器。
3.2代碼實現(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());
//重定向到百度。這只是一個示例,具體需要看項目業(yè)務需求
httpServletResponse.sendRedirect("http://www.baidu.com");
}
}
3.2.2修改配置項
使用successHandler()方法設置成功后交給哪個對象進行處理
// 表單認證
http.formLogin()
.loginProcessingUrl("/login") //當發(fā)現(xiàn)/login時認為是登錄,需要執(zhí)行UserDetailsServiceImpl
.successHandler(new MyAuthenticationSuccessHandler())
//.successForwardUrl("/toMain") //此處是post請求
.failureForwardUrl("/fail") //登錄失敗跳轉(zhuǎn)地址
.loginPage("/login.html");
4.自定義登錄失敗處理器
4.1源碼分析

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

4.2代碼實現(xiàn)
4.2.1新建控制器
新建com.msb.handler.MyForwardAuthenticationFailureHandler實現(xiàn)AuthenticationFailureHandler。
在方法中添加重定向語句
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修改配置類
? 修改配置類中表單登錄部分。設置失敗時交給失敗處理器進行操作。failureForwardUrl和failureHandler不可共存。
// 表單認證
http.formLogin()
.loginProcessingUrl("/login") //當發(fā)現(xiàn)/login時認為是登錄,需要執(zhí)行UserDetailsServiceImpl
.successHandler(new MyAuthenticationSuccessHandler())
//.successForwardUrl("/toMain") //此處是post請求
.failureHandler(new MyForwardAuthenticationFailureHandler())
// .failureForwardUrl("/fail") //登錄失敗跳轉(zhuǎn)地址
.loginPage("/login.html");以上就是Spring Security自定義登錄頁面認證過程常用配置的詳細內(nèi)容,更多關于Spring Security登錄認證配置的資料請關注腳本之家其它相關文章!
相關文章
SpringCloud OpenFeign與Ribbon客戶端配置詳解
在springcloud中,openfeign是取代了feign作為負載均衡組件的,feign最早是netflix提供的,他是一個輕量級的支持RESTful的http服務調(diào)用框架,內(nèi)置了ribbon,而ribbon可以提供負載均衡機制,因此feign可以作為一個負載均衡的遠程服務調(diào)用框架使用2022-11-11

