Angular 6-可观察的订阅不起作用

时间:2019-03-05 13:01:52

标签: java angular spring spring-boot

[已编辑]

我已尽力解决问题。我设法以测试用户身份登录,这将我重定向到home组件并显示用户名。

之所以能够做到这一点,是因为在Controller中,我将equals方法的参数名称更改为Johntest

return user.getCname().equals("John") && user.getPassword().equals("test");

这将我带到应该显示Hi John的主页,但向我显示了此信息:

homepage error

家庭组件:

export class HomeComponent implements OnInit {

    cname: string;
    constructor(private http: HttpClient) { }

    ngOnInit() {
        const url = 'http://localhost:8080/api/user';

        const headers: HttpHeaders = new HttpHeaders({
            'Authorization': 'Basic ' + sessionStorage.getItem('token')
        });

        const options = { headers: headers };
        this.http.post<Observable<Object>>(url, {}, options).
            subscribe(principal => {
                this.cname = principal['name'];
            },
            error => {
                if (error.status === 401) {
                    alert('Unauthorized');
                }
            }
        );
    }

登录组件:

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Component({
    selector: 'login',
    templateUrl: './login.component.html'
})

export class LoginComponent implements OnInit {

    model: any = {};


    constructor(
        private route: ActivatedRoute,
        private router: Router,
        private http: HttpClient
    ) { }

    ngOnInit() {
        sessionStorage.setItem('token', '');
    }

    login() {
        const url = 'http://localhost:8080/api/login';
        this.http.post<Observable<boolean>>(url, {
            cname: this.model.username,
            password: this.model.password
        }).subscribe(isValid => {
            if (isValid) {
                sessionStorage.setItem('token', btoa(this.model.username + ':' + this.model.password));
                this.router.navigate(['/home']);
            } else {
                alert('Authentication failed.');
                this.router.navigate(['/login']);
            }
        });
    }
}

---

然后我去BasicAuthConfiguration,将“用户”和“密码”的值更改为“约翰”和“测试”,如下所示:

auth.inMemoryAuthentication().withUser("John").password("test").roles("USER");

如果我将字符串设置为SQL表中的值,则可以使用该用户登录。如何避免不对值进行硬编码?

客户控制器:

@CrossOrigin(origins = "http://localhost:4200")
@RestController
@RequestMapping("/api")
public class CustomerController {

    @Autowired
    CustomerRepository repository;

    @RequestMapping("/login")
    public boolean login(@RequestBody Customer user) {
        return
          user.getCname().equals("user") && user.getPassword().equals("password");
    }

    @RequestMapping("/user")
    public Principal user(HttpServletRequest request) {
        String authToken = request.getHeader("Authorization")
          .substring("Basic".length()).trim();
        return () ->  new String(Base64.getDecoder()
          .decode(authToken)).split(":")[0];
    }

基本身份验证配置

@Configuration
@EnableWebSecurity
public class BasicAuthConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests().antMatchers("/api/**").permitAll().anyRequest().authenticated().and()
                .httpBasic().and().cors();

} }

错误

enter image description here

enter image description here

0 个答案:

没有答案