在ASP.NET Core和Angular中进行令牌身份验证的过程中可能会遇到一些问题。以下是一些可能的解决方法,包括代码示例:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = 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_security_key"))
};
});
import { JwtModule } from '@auth0/angular-jwt';
export function tokenGetter() {
return localStorage.getItem('access_token');
}
@NgModule({
imports: [
// ...
JwtModule.forRoot({
config: {
tokenGetter: tokenGetter,
allowedDomains: ['your_api_domain'],
disallowedRoutes: ['your_api_domain/auth/login']
}
})
],
// ...
})
export class AppModule { }
[HttpPost("login")]
public async Task Login([FromBody] LoginDto model)
{
// 验证用户名和密码
var user = await _userManager.FindByNameAsync(model.Username);
if (user != null && await _userManager.CheckPasswordAsync(user, model.Password))
{
// 生成令牌
var token = GenerateToken(user);
return Ok(new { access_token = token });
}
return Unauthorized();
}
private string GenerateToken(ApplicationUser user)
{
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes("your_security_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);
return tokenHandler.WriteToken(token);
}
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class ApiService {
private apiUrl = 'your_api_url';
constructor(private http: HttpClient) { }
getProtectedData() {
const token = localStorage.getItem('access_token');
const headers = new HttpHeaders().set('Authorization', `Bearer ${token}`);
return this.http.get(`${this.apiUrl}/protected-data`, { headers });
}
}
请注意,这些解决方法仅供参考,并且可能需要根据您的具体情况进行调整。此外,确保在配置身份验证时使用正确的密钥、颁发者和受众者等参数。