1. 程式人生 > >Spring Seurity系列(三)個性化使用者認證邏輯(自定義登入頁面)

Spring Seurity系列(三)個性化使用者認證邏輯(自定義登入頁面)

一:自定義登入頁面:

1.1:訪問資源時如果沒有認證返回的是標準的登入頁面:

@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {
	
	@Bean
	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}
	
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		
		http.formLogin()
			.loginPage("/imooc-signIn.html")//自定義登入頁面
			.loginProcessingUrl("/authentication/form")//登入處理的請求
			.and()
			.authorizeRequests()
			.antMatchers("/imooc-signIn.html").permitAll()
			.anyRequest()
			.authenticated()
			.and()
			.csrf().disable();//關閉跨站請求防護
	}
}

並建立標準的登入頁面(預設的登入請求為login,在上面程式碼的配置中配置為/authentication/form:):

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登入</title>
</head>
<body>
	<h2>標準登入頁面</h2>
	<h3>表單登入</h3>
	<form action="/authentication/form" method="post">
		<table>
			<tr>
				<td>使用者名稱:</td>
				<td><input type="text" name="username"></td>
			</tr>
			<tr>
				<td>密碼:</td>
				<td><input type="password" name="password"></td>
			</tr>
			<tr>
				<td colspan="2"><button type="submit">登入</button></td>
			</tr>
		</table>
	</form>
</body>
</html>

1.2:處理如果是Html的請求·1,就返回Html,如果是RestFul的請求就返回RestFule的不同請求的處理:

建立BrowserSecurityController,處理不同的請求:

@RestController
public class BrowserSecurityController {
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	//從session快取中獲取請求
	private RequestCache requestCache = new HttpSessionRequestCache();
	
	private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
	
	//處理一些配置的檔案
	@Autowired
	private SecurityProperties securityProperties;

	/**
	 * 當需要身份認證時,跳轉到這裡
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("/authentication/require")
	@ResponseStatus(code = HttpStatus.UNAUTHORIZED)
	public SimpleResponse requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {

		SavedRequest savedRequest = requestCache.getRequest(request, response);

		if (savedRequest != null) {
			String targetUrl = savedRequest.getRedirectUrl();
			logger.info("引發跳轉的請求是:"+targetUrl);
			if(StringUtils.endsWithIgnoreCase(targetUrl, ".html")){
				redirectStrategy.sendRedirect(request, response, securityProperties.getBrowser().getLoginPage());
			}
		}

		return new SimpleResponse("訪問的服務需要身份認證,請引導使用者到登入頁");
	}

}

配置安全配置類:

@Override
	protected void configure(HttpSecurity http) throws Exception {
		
		http.formLogin()
			.loginPage("/authentication/require")
			.loginProcessingUrl("/authentication/form")
//		http.httpBasic()
			.and()
			.authorizeRequests()
			.antMatchers("/authentication/require",
					securityProperties.getBrowser().getLoginPage()).permitAll()
			.anyRequest()
			.authenticated()
			.and()
			.csrf().disable();
		
	}

配置SecurityProperties

@ConfigurationProperties(prefix = "imooc.security")
public class SecurityProperties {
	
	private BrowserProperties browser = new BrowserProperties();

	public BrowserProperties getBrowser() {
		return browser;
	}

	public void setBrowser(BrowserProperties browser) {
		this.browser = browser;
	}

}

配置BrowserProperties

public class BrowserProperties {
	
	private String loginPage = "/imooc-signIn.html";

	public String getLoginPage() {
		return loginPage;
	}

	public void setLoginPage(String loginPage) {
		this.loginPage = loginPage;
	}
	
}

在配置檔案中配置自定義的登入頁面,如果不配置就跳轉到預設配置的登入頁面:

imooc.security.browser.loginPage = /demo-signIn.html

啟動專案進行測試:

請求中是Html的訪問

請求是RestFul風格的訪問:

說明:本系列部落格是記錄慕課網中的教程的學習,以便我自己複習回憶。文中涉及的一些細節問題請參考慕課網中相關視訊。