我是 Spring Security 的新手,我正在构建一个 Web 应用程序,其中我有 4 个不同的角色必须将用户发送到 4 个不同的页面,例如,如果用户以管理员身份输入,我想将他发送到管理页面,如果它是客户,我想将他发送到客户页面。
到目前为止,我能够使用用户详细信息服务来验证单个用户。
我是 Spring Security 的新手,我正在构建一个 Web 应用程序,其中我有 4 个不同的角色必须将用户发送到 4 个不同的页面,例如,如果用户以管理员身份输入,我想将他发送到管理页面,如果它是客户,我想将他发送到客户页面。
到目前为止,我能够使用用户详细信息服务来验证单个用户。
在您的配置中定义四种类型的角色并添加自定义登录成功处理程序。请参阅下面的示例。
<http use-expressions="true">
<intercept-url pattern="/login*" access="permitAll"/>
<intercept-url pattern="/**" access="isAuthenticated()"/>
<form-login login-page='/login.html'
authentication-failure-url="/login.html?error=true"
authentication-success-handler-ref="myAuthenticationSuccessHandler"/>
<logout/>
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="user1" password="user1Pass" authorities="ROLE_USER"/>
<user name="admin1" password="admin1Pass" authorities="ROLE_ADMIN"/>
<user name="customer1" password="customer1Pass" authorities="ROLE_CUSTOMER"/>
<user name="other1" password="other1Pass" authorities="ROLE_OTHER"/>
</user-service>
</authentication-provider>
</authentication-manager>
<beans:bean id="myAuthenticationSuccessHandler"
class="org.baeldung.security.MySimpleUrlAuthenticationSuccessHandler"/>
AuthenticationSuccessHandler 是这样的:
public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
protected Log logger = LogFactory.getLog(this.getClass());
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@Override
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication authentication)
throws IOException {
handle(request, response, authentication);
clearAuthenticationAttributes(request);
}
protected void handle(HttpServletRequest request,
HttpServletResponse response, Authentication authentication)
throws IOException {
String targetUrl = determineTargetUrl(authentication);
if (response.isCommitted()) {
logger.debug(
"Response has already been committed. Unable to redirect to "
+ targetUrl);
return;
}
redirectStrategy.sendRedirect(request, response, targetUrl);
}
protected String determineTargetUrl(Authentication authentication) {
boolean isUser = false;
boolean isAdmin = false;
boolean isCustomer = false;
boolean isOther = false;
Collection<? extends GrantedAuthority> authorities
= authentication.getAuthorities();
for (GrantedAuthority grantedAuthority : authorities) {
if (grantedAuthority.getAuthority().equals("ROLE_USER")) {
isUser = true;
break;
} else if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) {
isAdmin = true;
break;
} else if (grantedAuthority.getAuthority().equals("ROLE_CUSTOMER")) {
isCustomer = true;
break;
} else if (grantedAuthority.getAuthority().equals("ROLE_OTHER")) {
isOther = true;
break;
}
}
if (isUser) {
return "/user.html";
} else if (isAdmin) {
return "/admin.html";
} else if (isCustomer) {
return "/customer.html";
} else if (isOther) {
return "/other.html";
} else {
throw new IllegalStateException();
}
}
protected void clearAuthenticationAttributes(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session == null) {
return;
}
session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
}
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy;
}
protected RedirectStrategy getRedirectStrategy() {
return redirectStrategy;
}
}
另一种选择是将您的成功登录页面重定向authentication-success-handler-ref
到特殊的控制器映射。
@RequestMapping("/login/process")
public String processLogin() {
Collection<GrantedAuthority> authorities = (Collection<GrantedAuthority>)
SecurityContextHolder.getContext().getAuthentication().getAuthorities();
if (authorities.contains(new SimpleGrantedAuthority("ROLE_ADMIN"))) {
return "redirect:/admin-page";
} else if (authorities.contains(new SimpleGrantedAuthority("ROLE_USER_1"))) {
return "redirect:/user_1";
} else if (authorities.contains(new SimpleGrantedAuthority("ROLE_USER_2"))) {
return "redirect:/user_2";
} else if (authorities.contains(new SimpleGrantedAuthority("ROLE_USER_3"))) {
return "redirect:/user_3";
}
// catch else
return "redirect:/";
}
除了 shi 的回应,我会在 Handler 中做一些改变。您可以在处理程序中使用Map<String,String>
as 类字段来管理角色重定向匹配。
您还可以扩展org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler以利用它已经实现的方法,这样:
import java.io.IOException;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
public class MySimpleUrlAuthenticationSuccessHandler
extends SimpleUrlAuthenticationSuccessHandler
implements AuthenticationSuccessHandler {
protected Logger logger = Logger.getLogger(this.getClass());
private Map<String, String> authorityRedirectionMap;
public MySimpleUrlAuthenticationSuccessHandler(Map<String, String> authorityRedirectionMap) {
super();
this.authorityRedirectionMap = authorityRedirectionMap;
}
@Override
protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
throws IOException, ServletException {
String targetUrl = determineTargetUrl(request, response, authentication);
if (response.isCommitted()) {
logger.debug("Response has already been committed. Unable to redirect to "
+ targetUrl);
return;
}
this.getRedirectStrategy().sendRedirect(request, response, targetUrl);
}
/**
*
* @param request
* @param response
* @param authentication
* @return
*/
protected String determineTargetUrl(HttpServletRequest request,
HttpServletResponse response, Authentication authentication) {
for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
if(this.authorityRedirectionMap.containsKey(grantedAuthority.getAuthority())){
return this.authorityRedirectionMap.get(grantedAuthority.getAuthority());
}
}
return super.determineTargetUrl(request, response);
}
}
您的配置 xml 的成功处理程序部分应如下所示:
<beans:bean id="myAuthenticationSuccessHandler"
class="org.baeldung.security.MySimpleUrlAuthenticationSuccessHandler">
<beans:constructor-arg>
<beans:map>
<beans:entry key="ROLE_USER" value="/user.html" />
<beans:entry key="ROLE_ADMIN" value="/admin.html" />
<beans:entry key="ROLE_CUSTOMER" value="/customer.html" />
<beans:entry key="ROLE_OTHER" value="/other.html" />
</beans:map>
</beans:constructor-arg>
<beans:property name="defaultTargetUrl" value="/default.html" />
</beans:bean>