下面是一个使用ASP.NET Core身份验证和Web API与Angular前端配合的代码示例:
首先,创建一个ASP.NET Core Web API项目。
public void ConfigureServices(IServiceCollection services)
{
// 添加身份验证服务
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "your-issuer",
ValidAudience = "your-audience",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-secret-key"))
};
});
// 添加其他服务...
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// 其他中间件...
// 启用身份验证中间件
app.UseAuthentication();
// 其他中间件...
app.UseRouting();
// 其他中间件...
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
[Route("api/[controller]")]
[ApiController]
[Authorize] // 添加授权特性
public class ValuesController : ControllerBase
{
[HttpGet]
public ActionResult> Get()
{
// 从用户身份信息中获取用户名
var username = User.Identity.Name;
return new string[] { "value1", "value2" };
}
}
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ApiService {
private apiUrl = 'http://localhost:5000/api/values';
constructor(private http: HttpClient) { }
getValues(): Observable {
const token = 'your-jwt-token';
// 添加身份验证头部
const headers = new HttpHeaders().set('Authorization', `Bearer ${token}`);
return this.http.get(this.apiUrl, { headers });
}
}
import { Component, OnInit } from '@angular/core';
import { ApiService } from './api.service';
@Component({
selector: 'app-root',
template: `
- {{ value }}
`,
})
export class AppComponent implements OnInit {
values: string[];
constructor(private apiService: ApiService) { }
ngOnInit() {
this.apiService.getValues().subscribe(values => {
this.values = values;
});
}
}
以上是一个使用ASP.NET Core身份验证和Web API与Angular前端配合的基本示例。你可以根据你的具体需求进行修改和扩展。