Spring Security使用不同类型的用户进行身份验证

时间:2017-02-02 00:15:28

标签: spring spring-security userdetailsservice

我是Spring安全新手,我正在构建一个Web应用程序,其中我有4个不同的角色,我知道spring对授权用户使用不同的角色但是如果有4种不同类型的注册和之后我该如何实现它登录我必须将用户发送到4个不同的页面,如果用户输入管理员我想将他发送到管理页面,如果它是客户我想将他发送到客户页面。

到目前为止,我可以使用用户详细信息服务来验证单个用户。

3 个答案:

答案 0 :(得分:2)

在您的配置中定义四种类型的角色并添加自定义登录成功处理程序。见下面的例子。

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;
    }
}

AuthenticationSuccessHandler是这样的:

    Scanner input = new Scanner(System.in);

    double startingMile;
    System.out.print("Enter the starting mile: ");
    startingMile = input.nextDouble();
    double endingMile;
    System.out.print("Enter the ending mile: ");
    endingMile = input.nextDouble();
    System.out.println("");

    double countOne;
    countOne = startingMile;
    while (countOne <= endingMile) {
        endingMile = countOne * 1.609;
        System.out.println("miles: " + countOne + "," + " Kilometers: " + endingMile);
        countOne++;
    } 

答案 1 :(得分:1)

另一种方法是将成功登录页面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:/";
}

答案 2 :(得分:0)

除了shi的回复之外,我还会对Handler进行一些更改。您可以在处理程序中使用Map<String,String>作为类字段来管理角色重定向匹配。

你还可以扩展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>