Spring Security in Standalone Application

大城市里の小女人 提交于 2021-02-18 07:38:25

问题


How do I use Spring Security in a standalone application. I just need to use the Authentication portion of Spring Security. I need to authenticate users against Windows Active Directory. There are lots of examples in the web for using spring security in Servlets but couldn't find much for using them in standalone applications.

I am only looking for something to complete this method

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

回答1:


You can use the ActiveDirectoryLdapAuthenticationProvider from spring-security-ldap if you just need to do authentication.

Just create a bean in your application context like:

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

Then use it like

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

I haven't tried above code by myself, but looks reasonable. Below link to javadoc for convenience SecurityContextHolder



来源:https://stackoverflow.com/questions/11076784/spring-security-in-standalone-application

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!