ASP.NET Core API / Angular - 认证问题
创始人
2024-11-11 22:30:39
0

在ASP.NET Core API和Angular应用中处理认证问题的解决方法如下:

  1. 在ASP.NET Core API中配置认证: 在Startup.cs文件的ConfigureServices方法中添加以下代码来配置认证服务:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = Configuration["Jwt:Issuer"],
            ValidAudience = Configuration["Jwt:Audience"],
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
        };
    });

这将配置JWT身份验证,并使用appsettings.json文件中的密钥和签发者进行验证。请确保在appsettings.json文件中配置正确的密钥和签发者。

  1. 生成并返回JWT令牌: 在登录请求成功后,您需要生成JWT令牌并将其返回给Angular应用。您可以使用以下代码生成JWT令牌:
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(Configuration["Jwt:Key"]);
var tokenDescriptor = new SecurityTokenDescriptor
{
    Subject = new ClaimsIdentity(new Claim[]
    {
        new Claim(ClaimTypes.Name, user.Username)
    }),
    Expires = DateTime.UtcNow.AddDays(7),
    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token);
return Ok(new { Token = tokenString });
  1. 在Angular中处理认证: 在Angular应用中,您需要使用HttpClient模块发送带有JWT令牌的请求。您可以使用以下代码配置HttpClient模块:
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { JwtInterceptor } from './jwt.interceptor';

@NgModule({
  imports: [HttpClientModule],
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true }
  ]
})
export class AppModule { }

这将配置Angular应用以在每个请求中添加JWT令牌。

  1. 创建JWT拦截器: 创建一个名为jwt.interceptor.ts的文件,并添加以下代码来创建一个拦截器来在请求中添加JWT令牌:
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class JwtInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest, next: HttpHandler): Observable> {
    const token = localStorage.getItem('token');
    if (token) {
      request = request.clone({
        setHeaders: {
          Authorization: `Bearer ${token}`
        }
      });
    }
    return next.handle(request);
  }
}

这将在每个请求中添加名为Authorization的标头,其值为Bearer加上JWT令牌。

  1. 在Angular中登录并处理JWT令牌: 在登录组件中,您可以使用以下代码来处理登录请求并保存JWT令牌:
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-login',
  template: `
    
` }) export class LoginComponent { username: string; password: string; constructor(private http: HttpClient) { } login() { this.http.post('api/login', { username: this.username, password: this.password }).subscribe(response => { localStorage.setItem('token', response.token); }); } }

这将在登录成功后将JWT令牌保存在localStorage中。

这些是处理ASP.NET Core API和Angular应用中的认证问题的基本解决方法和示例代码。您可以根据自己的需求和应用场景进行适当的调整和修改。

相关内容

热门资讯

安卓换鸿蒙系统会卡吗,体验流畅... 最近手机圈可是热闹非凡呢!不少安卓用户都在议论纷纷,说鸿蒙系统要来啦!那么,安卓手机换上鸿蒙系统后,...
app安卓系统登录不了,解锁登... 最近是不是你也遇到了这样的烦恼:手机里那个心爱的APP,突然就登录不上了?别急,让我来帮你一步步排查...
windows官网系统多少钱 Windows官网系统价格一览:了解正版Windows的购买成本Windows 11官方价格解析微软...
安卓系统拦截短信在哪,安卓系统... 你是不是也遇到了这种情况:手机里突然冒出了很多垃圾短信,烦不胜烦?别急,今天就来教你怎么在安卓系统里...
iwatch怎么连接安卓系统,... 你有没有想过,那款时尚又实用的iWatch,竟然只能和iPhone好上好?别急,今天就来给你揭秘,怎...
iphone系统与安卓系统更新... 最近是不是你也遇到了这样的烦恼?手机更新系统总是失败,急得你团团转。别急,今天就来给你揭秘为什么iP...
安卓系统要维护多久,安卓系统维... 你有没有想过,你的安卓手机里那个陪伴你度过了无数日夜的安卓系统,它究竟要陪伴你多久呢?这个问题,估计...
安卓系统如何卸载app,轻松掌... 手机里的App越来越多,是不是感觉内存不够用了?别急,今天就来教你怎么轻松卸载安卓系统里的App,让...
安卓系统怎么连不上carlif... 安卓系统无法连接CarLife的原因及解决方法随着智能手机的普及,CarLife这一车载互联功能为驾...
安卓系统应用怎么重装,安卓应用... 手机里的安卓应用突然罢工了,是不是让你头疼不已?别急,今天就来手把手教你如何重装安卓系统应用,让你的...