简体   繁体   中英

Login application using xAuthToken , spring redis and security

I am new in angular and trying to develop a login application using spring boot, redis, spring security and Angular. I am following an Angular 2 tutorial while using Angular 5 and tried to convert all the code into Angular 5. Even though I converted most of the code, I couldn't convert localStorage.setItem("xAuthToken", res.json().token); line since this code was related to Http of Angular 2. My question is what is the equivalent of it? Below are what I did till now.

loging.service.ts

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class LoginService {

  constructor(private http: HttpClient) { }

  sendCredential(username: string, password: string) {

    //console.log("User -- > "+username,+"Pass -- > "+password);
    let url = "http://localhost:8181/token";
    let encodedCredentials = btoa(username + ":" + password);
    let basicHeader = "Basic " + encodedCredentials;
    let headers = new HttpHeaders({
      'Content-Type': 'application/x-www-form-urlencoded',
      'Authorization': basicHeader
    });

    return this.http.get(url, { headers: headers });

  }

 checkSession() {
    let url = "http://localhost:8181/checkSession";

    let headers = new HttpHeaders({
      'x-auth-token': localStorage.getItem('xAuthToken')
    });

    return this.http.get(url, { headers: headers });
  }
}

login.component.ts

import { Component, OnInit } from '@angular/core';
import {LoginService} from '../../services/login.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  private credential = {'username':'', 'password' : ''};
  private loggedIn = false;

  constructor(private loginService: LoginService) { }

  onSubmit() {
    this.loginService.sendCredential(this.credential.username, this.credential.password).subscribe(
        res => {
            console.log(res);
        localStorage.setItem("xAuthToken", res.json().token);
            this.loggedIn = true;
            location.reload();
        },
        error => {
            console.log(error);
        }
    );
  }

  ngOnInit() {
    this.loginService.checkSession().subscribe(
        res => {
            this.loggedIn=true;
        },
        error => {
            this.loggedIn=false;
        }
    );
  }

}

I am getting error:

Property 'json' does not exist on type 'Object' with existing code.

只需添加这个,它就会被解决:

localStorage.setItem("xAuthToken", res.token);

localStorage.setItem("xAuthToken", JSON.stringify(res)); "Appaji " This is pakka answer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM