简体   繁体   English

Spring Security LDAP与基本身份验证

[英]Spring Security LDAP vs Basic Authentication

I've burned a few days trying to get something that should be simple to work. 我花了几天的时间来尝试获得一些应该很简单的东西。 I have an application (web app) that works with Spring Security 3.0.5 and I'm having a hell of a time trying to switch out my authentication-manager for something that supports LDAP. 我有一个可以与Spring Security 3.0.5一起使用的应用程序(网络应用程序),并且在尝试将我的authentication-manager切换为支持LDAP的东西时遇到了麻烦。

I'm using JSF and it seems like most of the tutorials out there are geared towards jsp 我正在使用JSF,似乎大多数教程都针对jsp

I'm by no means a spring expert and I've hobbled something together off some tutorials I found scattered around the web. 我绝不是弹簧专家,我从散布在网络上的一些教程中吸收了一些东西。

Servlet-context.xml Servlet-context.xml

I'm not 100% sure exactly what this file does? 我不是100%确切知道此文件的作用吗?

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"

xsi:schemaLocation="
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">

<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->

<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />

<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <beans:property name="prefix" value="/WEB-INF/views/" />
    <beans:property name="suffix" value=".jsp" />
</beans:bean>

</beans:beans>

Security.xml Security.xml

This file appears to define the security configuration and such as well as what parts of the web app are locked down. 该文件似乎定义了安全配置,以及Web应用程序的哪些部分被锁定。

<?xml version="1.0" encoding="UTF-8"?>

<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.0.xsd">

<http use-expressions="true">
    <intercept-url pattern="/ff/**"         access="isAuthenticated()" />
    <intercept-url pattern="/**" access="permitAll()" />

    <!-- Custom login page -->
    <form-login login-page="/login.jsf" authentication-failure-url="/login-fail.jsf"/>

    <!-- Custom logout page -->
    <logout logout-success-url="/login.jsf"  invalidate-session="true"/>

</http>

<!-- Use inline authentication provider. -->
<authentication-manager>
    <authentication-provider>
        <password-encoder hash="md5"/>
        <user-service>
            <user name="admin" password="21232f297a57a5a743894a0e4a801fc3" authorities="ROLE_ADMIN,ROLE_USER" />
            <user name="raj" password="0b438dd454bc6a17de239ebf0a46b91b" authorities="ROLE_USER" />
        </user-service>
    </authentication-provider>
</authentication-manager>

Web.xml Web.xml

It appears this file tells the web-app which additional spring fillets parse 该文件似乎告诉网络应用,哪些附加的弹簧圆角会进行解析

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee     http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/spring/root-context.xml
        /WEB-INF/spring/security.xml
    </param-value>
</context-param>




<!-- Enable Spring Security -->
<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<!-- Allow login pages with JSF which redirects to security check, therefore we have to add the forward entry here -->
<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>REQUEST</dispatcher>
</filter-mapping>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>

<servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/servlet-context.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>appServlet</servlet-name>
    <url-pattern>/spring/</url-pattern>
</servlet-mapping>

<servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.jsf</url-pattern>
    <url-pattern>/faces/*</url-pattern>
</servlet-mapping>


<session-config>
    <session-timeout>
        30
    </session-timeout>
</session-config>
</web-app>

And lastly I have a bean (i think) that handles the security stuff 最后,我有一个处理安全问题的bean(我认为)

SecurityWrapper.java SecurityWrapper.java

import java.util.Collection;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

/**
* Code from: http://www.baeldung.com/get-user-in-spring-security
*/
@ManagedBean
@SessionScoped
public class SecurityWrapper {

public String getUser() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (!(authentication instanceof AnonymousAuthenticationToken)) {
        String currentUserName = authentication.getName();
        return currentUserName;
    }
    return "NO USER DETECTED";
}

/*This is a example for to obtain the rol name for example for generate automatic menu    */
public String getRole() {

    /*This is a example for to obtain the rol name for example for generate automatic menu    */
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    String namePrincipalRol = null;
    if (auth instanceof AnonymousAuthenticationToken) {

        namePrincipalRol = "ROLE_ANONYMOUS";
    } else {

        namePrincipalRol = auth.getAuthorities().iterator().next().getAuthority();
    }
    return namePrincipalRol;
}

private void getUserDetails() {
    UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().
            getAuthentication().getPrincipal();
    System.out.println(userDetails.getPassword());
    System.out.println(userDetails.getUsername());
    System.out.println(userDetails.isEnabled());
}

private boolean hasRole(String role) {
    Collection<GrantedAuthority> authorities = (Collection<GrantedAuthority>) SecurityContextHolder.getContext().getAuthentication().getAuthorities();
    boolean hasRole = false;
    for (GrantedAuthority authority : authorities) {
        hasRole = authority.getAuthority().equals(role);
        if (hasRole) {
            break;
        }
    }
    return hasRole;
}

 public String logout(){
     getUserDetails();
    SecurityContextHolder.clearContext();

    return "loggedout";
}

}

Questions 问题

So here is where I'm running into issues. 所以这是我遇到问题的地方。 1) This example code I put together (much came from: http://www.baeldung.com/get-user-in-spring-security ) is running Spring 3.0.5 which probably is very out of date, but I'm hoping that shouldn't matter. 1)我放在一起的示例代码(很多来自: http : //www.baeldung.com/get-user-in-spring-security )正在运行Spring 3.0.5 ,这可能已经过时了,但是我我希望这无关紧要。 I've gone various routes attempting to integrate and/or switch out my authentication provider for LDAP but I keep running into issues where my tutorials are of a different version and when I try to upgrade spring things go kaboom. 我走过各种途径尝试为LDAP集成和/或关闭我的身份验证提供程序,但是我遇到了教程版本不同以及尝试升级spring时遇到的问题。 I'm assuming this should be a straight forward process but I would love some pointers as how to move forward. 我认为这应该是一个简单的过程,但是我希望在前进的过程中能有所指点。

There are various answers on stack for integrating Spring LDAP but they are all (mostly) related to .jsp and not .xhtml which may/may not matter - and I've run into much trouble trying to integrate the other ones. 集成Spring LDAP的堆栈上有各种答案,但它们都(大部分)与.jsp无关,而与.xhtml无关,这可能/可能无关紧要-并且在集成其他问题时遇到了很多麻烦。

Should this be a straight forward process or is it actually more involved than I realize? 这应该是一个直截了当的过程,还是实际上比我意识到的要复杂得多? And if/so is it as simple as just swapping out my <authentication-manager> or do i need to add special java code as well? 如果是这样,那么就像换掉我的<authentication-manager>一样简单,还是我也需要添加特殊的Java代码?

So...assuming you have Spring security working and you wish to switch to LDAP 所以...假设您正在使用Spring安全性并且希望切换到LDAP

You need to have your authentication manager like so in your file Security.xml: 您需要在文件Security.xml中安装像这样的身份验证管理器:

<sec:authentication-manager alias="webAuthenticationManager">
    <sec:authentication-provider ref="ldapActiveDirectoryAuthProvider" />
</sec:authentication-manager> 

And the actual bean that does this: 实际的bean可以做到这一点:

<bean id="ldapActiveDirectoryAuthProvider" class="org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider">
    <constructor-arg value="yourcompany.com" />
    <constructor-arg value="ldap://yourserver.yourcompany.com:389 " />
    <property name="authoritiesMapper" ref="dataAutomationGrantedAuthoritiesMapper" />
    <property name="useAuthenticationRequestCredentials" value="true" />
</bean>   

You also need to MAP the groups to Spring security roles: 您还需要将组映射到Spring安全角色:

<!-- Mapping of Groups (user is member of) to Application roles used by Spring security -->
 <bean id="dataAutomationGrantedAuthoritiesMapper" class="com.deltarail.view.web.login.DataAutomationGrantedAuthoritiesMapper">        
    <property name="groupToRoleMap">
        <util:map>
            <entry key="SystemAdministrators" value="ROLE_SYSADMIN" />
            <entry key="Maint"  value="ROLE_MAINT" />
            <entry key="General"value="ROLE_USER" />

        </util:map>
    </property>
</bean> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM