这是我“学会”如何做的那一页:https://stormpath.com/blog/token-authentication-asp-net-core
但对我来说,这是不起作用的(也不适用于Fiddler ),我的ApplicationUser模型有一个控制器:
[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包装器,用于获取所有应用程序用户:
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-attribute,我将得到ApplicationUser,但是当设置属性时,结果为null (因为web没有被调用)。
包装器调用如下所示:
//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是空的。
两周以来我一直在尝试登录,但我还是没能正确登录.
知道我做错什么了吗?可能是一个错误的授权请求头值?
更新
这是我的Startup.Configure,我将其配置为使用Bearer / 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?}");
});
}发布于 2018-04-22 19:04:33
如果您收到授权程序错误或使用邮递员,您会意识到您被要求重定向登录,只需用以下内容装饰您的类:
[Authorize(AuthenticationSchemes = "Bearer")]默认情况下,.Net使用基于cookie的auth,使用基于标记的注释
发布于 2016-08-21 03:33:23
因此,您正在使用2个中间件作为身份验证。一个是由asp.net标识(基于cookie)提供的,另一个是基于令牌的。现在,这两个中间件都使用相同的属性来处理请求授权。更准确地说,看看这里的代码
对于JWTBearer
和
为琦琦
因为两者都是在中间件管道中激活的,所以当您发送auth令牌或cookie时,主体将拥有数据。
但是,由于它们都是活动的,它们中的任何一个都会返回未经授权的请求,而请求没有cookie或JwtBearer。
对于正在寻找的解决方案,需要在现有cookie和令牌的基础上创建一个中间件,以便根据授权头将请求路由到任何一个。
发布于 2016-09-30 07:53:48
在Fiddler中,您会看到,如果您被重定向到登录页面(它将报告2个结果,一个为302 (重定向),然后404 -是这样吗?)
您已经激活了DebugLogger,所以尝试AddDebug(LogLevel.Trace)并查看Debug输出窗口,这对于分析哪些身份验证步骤失败非常有帮助。它还显示身份验证是否失败或授权,以及是否具有有效令牌等。因此,它指向查找问题的方向。
https://stackoverflow.com/questions/38906404
复制相似问题