該代碼示例可從Spring-MVC-Login-Logout目錄中的Github獲得。 它從帶有注釋示例的Spring MVC派生而來。
定制身份驗證提供者
為了實現我們自己的接受用戶登錄請求的方式,我們需要實現身份驗證提供程序。 如果用戶的ID與密碼相同,以下內容可讓用戶進入:
public class MyAuthenticationProvider implements AuthenticationProvider {private static final List<GrantedAuthority> AUTHORITIES= new ArrayList<GrantedAuthority>();static {AUTHORITIES.add(new SimpleGrantedAuthority('ROLE_USER'));AUTHORITIES.add(new SimpleGrantedAuthority('ROLE_ANONYMOUS'));}@Overridepublic Authentication authenticate(Authentication auth)throws AuthenticationException {if (auth.getName().equals(auth.getCredentials())) {return new UsernamePasswordAuthenticationToken(auth.getName(),auth.getCredentials(), AUTHORITIES);}throw new BadCredentialsException('Bad Credentials');}@Overridepublic boolean supports(Class<?> authentication) {if ( authentication == null ) return false;return Authentication.class.isAssignableFrom(authentication);}}
Security.xml
我們需要創建一個security.xml文件:
<beans:beans xmlns='http://www.springframework.org/schema/security'xmlns:beans='http://www.springframework.org/schema/beans'xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'xsi:schemaLocation='http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/securityhttp://www.springframework.org/schema/security/spring-security-3.1.xsd'><http><intercept-url pattern='/*' access='ROLE_ANONYMOUS'/><form-logindefault-target-url='/'always-use-default-target='true' /><anonymous /><logout /></http><authentication-manager alias='authenticationManager'><authentication-provider ref='myAuthenticationProvider' /></authentication-manager><beans:bean id='myAuthenticationProvider'class='com.jverstry.LoginLogout.Authentication.MyAuthenticationProvider' /></beans:beans>
以上內容可確保所有用戶都具有匿名角色來訪問任何頁面。 登錄后,它們將重定向到主頁。 如果他們沒有登錄,他們將被自動視為匿名用戶。 還聲明了注銷功能。 與其重新實現輪子,不如使用Spring本身提供的項目。
主頁
我們實現了一個主頁,顯示當前登錄用戶的名稱以及登錄和注銷鏈接:
<%@ taglib prefix='c' uri='http://java.sun.com/jsp/jstl/core' %>
<!doctype html>
<html lang='en'>
<head><meta charset='utf-8'><title>Welcome To MVC Customized Login Logout!!!</title>
</head><body><h1>Spring MVC Customized Login Logout !!!</h1>Who is currently logged in? <c:out value='${CurrPrincipal}' /> !<br /><a href='<c:url value='/spring_security_login'/>'>Login</a>?<a href='<c:url value='/j_spring_security_logout'/>'>Logout</a></body>
</html>
控制者
我們需要向視圖提供當前登錄的用戶名:
@Controller
public class MyController {@RequestMapping(value = '/')public String home(Model model) {model.addAttribute('CurrPrincipal',SecurityContextHolder.getContext().getAuthentication().getName());return 'index';}}
運行示例
編譯后,可以通過瀏覽以下示例開始示例:http:// localhost:9292 / spring-mvc-login-logout /。 它將顯示以下內容:

使用相同的ID和密碼登錄:

該應用程序返回主窗口并顯示:

更多春天相關的帖子在這里 。
祝您編程愉快,別忘了分享!
參考: Spring MVC定制的用戶登錄注銷實現示例,來自我們的JCG合作伙伴 Jerome Versrynge,在技術說明博客中。
翻譯自: https://www.javacodegeeks.com/2012/10/spring-mvc-customized-user-login-logout.html