我有一个问题。我正在尝试以 Angular 形式登录。
我的用户位于 LDAP 中。我将通过 Rest 和 Spring security 进行身份验证
但我不知道如何将用户名和密码发送到后端并对用户进行身份验证。
这是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});
}
}
这是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);
}
}
最佳答案
您可以在这里找到一篇有关 Spring LDAP 的精彩文章 Spring-LDAP
请使用 HeaderInterceptor 设置请求 header 。示例如下:
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;
}
}
请使用 POST 方法发送用户凭据以进行身份验证。
关于java - 如何使用 Rest 和 Spring 安全性通过 ldap 登录 Angular?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57333587/