简体   繁体   中英

How to Login with Angular by ldap with using Rest and Spring security

I hava problem . I am trying to login in angular form .

My users are in LDAP. I will authenticate by Rest and Spring security

but i don't know how to send username and password to the Backend and to authenticate the user.

This is authentication.service.ts :

export class AuthenticationService {

  private baseUrl = "http://localhost:8090;

  constructor(private http: HttpClient) {
  }

  authentication(username: string, password: string): Observable<Object> {
    const headers = new HttpHeaders({ Authorization: 'Basic ' + btoa(username + ':' + password) });
    return this.http.get(`${this.baseUrl}` + '/' , {headers});
  }
}

This is WebSecurityConfig.java

@EnableWebSecurity(debug = true)
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    private String url = "ldap://dc.msv.net:389";
    private String domain = "msv.net";
    private String bsDn = "DC=msv,DC=net";
    private String userDNPattern = "(&(userPrincipalName={0}))";

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests().antMatchers("/login").permitAll().anyRequest().authenticated()
                .and().formLogin().usernameParameter("username").passwordParameter("password");

    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        ActiveDirectoryLdapAuthenticationProvider adProvider = new ActiveDirectoryLdapAuthenticationProvider(
                domain, url, bsDn);

        adProvider.setConvertSubErrorCodesToExceptions(true);
        adProvider.setUseAuthenticationRequestCredentials(true);
        // Checks with the Distinguished Name pattern provided
        if (this.userDNPattern != null && this.userDNPattern.trim().length() > 0) {
            adProvider.setSearchFilter(this.userDNPattern);
        }

        auth.authenticationProvider(adProvider);

    }

}

Please help me.

You can find a greate article for Spring LDAP here Spring-LDAP

Please use an HeaderInterceptor to set Request Header. Example here:

import {
 HttpInterceptor,
 HttpEvent,
 HttpHandler,
 HttpRequest,
 HttpHeaders
} from '@angular/common/http';

@Injectable()
export class HeaderInterceptor implements HttpInterceptor { 

   addAuthHeader(request) {
     const r: HttpRequest<any> = request.clone({
         headers: new HttpHeaders({
             'Content-Type': 'application/json',
             Authorization: 'Bearer ' + this.userService.getAccessToken()
         })
     });
     return r;
  }
}

And please use the POST-Method to send User-Credentials for Authentication. Regards

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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