问题
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