[已编辑]
我已尽力解决问题。我设法以测试用户身份登录,这将我重定向到home组件并显示用户名。
之所以能够做到这一点,是因为在Controller中,我将equals方法的参数名称更改为John
和test
:
return user.getCname().equals("John") && user.getPassword().equals("test");
这将我带到应该显示Hi John
的主页,但向我显示了此信息:
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();
} }