Angular与ASP.NET Core 2 Web API的认证项目教程

随着前后端分离架构的普及,Angular与ASP.NET Core的结合越来越受到开发者的青睐。本教程将带您一步步构建一个简单的Angular与ASP.NET Core 2 Web API的认证项目。

项目准备

  1. 环境要求
  2. .NET Core SDK(2.1及以上)
  3. Node.js(8.x及以上)
  4. Angular CLI(8.x及以上)

  5. 创建ASP.NET Core Web API项目: 使用命令行工具创建一个新的ASP.NET Core Web API项目: bash dotnet new webapi -n AuthExample cd AuthExample

  6. 创建Angular项目: 使用Angular CLI创建一个新的Angular项目: bash ng new AuthFrontend cd AuthFrontend ng serve

ASP.NET Core Web API 实现

1. 安装必要的包

在项目目录中,打开命令行,添加JWT认证支持:

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

2. 配置Startup.cs

Startup.cs中配置JWT认证和CORS:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("AllowAll", builder =>
        {
            builder.AllowAnyOrigin()
                   .AllowAnyMethod()
                   .AllowAnyHeader();
        });
    });

    var key = Encoding.ASCII.GetBytes("your_secret_key_here");
    services.AddAuthentication(x =>
    {
        x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(x =>
    {
        x.RequireHttpsMetadata = false;
        x.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(key),
            ValidateIssuer = false,
            ValidateAudience = false
        };
    });

    services.AddControllers();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseHsts();
    }

    app.UseCors("AllowAll");
    app.UseAuthentication();
    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

3. 创建用户控制器

Controllers文件夹中创建AuthController.cs以处理登录请求:

[ApiController]
[Route("[controller]")]
public class AuthController : ControllerBase
{
    [HttpPost("login")]
    public IActionResult Login([FromBody] UserLogin userLogin)
    {
        // 这里你应该验证用户
        if (userLogin.Username != "test" || userLogin.Password != "password")
            return Unauthorized();

        var tokenHandler = new JwtSecurityTokenHandler();
        var key = Encoding.ASCII.GetBytes("your_secret_key_here");
        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(new Claim[]
            {
                new Claim(ClaimTypes.Name, userLogin.Username)
            }),
            Expires = DateTime.UtcNow.AddHours(1),
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
        };
        var token = tokenHandler.CreateToken(tokenDescriptor);
        return Ok(new { Token = tokenHandler.WriteToken(token) });
    }
}

public class UserLogin
{
    public string Username { get; set; }
    public string Password { get; set; }
}

Angular 前端实现

1. 安装HTTP客户端模块

在Angular项目中安装HTTP模块:

ng generate service auth

2. 创建认证服务

auth.service.ts中实现用户登录功能:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  private baseUrl = 'http://localhost:5000/auth'; // 你的 API 地址

  constructor(private http: HttpClient) { }

  login(username: string, password: string): Observable<any> {
    return this.http.post(`${this.baseUrl}/login`, { username, password });
  }
}

3. 创建登录组件

创建一个简单的登录组件,让用户输入用户名和密码:

import { Component } from '@angular/core';
import { AuthService } from '../auth.service';

@Component({
  selector: 'app-login',
  template: `
    <form (submit)="onSubmit()">
      <input [(ngModel)]="username" placeholder="Username" required>
      <input [(ngModel)]="password" type="password" placeholder="Password" required>
      <button type="submit">Login</button>
    </form>
    <div *ngIf="token">Token: {{ token }}</div>
  `
})
export class LoginComponent {
  username: string;
  password: string;
  token: string;

  constructor(private authService: AuthService) { }

  onSubmit() {
    this.authService.login(this.username, this.password).subscribe(response => {
      this.token = response.token;
    }, error => {
      console.error(error);
    });
  }
}

4. 在模板中使用登录组件

最后,将登录组件添加到app.component.html中:

<app-login></app-login>

总结

通过以上步骤,我们成功创建了一个使用ASP.NET Core 2 Web API进行JWT身份验证的Angular项目。用户可以通过用户界面进行登录,系统将返回一个JWT令牌,以便进行后续的认证授权处理。这为现实应用程序提供了基本的认证机制,后续可以根据需求扩展功能,比如密码加密、角色管理等。希望这个简单的示例能帮助您快速了解Angular与ASP.NET Core的集成及认证实现。

点赞(0) 打赏

微信小程序

微信扫一扫体验

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部