【问题标题】:Spring Security in Standalone Application独立应用程序中的 Spring Security
【发布时间】:2015-03-23 16:19:12
【问题描述】:

如何在独立应用程序中使用 Spring Security。我只需要使用 Spring Security 的 Authentication 部分。我需要针对 Windows Active Directory 对用户进行身份验证。网络上有很多在 Servlet 中使用 Spring Security 的示例,但在独立应用程序中使用它们却找不到太多。

我只是在找东西来完成这个方法

boolean isValidCredentials(String username, String password)
{
    //TODO use spring security for authentication here..
}

【问题讨论】:

    标签: spring security


    【解决方案1】:

    如果您只需要进行身份验证,可以使用 spring-security-ldap 中的ActiveDirectoryLdapAuthenticationProvider

    只需在您的应用程序上下文中创建一个 bean,例如:

    <bean id="adAuthProvider" class="org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider">
        <constructor-arg value="your.domain" />
        <constructor-arg value="ldap://your.ad.server" />
    </bean>
    

    然后像这样使用它

    try {
        adAuthProvider.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
    } catch (AuthenticationException ae) {
        // failed
    }
    

    【讨论】:

      【解决方案2】:

      using-spring-security-in-a-swing-desktop-application

      public Authentication authenticate( String username, String password ) {
       UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( username, password );
      
       Authentication auth = _authProvider.authenticate( token );
       if (null != auth) {
         SecurityContextHolder.getContext().setAuthentication( auth );
      
         _eventPublisher.publishEvent( new InteractiveAuthenticationSuccessEvent( auth, this.getClass() ) );
      
         return auth;
       }
       throw new BadCredentialsException( "null authentication" );
       }
      

      我自己没有尝试过上面的代码,但看起来很合理。为方便起见,下面链接到 javadoc SecurityContextHolder

      【讨论】:

        猜你喜欢
        • 2015-08-02
        • 2012-09-20
        • 2012-03-29
        • 1970-01-01
        • 2016-07-04
        • 2021-05-24
        • 1970-01-01
        • 2016-11-20
        相关资源
        最近更新 更多