该代码示例可从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'));
}
@Override
public 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');
}
@Override
public 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/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd'>
<http>
<intercept-url pattern='/*' access='ROLE_ANONYMOUS'/>
<form-login
default-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