How to implement Windows Authentication with Angular 2 and above with backend as JAVA. I searched all the places but only seeing the Web API as solution which is specific to .NET
Asked
Active
Viewed 723 times
1 Answers
0
Following Code authenticates from LDAP using pure Java JNDI. The Principle is:-
First Lookup the user using a admin or DN user.
The user object needs to be passed to LDAP again with the user credential.
No Exception means - Authenticated Successfully. Else Authentication Failed.
public static boolean authenticateJndi(String username, String password) throws Exception{
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
props.put(Context.PROVIDER_URL, "ldap://LDAPSERVER:PORT");
props.put(Context.SECURITY_PRINCIPAL, "uid=adminuser,ou=special users,o=xx.com");//adminuser - User with special priviledge, dn user
props.put(Context.SECURITY_CREDENTIALS, "adminpassword");//dn user password
InitialDirContext context = new InitialDirContext(props);
SearchControls ctrls = new SearchControls();
ctrls.setReturningAttributes(new String[] { "givenName", "sn","memberOf" });
ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<javax.naming.directory.SearchResult> answers = context.search("o=xx.com", "(uid=" + username + ")", ctrls);
javax.naming.directory.SearchResult result = answers.nextElement();
String user = result.getNameInNamespace();
try {
props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
props.put(Context.PROVIDER_URL, "ldap://LDAPSERVER:PORT");
props.put(Context.SECURITY_PRINCIPAL, user);
props.put(Context.SECURITY_CREDENTIALS, password);
context = new InitialDirContext(props);
} catch (Exception e) {
return false;
}
return true;
}
More on
LDAP Authentication using Java.
For angular and spring boot ,
Have a login controller , pass username and password to that controller and then validate the user.Use httpsession for subsequent requests.
@RestController
public class HomeController {
@PostMapping("/")
public String index(@RequestBody User user,HttpSession httpSession) {
if(authenticateJndi(user.getUsername(),user.getPassword()))
{
// Login success
httpSession.setAttribute("userName",user.getUsername()),;
}
else
{
// Login failed
}
}
}

Srinivasan Sekar
- 2,049
- 13
- 22
-
I agree Srinivasan but the thing is how angular will pick the username and password, after picking the username password then only i can pass it to backend right – Saurabh Singh May 08 '19 at 10:00
-
show login page or do authentication while loading the html/ftl/index.html. You can find many example by searching spring boot ldap. – Srinivasan Sekar May 08 '19 at 11:05