I tried to implement OAuth2 authentication and authorization. I have an authorization server and a resource server. The client logs in to the authorization server (sends the username and password to the authorization server) and the authorization server returns an access_token. The client uses the access_token in order to ask for any resource with an [Authorize] tag from the resource_server.
The authentication part (sending credentials to the authorization server and getting back an access_token) works fine. I get a valid JWT token. The problem is that the resource server does not recognize the access_token. Everytime the client sends a request to get a resource that has an [Authorize] tag I get : '401 Unauthorized Authorization has been denied for this request'.
This is a list of things I tried/verified:
Authorization:JWT eyJ0eXAiO.......JuRpuf6yWg
My implementation is based on these two tutorials:
This is the Startup.cs class in my resource server:
using Microsoft.Owin.Cors;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.DataHandler.Encoder;
using Microsoft.Owin.Security.Jwt;
using Microsoft.Owin.Security.OAuth;
using Owin;
using System.Threading.Tasks;
using System.Web.Http;
using Web.Api.App_Start;
namespace Web.Api
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
ConfigureOAuth(app);
app.UseAutofacMiddleware((newAutofacContainer())
.ConfigureContainer(config));
app.UseCors(CorsOptions.AllowAll);
WebApiConfig.Register(config);
app.UseWebApi(config);
}
public void ConfigureOAuth(IAppBuilder app)
{
var issuer = "http://localhost:81/Auth.Server";
var audience = "AUDIENCE";
var secret = TextEncodings.Base64Url.Decode("SECRET");
app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
AllowedAudiences = new[] { audience },
IssuerSecurityTokenProviders = new
IIssuerSecurityTokenProvider[]
{
new SymmetricKeyIssuerSecurityTokenProvider(issuer,
secret)
},
Provider = new OAuthBearerAuthenticationProvider
{
OnValidateIdentity = context =>
{
context.Ticket.Identity.AddClaim(new
System.Security
.Claims.Claim("newCustomClaim", "newValue"));
return Task.FromResult<object>(null);
}
}
});
}
}
}
[SOLVED]: It should be Authorization:Bearer eyJ0eXAiO.......JuRpuf6yWg
(Bearer NOT JWT!)