1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > Spring MVC定制用户登录注销实现示例

Spring MVC定制用户登录注销实现示例

时间:2019-10-26 09:37:11

相关推荐

Spring MVC定制用户登录注销实现示例

这篇文章描述了如何实现对Spring MVC Web应用程序的自定义用户访问(登录注销)。 作为前提,建议读者阅读这篇文章 ,其中介绍了一些Spring Security概念。

该代码示例可从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='/schema/security'xmlns:beans='/schema/beans'xmlns:xsi='/2001/XMLSchema-instance'xsi:schemaLocation='/schema/beans/schema/beans/spring-beans-3.0.xsd/schema/security/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='/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>

控制者

我们需要向视图提供当前登录的用户名:

@Controllerpublic 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,在技术说明博客中。

翻译自: //10/spring-mvc-customized-user-login-logout.html

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。