c# - Sveltekit + NET 6 C# Api - 登录后,我无法调用具有授权的api

标签 c# asp.net-core-webapi svelte

登录后,我有jwt token 并且可以登录。但是,当我使用 jwt token 在 fetch 函数中调用其他 api 时,我的 api 调用未经授权。我无法调用 api。

NET 6 API

Program.cs

builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
    options.SaveToken = true;
    options.RequireHttpsMetadata = false;
    options.TokenValidationParameters = new TokenValidationParameters()
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidAudience = builder.Configuration["JWT:ValidAudience"],
        ValidIssuer = builder.Configuration["JWT:ValidIssuer"],
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["JWT:SecretKey"]))
    };
});

LoginController.cs

var tokenHandler = new JwtSecurityTokenHandler();
            var key = Encoding.UTF8.GetBytes(_configuration["JWT:SecretKey"]);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                        new Claim(SessionConstant.UserName, user.UserName!),
                        new Claim(ClaimTypes.Role, userRole)
                }),
                Issuer = _configuration["JWT:ValidIssuer"],
                Audience = _configuration["JWT:ValidAudience"],
                Expires = DateTime.Now.AddMinutes(20),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);

UserController.cs

[Authorize(Roles = RoleConstant.Developer)]
[HttpGet("GetUsers")]
public async Task<JsonResult> GetUsers(User user)

Sveltekit

index.svelte

// get = fetch with 'get' method.
let result = await get(`api/User/GetUsers?id=${id}`, accesstoken);

utils.ts

export async function get(endpoint, token) {
    let headers = {};
    
    if (token)
    {
        headers = {
            'Authorization': `JWT ${token}`
        };
    }

    return await fetch(`${baseApiUrl}/${endpoint}`, {
        method: 'GET',
        headers
    }).then(r => r.json())
        .then(x => x);
}

我有 jwt token 。在 jwt token 内,它显示我的角色是开发人员,与 NET Api 的 [Authorize(Roles = RoleConstant.Developer)] 匹配。但我仍然无法调用 GetUsers 并且它返回“未授权”。我也在“Authorization” header 中尝试了“Bearer ${token}”,但它不起作用。

代码中我错过了什么吗?

最佳答案

你应该使用这个;

headers = new Headers({ 'Authorization': 'Bearer' + token, 'Content-Type': 'application/json' });

关于c# - Sveltekit + NET 6 C# Api - 登录后,我无法调用具有授权的api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71814690/

相关文章:

c# - 将 HttpModule .Net 类库移植到 .Net Core Web API

c# - 如何在我的 asp net core 3.1 Controller 中的特定操作上设置基本身份验证?

svelte - 延迟加载组件

c# - 如何将打印对话框添加到打印预览对话框?

c# - 如何在C#.NET中修改其他Form的RichTextBox

c# - 如何转义 Razor 页面中属性内的引号

c# - 通过 POST、PUT 方法返回 400 Bad Request,但 GET 工作正常

javascript - slim 长按

svelte - 从距 IP 最近到最远的距离对数组进行排序

c# - ServiceBusTrigger 中的连接是什么?