带有jwt身份验证的RestSharp不起作用

本文关键字:RestSharp 不起作用 身份验证 jwt 带有 | 更新日期: 2023-09-27 18:01:57

这是我"学会"如何做的页面:https://stormpath.com/blog/token-authentication-asp-net-core

但对我来说,这是不工作(不与小提琴手工作,太)这是我的ApplicationUser-model的控制器:

[Authorize] //works when it's not set, doesn't work when it's set
[Route("api/[controller]")]
public class ApplicationUserController : Controller
{
    private IRepository<ApplicationUser> _applicationUserRepository;
    public ApplicationUserController(IRepository<ApplicationUser> applicationUserRepository)
    {
        _applicationUserRepository = applicationUserRepository;
    }
    [HttpGet("{id}")]
    public ApplicationUser Get(int id)
    {
        return _applicationUserRepository.Get(id);
    }
}

,这是我的包装器RestSharp获取所有的applicationusers:

public Task<T> GetResponseContentAsync<T>(string resource, int id) where T : new()
{
    RestRequest request = new RestRequest($"{resource}/{{id}}", Method.GET);
    request.AddUrlSegment("id", id);
    if (!AuthenticationToken.IsNullOrEmpty(true))
    {
        request.AddHeader("Authorization", string.Format("Bearer {0}", AuthenticationToken));
        _client.Authenticator = new JwtAuthenticator(AuthenticationToken);
        _client.Authenticator.Authenticate(_client, request);
    }
    TaskCompletionSource<T> tcs = new TaskCompletionSource<T>();
    _client.ExecuteAsync<T>(request, response =>
    {
        tcs.SetResult(response.Data);
    });
    return tcs.Task;
}

从我的web客户端应用程序,我想用JWT(令牌认证)什么工作登录。登录后,我得到例如这个access_token:eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJURVNUIiwianRpIjoiZTBjYjE0NjgtYzBmOS00ZTM4LTg4ZjgtMGM4ZjNmYjMyNjZmIiwiaWF0IjoxNDcwOTUwMTA0LCJuYmYiOjE0NzA5NTAxMDQsImV4cCI6MTQ3MDk1MDQwNCwiaXNzIjoiRXhhbXBsZUlzc3VlciIsImF1ZCI6IkV4YW1wbGVBdWRpZW5jZSJ9.a9_JK2SG3vzc6NSOB0mZXqHlM9UAEXUHHrrijAQUsX0

没有Authorize -属性我得到ApplicationUser,但在设置属性时,结果为空(因为web-api没有被调用)

包装器调用看起来像这样:

//this works, token-value is set
string token = new RepositoryCall("http://localhost:54008/").Login("token", "TEST", "TEST123");
string accessToken = JsonConvert.DeserializeObject<Dictionary<string, string>>(token)["access_token"];
ViewData["Result"] = accessToken;
ApplicationUser userAfterLogin = await new RepositoryCall("http://localhost:54008/api") 
    { AuthenticationToken = accessToken }
    .GetResponseContentAsync<ApplicationUser>("ApplicationUser", 2);

,这里userAfterLogin为空。

两个星期以来我一直在尝试登录,但我仍然没有得到它的权利。

知道我做错了什么吗?可能是授权的请求头值错误?

这是我的启动。配置我配置使用承载/JWT的位置:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
        app.UseBrowserLink();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }
    app.UseStaticFiles();
    app.UseIdentity();
    var secretKey = "mysupersecret_secretkey!123";
    var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));
    // Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715
    var options = new TokenProviderOptions
    {
        Audience = "ExampleAudience",
        Issuer = "ExampleIssuer",
        SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256),
    };

    var tokenValidationParameters = new TokenValidationParameters
    {
        // The signing key must match!
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = signingKey,
        // Validate the JWT Issuer (iss) claim
        ValidateIssuer = true,
        ValidIssuer = "ExampleIssuer",
        // Validate the JWT Audience (aud) claim
        ValidateAudience = true,
        ValidAudience = "ExampleAudience",
        // Validate the token expiry
        ValidateLifetime = true,
        // If you want to allow a certain amount of clock drift, set that here:
        ClockSkew = TimeSpan.Zero
    };

    app.UseJwtBearerAuthentication(new JwtBearerOptions
    {
        AutomaticAuthenticate = true,
        AutomaticChallenge = true,
        TokenValidationParameters = tokenValidationParameters
    });
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AutomaticAuthenticate = true,
        AutomaticChallenge = true,
        AuthenticationScheme = "Cookie",
        CookieName = "access_token",
        TicketDataFormat = new CustomJwtDataFormat(
            SecurityAlgorithms.HmacSha256,
            tokenValidationParameters)
    });
    app.UseMiddleware<TokenProviderMiddleware>(Options.Create(options));
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

带有jwt身份验证的RestSharp不起作用

如果您收到授权错误或使用postman,您意识到您被要求重定向到登录,只需用:

装饰您的类:
[Authorize(AuthenticationSchemes = "Bearer")]

默认情况下,.Net使用基于cookie的认证,通过该注释,您可以切换到基于token的认证

在提琴你会看到,如果你被重定向到登录页面(它会报告2个结果,一个与302(重定向),然后是404 -是这种情况吗?

你已经激活了DebugLogger,所以尝试AddDebug(LogLevel.Trace)并查看Debug输出窗口,它对分析哪个认证步骤失败非常有帮助。它还显示身份验证或授权是否失败,以及是否有有效的令牌等。因此,它指出了寻找问题的方向。

所以你是使用2中间件的身份。一个由asp.net identity(基于cookie)提供,另一个基于令牌。现在两个中间件都使用相同的属性处理请求[authorization]。更准确地说,看看这里的代码

https://github.com/aspnet/Security/blob/dev/src/Microsoft.AspNetCore.Authentication.JwtBearer/JwtBearerHandler.cs

为JWTBearer

https://github.com/aspnet/Security/blob/dev/src/Microsoft.AspNetCore.Authentication.Cookies/CookieAuthenticationHandler.cs

饼干

因为两者都在中间件管道中激活,所以当您发送认证令牌或cookie时,主体将拥有数据。

但是因为它们都是活动的,它们中的任何一个都将为没有cookie或JwtBearer的请求返回Unauthorized。

对于您正在寻找的解决方案,您需要在现有的cookie和令牌之上创建一个中间件,以便根据是否存在授权头将请求路由到其中之一。