Joh*_*ohn 5 stomp spring-security websocket spring-websocket angular
我有一个使用 ng2-stomp-service 的 Angular 2 应用程序。它与 Spring WebSocket 一起使用,但没有安全性。
但我无法将身份验证凭据发送到 Spring Security。这是 Spring Security 中的配置:
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.httpBasic()
.and()
.authorizeRequests()
.antMatchers("/demo-websocket/info").permitAll()
.antMatchers("/demo-websocket/**/websocket").permitAll()
.antMatchers("/info", "/health").permitAll()
.antMatchers("/info", "/health").permitAll()
.antMatchers("/api/**", "/advisor").hasRole("USER")
.anyRequest().authenticated();
}
}
Run Code Online (Sandbox Code Playgroud)
这是 Spring WebSocket 安全设置:
@Configuration
public class WebSocketSecurityConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer {
@Override
protected void configureInbound(MessageSecurityMetadataSourceRegistry registry) {
registry
.simpTypeMatchers(CONNECT).permitAll()
.simpTypeMatchers(UNSUBSCRIBE, DISCONNECT).permitAll()
.simpMessageDestMatchers("/app/**").permitAll()
.simpSubscribeDestMatchers("/topic/**").permitAll()
.anyMessage().authenticated()
;
}
@Override
protected boolean sameOriginDisabled() {
//disable CSRF for websockets for now...
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,正在使用“permitAll()”,因此它无需身份验证即可工作。但是,如果将“.simpMessageDestMatchers(”/app/ ”).permitAll()”更改为“.simpMessageDestMatchers(”/app/ ”).authenticated()”,则不起作用。
这是 Angular 2 设置:
this.stomp.configure({
host: `http://${config.host}:${config.port}/demo-websocket`,
debug: true,
queue: {'init': false},
headers: {
login: 'user',
passcode: 'password',
authorization: `Basic ${this.calcBase64UserPassword()}`
},
});
Run Code Online (Sandbox Code Playgroud)
连接到 Spring WebSocket 的 Angular 2 代码:
this.subject = new Subject<Greeting>();
this.stomp.startConnect().then(() => {
this.stomp.done('init');
console.log('Connect established.');
this.connected = true;
this.subscription = this.stomp.subscribe('/topic/greetings', this.response.bind(this));
});
Run Code Online (Sandbox Code Playgroud)
通过 Web 套接字发送消息的 Angular 2 代码:
send(messageText: string): void {
if (this.connected) {
const message = new DomainMessage(this.msgId, messageText);
this.stomp.send('/app/hello', message, {
login: 'user',
passcode: 'password'
});
}
}
Run Code Online (Sandbox Code Playgroud)
用于计算基本身份验证 Base 64 标头的 Angular 2 代码:
private calcBase64UserPassword(username = config.username, password = config.password): string {
const result = btoa(`${username}:${password}`);
console.log (`${result}`);
return result;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
810 次 |
| 最近记录: |