Angular2框架获取JWT令牌

时间:2017-06-10 06:06:23

标签: angular jwt

我有一个返回JWT的SpringBoot后端Java应用程序。这是我的代码

@RequestMapping(value = "/admin/login", method = RequestMethod.POST)
        public String login(@RequestBody Customer login) throws ServletException {

            String jwtToken = "";

            if (login.getUsername()== null || login.getPassword()== null) {
                throw new ServletException("Please fill in username and password");
            }

            String username = login.getUsername();
            String password = login.getPassword();

            Customer customer = customerservice.findByusername(username);

            if (customer == null) {
                throw new ServletException("Username not found.");
            }

            String pwd = customer.getPassword();

            if (!password.equals(pwd)) {
                throw new ServletException("Invalid login. Please check your name and password.");
            }

            jwtToken = Jwts.builder().setSubject(username).claim("roles", "administrator").setIssuedAt(new Date())
                    .signWith(SignatureAlgorithm.HS256, "ZGVkeXB1amk=").compact();

            return jwtToken;
        }

它像这样返回TEXT

  

eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJkZWR5cHVqaSIsInJvbGVzIjoiYWRtaW5pc3RyYXRvciIsImlhdCI6MTQ5NzA3NDQ3OX0.i7CjOhNScJRZc5dKhGaNFwje_5-PcOWDwlHD68fmOrw

如何在我的angular2代码中保存该令牌并获取用户名

这是我到目前为止的angular2代码

服务

import { Injectable } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

import {CustomerData} from '../model/customer';
import {Auth} from '../model/auth';

@Injectable()
export class CustomerService {

  private headers = new Headers({'Content-Type': 'application/json'});
  constructor(private http: Http) { }

  registerCustomer( registerdata:CustomerData){
    return this.http.post("http://localhost:8080/customer/new", JSON.stringify(registerdata), {headers: this.headers})
    .map((res: Response) => res.json())
    .catch((error:any) => Observable.throw(error.json().error || 'Server error'));
  }

  login(auth:Auth){

    return this.http.post("http://localhost:8080/admin/login", JSON.stringify(auth), {headers: this.headers})
    .map((response: Response) => {
                // login successful if there's a jwt token in the response
                let token = response.json() && response.json().token;
                if (token) {
                    // store username and jwt token in local storage to keep user logged in between page refreshes
                    localStorage.setItem('currentUser', JSON.stringify({ username: auth.username, token: token }));

                    // return true to indicate successful login
                    return true;
                } else {
                    // return false to indicate failed login
                    return false;
                }
            }).catch((error:any) => Observable.throw(error.json().error || 'Server error'));

  }


  }

班级模型Auth

export class Auth {
    public username:string;
    public password:string;
}

和登录组件

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import {CustomerService} from '../services/customer.service';
import {Auth} from '../model/auth';




@Component({
  selector: 'app-app-login-admin',
  templateUrl: './app-login-admin.component.html',
  styleUrls: ['./app-login-admin.component.css'],
  providers:[CustomerService]

})
export class AppLoginAdminComponent implements OnInit {

  auth: Auth = new Auth();
  login_admin: FormGroup;
  private tmpresult: String = '';
  err: string;

  constructor(
    private fb: FormBuilder,
    private service: CustomerService,

    ) {}

  ngOnInit() {
      this.login_admin = this.fb.group({
      username: ['', [Validators.required, Validators.minLength(2)]],
      password: ['', [Validators.required, Validators.minLength(2)]],
    });
  }

  onSubmit() {
    this.service.login(this.login_admin.value)
  }

}

如果我运行代码。什么也没有回报。 IDK哪里出错了?我检查谷歌浏览器的开发者工具并检查本地存储,但没有任何令牌出现在那里。请帮忙。谢谢:))

1 个答案:

答案 0 :(得分:0)

有几个错误。

  1. 您实际上从未发送过POST请求,因为您从未订阅login()方法返回的observable。
  2. 您的服务需要一个包含属性token的JSON对象。但是你的弹簧控制器并没有返回JSON。它返回一个String。
  3. 您不需要调用JSON.stringify()并使用HTTP服务传递Content-Type标头。只需传递要发送的对象,然后将服务字符串化为您,并设置相应的内容类型。