auth0授权到asp.net核心api

时间:2017-01-23 19:30:43

标签: asp.net-core jwt auth0

我开始执行angular2 + asp.net core申请,开始实施Auth0。我创建了客户端应用程序和用户。

以下是url提供的Api客户端应用程序设置:

enter image description here

用户登录正常:

enter image description here

现在我有了这个controller的api:

    [Route("api")]
public class PingController : Controller
{
    [Authorize]
    [HttpGet]
    [Route("ping/secure")]
    public string PingSecured()
    {
        return "All good. You only get this message if you are authenticated.";
    }
}

startup.cs中,我尝试像这样实施:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        var options = new JwtBearerOptions
        {
            Audience = "uUdThU122xYPugR8gLoNTr3HdJ6sWvQV",
            Authority = "https://dntquitpls.eu.auth0.com/",

        };

        if (env.IsDevelopment())
        {
            app.UseBrowserLink();
            app.UseDeveloperExceptionPage();
        };

        app.UseJwtBearerAuthentication(options);

        app.UseCors(builder =>
                    builder.WithOrigins("http://localhost:61290/").AllowAnyOrigin()
                           .AllowAnyHeader()
                           .AllowAnyMethod()
                    );

        app.UseDefaultFiles();

        app.UseStaticFiles();

        app.UseMvc(routes =>
        {
            routes.MapWebApiRoute("defaultApi",
                                  "api/{controller}/{id?}");
        });
    }

这不起作用:

enter image description here

Api部分由Auth0 Api教程完成,例如,如果我创建了Api并且有一个测试Bearer令牌,那么在api中,我也按Startup.cs配置Api文件,但遗憾的是我的Bearer令牌来自响应不起作用。

请知道为什么它不起作用而且我没有获得授权?

1 个答案:

答案 0 :(得分:4)

找到一个解决方案,现在它可以正常运行,问题出现在选项HS256编码的Any文件中,用于Startup.cs解决方案:

UseJwtBearerAuthentication

源:

http://www.jerriepelser.com/blog/using-roles-with-the-jwt-middleware/

如果你想使用RS256编码,请使用:

var keyAsBytes = Encoding.ASCII.GetBytes("CLIENT_SECRET");

    var options = new JwtBearerOptions
    {
        TokenValidationParameters =
        {
            ValidIssuer = "https://dntquitpls.eu.auth0.com/",
            ValidAudience = "uUdThU122xYPugR8gLoNTr3HdJ6sWvQV",
            IssuerSigningKey = new SymmetricSecurityKey(keyAsBytes)
        }
    };
    app.UseJwtBearerAuthentication(options);