步骤
1、客户端添加headers
cities.service.ts
import { Injectable } from '@angular/core';
import { City } from "../models/city";
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { Observable } from "rxjs";
const API_BASE_URL: string = "https://localhost:7173/api/";
@Injectable({
providedIn: 'root'
})
export class CitiesService {
cities: City[] = [];
constructor(private httpClient: HttpClient) {
}
public getCities(): Observable<City[]> {
let headers = new HttpHeaders();
headers = headers.append("Authorization", `Bearer ${localStorage["token"]}`);
return this.httpClient.get<City[]>(`${API_BASE_URL}v1/cities`, { headers: headers })
}
public postCity(city: City): Observable<City> {
let headers = new HttpHeaders();
headers = headers.append("Authorization", `Bearer ${localStorage["token"]}`);
return this.httpClient.post<City>(`${API_BASE_URL}v1/cities`, city, { headers: headers })
}
public putCity(city: City): Observable<string> {
let headers = new HttpHeaders();
headers = headers.append("Authorization", `Bearer ${localStorage["token"]}`);
return this.httpClient.put<string>(`${API_BASE_URL}v1/cities/${city.cityID}`, city, { headers: headers })
}
public deleteCity(cityID: string | null): Observable<string> {
let headers = new HttpHeaders();
headers = headers.append("Authorization", `Bearer ${localStorage["token"]}`);
return this.httpClient.delete<string>(`${API_BASE_URL}v1/cities/${cityID}`, { headers: headers })
}
}
2、Logout清除token
app.component.ts添加localStorage.removeItem("token");
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { AccountService } from './services/account.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(public accountService: AccountService, private router: Router) { }
onLogOutClicked() {
this.accountService.getLogout().subscribe({
next: (response: string) => {
this.accountService.currentUserName = null;
localStorage.removeItem("token");
this.router.navigate([ '/login' ]);
},
error: (error: any) => {
console.log(error);
},
complete: () => { },
});
}
}
3、服务器验证Token
CitiesManager.WebAPI项目安装如下NuGet包
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.6" />
Program.cs
//JWT
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateAudience = true,
ValidAudience = builder.Configuration["Jwt: Audience"],
ValidateIssuer = true,
ValidIssuer = builder.Configuration["Jwt: Issuer"],
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
};
});
builder.Services.AddAuthorization(options =>
{
});
var app = builder.Build();
全局应用到Controller(也可以DataAnnotation应用到需要的Controller)
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers(options =>
{
options.Filters.Add(new ProducesAttribute("application/json")); //Response Body
options.Filters.Add(new ConsumesAttribute("application/json")); //Request Body
//JWT-Authorization policy
var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
options.Filters.Add(new AuthorizeFilter(policy));
}).AddXmlSerializerFormatters();
排除在外可以添加[AllowAnonymous]
Gitee获取源码:
https://gitee.com/huang_jianhua0101/asp.-net-core-8.git
标签:338,builder,JWT,headers,token,import,new,options,Authorization From: https://blog.csdn.net/KevinHuang2088/article/details/140110554