这篇文章是在 Spring Security Hibernate注释实例 基础上补充的, 并简单地增加了基于角色的登录功能。由于这个篇文章与 Spring Security Hibernate注解实例有 99% 是相同的,除了一些改变,我们就不在这里重复的代码。仅做了一些简单地更改如下。
首先我们来看看整个工程目录的结构,如下图所示 -
第1步:创建一个新客户成功处理程序
package com.yiibai.springsecurity.configuration; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.web.DefaultRedirectStrategy; import org.springframework.security.web.RedirectStrategy; import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler; import org.springframework.stereotype.Component; @Component public class CustomSuccessHandler extends SimpleUrlAuthenticationSuccessHandler{ private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); @Override protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException { String targetUrl = determineTargetUrl(authentication); if (response.isCommitted()) { System.out.println("Can't redirect"); return; } redirectStrategy.sendRedirect(request, response, targetUrl); } protected String determineTargetUrl(Authentication authentication) { String url=""; Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities(); List<String> roles = new ArrayList<String>(); for (GrantedAuthority a : authorities) { roles.add(a.getAuthority()); } if (isDba(roles)) { url = "/db"; } else if (isAdmin(roles)) { url = "/admin"; } else if (isUser(roles)) { url = "/home"; } else { url="/accessDenied"; } return url; } public void setRedirectStrategy(RedirectStrategy redirectStrategy) { this.redirectStrategy = redirectStrategy; } protected RedirectStrategy getRedirectStrategy() { return redirectStrategy; } private boolean isUser(List<String> roles) { if (roles.contains("ROLE_USER")) { return true; } return false; } private boolean isAdmin(List<String> roles) { if (roles.contains("ROLE_ADMIN")) { return true; } return false; } private boolean isDba(List<String> roles) { if (roles.contains("ROLE_DBA")) { return true; } return false; } }
请注意我们是如何扩展Spring SimpleUrlAuthenticationSuccessHandler类和覆盖 handle() 方法,只是调用使用配置RedirectStrategy重定向[默认在这种情况下]URL,它是用户定义determineTargetUrl方法返回。 这个方法从当前认证对象提取登录用户的角色,然后构造基于角色有相应的URL。最后是RedirectStrategy 负责Spring Security 框架内的所有重定向,将请求重定向到指定的URL。
第2步:注册自定义成功处理程序使用[现有]Security配置
package com.yiibai.springsecurity.configuration; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; @Configuration @EnableWebSecurity public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Autowired @Qualifier("customUserDetailsService") UserDetailsService userDetailsService; @Autowired CustomSuccessHandler customSuccessHandler; @Autowired public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() //.antMatchers("/", "/home").permitAll() .antMatchers("/", "/home").access("hasRole('USER')") .antMatchers("/admin/**").access("hasRole('ADMIN')") .antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')") //.and().formLogin().loginPage("/login") .and().formLogin().loginPage("/login").successHandler(customSuccessHandler) .usernameParameter("ssoId").passwordParameter("password") .and().csrf() .and().exceptionHandling().accessDeniedPage("/Access_Denied"); } }
formLogin().loginPage("/login").successHandler(customSuccessHandler).
我们来看看 successHandler。这个类基于自定义逻辑负责最后的重定向,这对我们来说是用户的重定向[home/admin/db]是根据他的角色[USER/ADMIN/DBA]。
<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-4.1.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.0.xsd"> <http auto-config="true" > <intercept-url pattern="/" access="permitAll" /> <intercept-url pattern="/home" access="permitAll" /> <intercept-url pattern="/admin**" access="hasRole('ADMIN')" /> <intercept-url pattern="/dba**" access="hasRole('ADMIN') and hasRole('DBA')" /> <form-login login-page="/login" username-parameter="ssoId" password-parameter="password" authentication-success-handler-ref="customSuccessHandler" authentication-failure-url="/Access_Denied" /> <csrf/> </http> <authentication-manager > <authentication-provider user-service-ref="customUserDetailsService"/> </authentication-manager> <beans:bean id="customUserDetailsService" class="com.yiibai.springsecurity.service.CustomUserDetailsService" /> <beans:bean id="customSuccessHandler" class="com.yiibai.springsecurity.configuration.CustomSuccessHandler" /> </beans:beans>
构建和部署应用程序
现在构造 war(通过 eclipse/m2eclipse)或通过Maven的命令行(mvn clean install)。部署WAR文件到Servlet3.0容器。由于这里我使用的是在 eclipse 中配置 Tomcat,可以直接发布到 Tomcat 服务容器中。如果不知道怎么使用,可以参考:http://www.yiibai.com/maven/create-a-maven-web-project-with-eclipse.html
仅供参考,我们将使用在上一节中的所定义的数据库表结构及数据记录。点击查看数据库表和记录 。
打开浏览器并访问 - http://localhost:8080/SpringSecurityHibernateRoleBasedLogin/
结果如下所示 -
提供DBA登录帐户信息,这里使用 kenny 作为登录名。
提交后登录成功后,你会被直接跳转到 /db 页面, kenny具有DBA角色。如下图中所示 -
这里为了演示,故意写错了登录密码,如下所示 -
提供正确的用户(USER )角色的凭据,您将被重定向到主页。
最后,注销登录-
下载源代码
09-SpringSecurityHibernateRoleBasedLogin.zip
参考