【发布时间】:2020-05-19 13:44:42
【问题描述】:
我正在建立一个简单的问答网站。前端是 Angular 6,后端是 Spring Boot。我还在使用 Spring Security 和 Redis 来存储会话。我有几个问题。
- 当用户登录时,我看到来自服务器的响应在响应标头中包含 SetCookie: Session: XXXXX,但在随后的调用中,从未在 HEADER 中设置会话属性。我还在 Chrome 的检查模式下检查了应用程序选项卡中的 Cookie。未设置任何值。但是,如果我在 localStorage 中设置任何内容。我可以在那里看到它。
登录代码
login.component.ts (This is called once the user press login)
this.authenticationService.login(this.f.email.value, this.f.password.value)
.pipe(first())
.subscribe(
data => {
// this.router.navigate([this.returnUrl]);
this.router.navigate(['/home']);
},
error => {
this.alertService.error(error);
this.loading = false;
});
AuthenticationService
export class AuthenticationService {
constructor(private http: HttpClient) { }
login(emailId: string, password: string) {
const headers = new HttpHeaders(
emailId && password ? {
authorization:'Basic ' + btoa(emailId + ':' + password)
}:{}
);
return this.http.get<any>(`${environment.apiUrl}/users/login`, {headers:headers})
.pipe(map(user => {
if (user ) {
localStorage.setItem('currentUser', JSON.stringify(user));
console.log("user is " + JSON.stringify(user));
}
return user;
}));
}
SpringBoot
@Override
protected void configure(HttpSecurity http) throws Exception {
logger.info("*********Authorizing in websecurityconfig*********");
http.cors().and()
//starts authorizing configurations
.authorizeRequests()
//ignoring the guest urls...
.antMatchers("/resources/**", "/error","/users/**").permitAll()
.anyRequest().fullyAuthenticated()
.and()
.logout().permitAll()
.logoutRequestMatcher(new AntPathRequestMatcher("/users/logout", "POST"))
.and()
.formLogin().loginPage("/users/login").and()
.httpBasic().and()
.csrf().disable();
}
REST API
@CrossOrigin
@GetMapping("/login")
public ResponseEntity<?> getStudentDetailById (Principal principal) throws Exception{
final String emailId = principal.getName();
try {
ValidationUtil.validate(emailId);
logger.info("Email id is " + emailId);
} catch (InvalidArgumentException e) {
logger.info("Exception = {} occurred", e);
}
return ResponseEntity.ok(principal.getName());
}
这是从服务器收到的登录响应中的 SESSION
设置 Cookie:SESSION=YjBjODE2MjQtMGQxOC00ZmU1LWI2MmMtOTg5YzkwM2FjY2Fm;路径=/; HttpOnly
登录后,假设我想在同一台服务器/另一台服务器上调用另一个 API。该请求不包含会话详细信息。
我错过了什么。
- 我想澄清一下收到的 SESSIONID 的功能和将用户 ID 存储在 localStorage 中的优势。
我的问题
我想在用户登录后获取他/她发布的问题。因此,我需要他/她的用户 ID 在登录后的响应中。因此,登录后,我将用户 ID 存储在 localStorage 中。那么SESSIONID有什么用呢?是否只是为了确保对服务器的后续请求不必一次又一次地进行身份验证,因为 Spring Security 将使用 SESSIONID 来允许用户使用其他资源。如果是,那么 Spring Security 是否会验证每个 SESSIONID 请求(我认为是这样)。
【问题讨论】:
-
您是否在同一台服务器上为 Angular 和 Spring 提供服务?例如。 Spring 是在为您的静态 Angular 构建提供服务,还是从不同的服务器提供 Angular 构建?
-
@NateVaughan 都在不同的服务器上运行。角度:本地主机:4200 SpringBoot:本地主机:8080
标签: angular spring spring-boot spring-security redis