У меня большая проблема .Я сижу здесь и сейчас несколько дней думаю о том, как заставить работать мое приложение для входа в систему .Я хочу отправить имя пользователя и пароль для весенней загрузки , где это будет проверено.Базовый материал в Spring boot уже работает (loginForm).Я довольно новичок в программировании с Spring Boot , потому что раньше я работал с NodeJS.Цель состоит в том, чтобы проверять пользователей через LDAP в Backend, но с Spring Security, а не с Pure Java (было бы легко) .Все это, конечно, ведьма HTTP-запросы (конечные точки)
Вот что у меня есть до сих пор:
// WebSecurityConfiguration
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().fullyAuthenticated()
.and()
.formLogin()
.loginPage("/test").permitAll()
.usernameParameter("_username_")
.passwordParameter("_password_")
.and()
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.ldapAuthentication()
.userDnPatterns("uid={0},ou=people")
.groupSearchBase("ou=groups")
.contextSource()
.url("ldap://localhost:8389/dc=springframework,dc=org")
.and()
.passwordCompare()
.passwordEncoder(new LdapShaPasswordEncoder())
.passwordAttribute("userPassword");
}
@Bean
public DefaultSpringSecurityContextSource contextSource() {
return new DefaultSpringSecurityContextSource(Arrays.asList("ldap://localhost:8389/"), "dc=springframework,cd=org");
}
Я использую Gradle, потому что мы его используемв нашей компании по умолчанию, так что вот build.gradle :
// build.gradle
plugins {
id 'org.springframework.boot' version '2.1.2.RELEASE'
id 'java'
}
apply plugin: 'io.spring.dependency-management'
group = 'net.company'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-ldap'
implementation 'org.springframework.boot:spring-boot-starter-data-rest'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-web-services'
implementation 'org.springframework.boot:spring-boot-starter-websocket'
implementation 'org.springframework.boot:spring-boot-starter-security'
runtimeOnly 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'mysql:mysql-connector-java'
compileOnly 'org.projectlombok:lombok'
compile("org.springframework.ldap:spring-ldap-core")
compile("org.springframework.security:spring-security-ldap")
compile("org.springframework:spring-tx")
compile("com.unboundid:unboundid-ldapsdk")
compile group: 'javax.xml.bind', name: 'jaxb-api', version: '2.2.4'
compile group: 'org.glassfish.jaxb', name: 'jaxb-core', version: '2.3.0.1'
compile group: 'javax.xml', name: 'jaxb-impl', version: '2.1'
compile group: 'javax.activation', name: 'activation', version: '1.1.1'
testCompile("org.springframework.boot:spring-boot-starter-test")
testCompile("org.springframework.security:spring-security-test")
}
И это мой app.component.ts на данный момент.Я уже импортировал модуль HttpClientModule и добавил его в import :
// app.component.ts
import {Component} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import * as Stomp from 'stompjs';
import * as SockJS from 'sockjs-client';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Memory';
status: string;
greeting = {};
private serverUrl = 'http://localhost:8082/';
private stompClient;
constructor(private http: HttpClient) {
this.initializeWebSocketConnection();
http.get(this.serverUrl + 'login').subscribe(data => data);
}
initializeWebSocketConnection() {
let ws = new SockJS(this.serverUrl);
this.stompClient = Stomp.over(ws);
let that = this;
this.stompClient.connect({}, function(frame) {
that.stompClient.subscribe('/chat', (message) => {
console.log(message);
});
});
}
sendMessage(msg) {
this.stompClient.send('/app/send/message', {}, msg);
}
ngOnInit() {
this.setStatus('login');
setTimeout(() => {
this.sendMessage('test =>');
}, 5000);
}
setStatus(status): void {
this.status = status;
}
}
Приложение для входа в систему Look
// login.component.html
<div id="container"
fxLayout="column"
fxLayoutAlign="start center">
<div class="spacer" fxFlex="10%"></div>
<div id="login" fxFlex="25%"
fxLayout="column"
fxLayoutAlign="start center">
<h1 id="loginTitle" fxFlex="35%">LOGIN</h1>
<label for="user"></label><input id="user" placeholder="username" fxFlex="17.5%" onkeydown="if (event.keyCode == 13) document.getElementById('loginButton').click()"/>
<div class="spacer" fxFlex="10%"></div>
<label for="password"></label><input type="password" id="password" placeholder="password" fxFlex="17.5%" onkeydown="if (event.keyCode == 13) document.getElementById('loginButton').click()"/>
<div class="spacer" fxFlex="10%"></div>
<img id="loginButton" src="../../assets/login/img/right-arrow.png" fxFlex="10%" alt="">
</div>
<div id="spacer" fxFlex="74%"></div>
<div id="attention" fxFlex="1%">Icons made by <a href="https://www.flaticon.com/authors/lyolya" title="Lyolya">Lyolya</a></div>
</div>
Здесь application.properties для тех, кому нужна информация о LDAP материалах ( application.yml на данный момент пусто ):
// application.properties
spring.ldap.embedded.ldif=classpath:test-server.ldif
spring.ldap.embedded.base-dn=dc=springframework,dc=org
spring.ldap.embedded.port=8389
server.servlet.context-path=/
server.port=8082
Если вам нужна дополнительная информация или файлы, просто напишите мне в личку. Я проведу рефакторинг этой статьи, если мы найдем решение, так что его легко понять всем начинающим.