angular token 认证


Angular2端

创建View Model

在wwwroot/app下创建一个目录:_model, 并添加一个Typescript文件RequestResult.ts,内容应该是这样。

export class RequestResult {
    State: number;
    Msg: string;
    Data: Object;
}

 

创建Service

在wwwroot/app下创建一个目录:_services,并添加一个Typescript文件auth.service.ts,内容应该是这样。

复制代码
import { Injectable } from "@angular/core";
import { Headers, Http } from "@angular/http";
import "rxjs/add/operator/toPromise";

import { RequestResult } from "../_model/RequestResult";

@Injectable()
export class AuthService {
    private tokeyKey = "token";
    private token: string;

    constructor(
        private http: Http
    ) { }

    login(userName: string, password: string): Promise<RequestResult> {
        return this.http.post("/api/TokenAuth", { Username: userName, Password: password }).toPromise()
            .then(response => {
                let result = response.json() as RequestResult;
                if (result.State == 1) {
                    let json = result.Data as any;

                    sessionStorage.setItem("token", json.accessToken);
                }
                return result;
            })
            .catch(this.handleError);
    }

    checkLogin(): boolean {
        var token = sessionStorage.getItem(this.tokeyKey);
        return token != null;
    }

    getUserInfo(): Promise<RequestResult> {
        return this.authGet("/api/TokenAuth");
    }

    authPost(url: string, body: any): Promise<RequestResult> {
        let headers = this.initAuthHeaders();
        return this.http.post(url, body, { headers: headers }).toPromise()
            .then(response => response.json() as RequestResult)
            .catch(this.handleError);
    }

    authGet(url): Promise<RequestResult> {
        let headers = this.initAuthHeaders();
        return this.http.get(url, { headers: headers }).toPromise()
            .then(response => response.json() as RequestResult)
            .catch(this.handleError);
    }

    private getLocalToken(): string {
        if (!this.token) {
            this.token = sessionStorage.getItem(this.tokeyKey);
        }
        return this.token;
    }

    private initAuthHeaders(): Headers {
        let token = this.getLocalToken();
        if (token == null) throw "No token";

        var headers = new Headers();
        headers.append("Authorization", "Bearer " + token);

        return headers;
    }

    private handleError(error: any): Promise<any> {
        console.error('An error occurred', error);
        return Promise.reject(error.message || error);
    }
}
复制代码

本文件主要用来完成登录以及登录验证工作,之后该service将可以被注入到Component中以便被Component调用。

注:主要的逻辑都应该写到service中

创建Component

在wwwroot/app下创建一个目录home,该目录用来存放HomeComponent,home应拥有如下文件:

  • home.component.ts

    复制代码
    import { Component, OnInit } from "@angular/core";
    
    import { AuthService } from "../_services/auth.service";
    
    @Component({
        moduleId: module.id,
        selector: "my-home",
        templateUrl: "view.html",
        styleUrls: ["style.css"]
    })
    export class HomeComponent implements OnInit {
        isLogin = false;
        userName: string;
        
        constructor(
            private authService: AuthService
        ) { }
    
        ngOnInit(): void {
            this.isLogin = this.authService.checkLogin();
            if (this.isLogin) {
                this.authService.getUserInfo().then(res => {
                    this.userName = (res.Data as any).UserName;
                });
            }
    
        }
    }
    复制代码

    查阅代码,在@Component中指定了View以及style。

    AuthService被在构造方法中被注入了本Component,ngOnInit是接口OnInit的一个方法,他在Component初始化时会被调用。

  • style.css

    /*styles of this view*/

    本例中没有添加任何样式,如有需要可以写在这里。

  • view.html

    复制代码
    <div *ngIf="isLogin">
        <h1>Hi <span>{{userName}}</span></h1>
    </div>
    
    <div *ngIf="!isLogin">
        <h1>please login</h1>
        <a routerLink="/login">Login</a>
    </div>
    复制代码

    *ngIf=""是Angular2 的其中一种标记语法,作用是当返回真时渲染该节点,完整教程请参阅官方文档。

在wwwroot/app下创建目录Login,该目录用来存放LoginComponent,文件结构类似于上一节。

  • login.component.ts

    复制代码
    import { Component } from "@angular/core";
    import { Router } from '@angular/router';
    
    import { AuthService } from "../_services/auth.service";
    
    @Component({
        moduleId: module.id,
        selector: "my-login",
        templateUrl: "view.html",
        styleUrls: ["style.css"]
    })
    export class LoginComponent {
    
        private userName: string;
        private password: string;
    
        constructor(
            private authService: AuthService,
            private router: Router
        ) { }
    
        login() {
            this.authService.login(this.userName, this.password)
                .then(result => {
                    if (result.State == 1) {
                        this.router.navigate(["./home"]);
                    }
                    else {
                        alert(result.Msg);
                    }
                });
        }
    }
    复制代码
  • style.css

    /*styles of this view*/
  • view.html

    复制代码
    <table>
        <tr>
            <td>userName:</td>
            <td><input [(ngModel)]="userName" placeholder="useName:try type user1" /></td>
        </tr>
        <tr>
            <td>userName:</td>
            <td><input [(ngModel)]="password" placeholder="password:try type user1psd" /></td>
        </tr>
        <tr>
            <td></td>
            <td><input type="button" (click)="login()" value="Login" /></td>
        </tr>
    </table>
    复制代码

应用路由

路由是切换多页面用的。

在wwwroot/app下新建一个Typescript文件,命名为app-routing.module.ts,内容应该是这个样子。

复制代码
import { NgModule } from "@angular/core";
import { RouterModule, Routes } from "@angular/router";

import { HomeComponent } from "./home/home.component";
import { LoginComponent } from "./login/login.component"

const routes: Routes = [
    { path: "", redirectTo: "/home", pathMatch: "full" },
    { path: "home", component: HomeComponent },
    { path: "login", component: LoginComponent }
];

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class AppRoutingModule { }
复制代码

 

接下来我们来应用这个路由,

打开app.module.ts,更新代码如下:

复制代码
import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";
import { HttpModule } from "@angular/http";
import { FormsModule } from "@angular/forms";

import { AppRoutingModule } from "./app-routing.module";

import { AuthService } from "./_services/auth.service";

import { AppComponent } from "./app.component";
import { HomeComponent } from "./home/home.component";
import { LoginComponent } from "./login/login.component";

@NgModule({
    bootstrap: [AppComponent],
    imports: [
        BrowserModule,
        HttpModule,
        AppRoutingModule,
        FormsModule
    ],
    declarations: [
        AppComponent,
        HomeComponent,
        LoginComponent
    ],
    providers: [AuthService]
})
export class AppModule { }
复制代码

 

NgModule和BrowserModule你可以理解为基础模块,必加的。

HttpModule是做http请求用的。

FormsModule是做双向数据绑定用的,比如下面这样的,如果想把数据从view更新到component,就必须加这个。

<input [(ngModel)]="userName" placeholder="useName:try type user1" />

 

AppRoutingModule即为我们刚才添加的路由文件。

AuthService是我们最早添加的service文件。

AppComponent是我们最初添加的那个app.component.ts里的那个component.

HomeComponent,LoginComponent同上。

 

最后我们再app.component.ts中添加路由锚点,

把template的值为 "<router-outlet></router-outlet>"

完整的代码应该是这样:

复制代码
import { Component } from '@angular/core';

@Component({
    moduleId: module.id,
    selector: 'my-app',
    template: "<router-outlet></router-outlet>",
})
export class AppComponent {
}
复制代码

 

router-outlet是路由锚点的关键词。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM