unauthorize access with authorization header signalr - c#

I'm using signalR and I'm trying to get the [Authorize] attribute to work. With below setup I get 401 Unauthorized..
Right before I start the Hub I set the Authorization like this:
$.signalR.ajaxDefaults.headers = { Authorization: 'Bearer ' + settingsService.getItem('authData').token }
I can see that the header is sent in the request like below:
Authorization: Bearer F0wGNa7cAwUjOFI27TDR_w7N4Ncmz66PGpsU1AH2AWt0Gdt39e2o4DGwPsBXTAlIwHrAF-YHE9I1KGLxfabE0QxpcY5mLn1gxGWStOSX_W5NaUQlRlpRu5k-s6YLH-vVjlakqap_YXbzPelZJOjwcz7Ea5VHcCUFQ5xDYYK0VJXDIqMwQXZPIyVtNVu1RyLLVj7iOZaMd-41gHKWNqFWJBmK5WkWw06dI4AWiifWJT_8v1WrFPCAzYfiT0U
My Hub:
[Authorize]
[HubName("myHub")]
public class DataHub : Hub {
private static bool _isInitated;
public DataHub() {
//Do stuff
}
}
}
The token is created like this:
var identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);
identity.AddClaim(new Claim("Username", "myname"));
var properties = new AuthenticationProperties() {
IssuedUtc = DateTime.UtcNow,
ExpiresUtc = DateTime.UtcNow.Add(Startup.OAuthOptions.AccessTokenExpireTimeSpan)
};
var ticket = new AuthenticationTicket(identity, properties);
var accessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);
var response = new JObject(new JProperty("access_token", accessToken), new JProperty("expires_in", Startup.OAuthOptions.AccessTokenExpireTimeSpan.TotalMinutes));
return Ok(new { token = response });
Am I missing something special here? Don't really get it.

If this is an issue for someone else I got the answer here. In my startup.cs I had to move app.MapSignalR(); last in the Configuration method. Like below:
public class Startup {
public void Configuration(IAppBuilder app) {
CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture;
GlobalHost.Configuration.DefaultMessageBufferSize = 100;
ConfigureOAuth(app);
app.MapSignalR();
}
public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }
public void ConfigureOAuth(IAppBuilder app) {
OAuthOptions = new OAuthAuthorizationServerOptions {
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(7)
};
app.UseOAuthAuthorizationServer(OAuthOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
}
Before I had ConfigureOAuth(app); last.. and then it didn't work

Related

Web API Core JWT Authentication is not working

I'm new to writing Web APIs in .NET. I wrote this API which is working fine normally but then I added JWT authentication and now when I provide correct username and password I get an authentication bearer token that I add to swagger UI but now when I try to access any other end point I get this 401 Unauthorized status. I'm unable to understand why. I've also tried this with Postman but same response.
Here is my Program.cs
using System.Text;
using Comply_Api_DotNet.Database;
using Comply_Api_DotNet.Repository;
using Comply_Api_DotNet.Services;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddScoped<IUsersDb, UsersDb>();
builder.Services.AddScoped<IAuthenticationService, AuthenticationService>();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = #"Please provide authorization token to access restricted features.",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
Scheme = "Bearer"
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement()
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
},
Scheme = "oauth2",
Name = "Bearer",
In = ParameterLocation.Header,
},
new List<string>()
}
});
});
// ADD JWT Authentication
builder.Services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(o =>
{
var key = Encoding.UTF8.GetBytes(builder.Configuration["JWT:Key"]);
o.SaveToken = true;
o.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = builder.Configuration["JWT:Issuer"],
ValidAudience = builder.Configuration["JWT:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(key)
};
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
Her is my Controller.
[Authorize]
[Route("api/[controller]")]
[ApiController]
public class UsersController : ControllerBase
{
private readonly IAuthenticationService _authenticationService;
private readonly IUsersDb _usersDb;
public UsersController(IAuthenticationService authenticationService, IUsersDb usersDb)
{
_authenticationService = authenticationService;
_usersDb = usersDb;
}
[AllowAnonymous]
[HttpPost]
[Route("authenticate")]
public IActionResult Authenticate(User user)
{
var token = _authenticationService.Authenticate(user);
if (token == null)
{
return Unauthorized();
}
return Ok(token);
}
// GET api/<UsersController>/5
[HttpGet]
public IEnumerable<User> Get(long id)
{
var usersFound = _usersDb.GetAllUsers(id);
return usersFound;
}
// POST api/<UsersController>
[HttpPost]
public User Post([FromBody] User user)
{
var userAdded = _usersDb.AddNewUser(user);
return userAdded;
}
// PUT api/<UsersController>/5
[HttpPut("{id:long}")]
public void Put(long id, [FromBody] User user)
{
throw new NotImplementedException();
}
[HttpDelete("{id:long}")]
public bool Delete(long id)
{
return _usersDb.DeleteUser(id);
}
} // end of class
appsettings.Json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"JWT": {
"Key": "fc746b61cde4f6665d3f9791446cd5395661860c0075a905ed9810b7391af467",
"Issuer": "Comply",
"Audience": "comply"
}
}
UPDATE: Authentication Service
public class AuthenticationService : IAuthenticationService
{
private readonly IConfiguration _configuration;
private readonly IUsersDb _usersDb;
public AuthenticationService(IConfiguration configuration, IUsersDb usersDb)
{
_configuration = configuration;
_usersDb = usersDb;
}
public AuthenticationToken? Authenticate(User user)
{
var foundUser = _usersDb.GetAllUsers(0)
.FirstOrDefault(x => x.Name == user.Name && x.Password == user.Password);
if (foundUser == null)
{
return null;
}
//If user found then generate JWT
return CreateAuthenticationToken(foundUser);
}
private AuthenticationToken CreateAuthenticationToken(User user)
{
var tokenHandler = new JwtSecurityTokenHandler();
var tokenKey = Encoding.UTF8.GetBytes(_configuration["JWT:Key"]);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new(ClaimTypes.Name, user.Name),
}),
Expires = DateTime.UtcNow.AddMinutes(10),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(tokenKey),
SecurityAlgorithms.HmacSha256Signature),
Issuer = _configuration["JWT:Issuer"],
Audience = _configuration["JWT:Audience"],
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return new AuthenticationToken()
{
Token = tokenHandler.WriteToken(token),
};
}
} //end of class
The issue is here Type = SecuritySchemeType.ApiKey, you are specifying security scheme type as apiKey. you need to replace that with Type = SecuritySchemeType.Http,. So, your OpenApiSecurityScheme should now look like this.
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = #"Please provide authorization token to access restricted features.",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.Http,
Scheme = "Bearer",
BearerFormat = "JWT",
});
In swagger Ui, You should add Bearer before Token. Reference:Bearer Authentication
Authorization: Bearer <token>
As you can see in Postman Headers, It has a Bearer.

JWT on .NET Core 2.0

I've been on quite an adventure to get JWT working on DotNet core 2.0 (now reaching final release today). There is a ton of documentation, but all the sample code seems to be using deprecated APIs and coming in fresh to Core, It's positively dizzying to figure out how exactly it's supposed to be implemented. I tried using Jose, but app. UseJwtBearerAuthentication has been deprecated, and there is no documentation on what to do next.
Does anyone have an open source project that uses dotnet core 2.0 that can simply parse a JWT from the authorization header and allow me to authorize requests for a HS256 encoded JWT token?
The class below doesn't throw any exceptions, but no requests are authorized, and I get no indication why they are unauthorized. The responses are empty 401's, so to me that indicates there was no exception, but that the secret isn't matching.
One odd thing is that my tokens are encrypted with the HS256 algorithm, but I see no indicator to tell it to force it to use that algorithm anywhere.
Here is the class I have so far:
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Net.Http.Headers;
using Newtonsoft.Json.Linq;
using Microsoft.IdentityModel.Tokens;
using System.Text;
namespace Site.Authorization
{
public static class SiteAuthorizationExtensions
{
public static IServiceCollection AddSiteAuthorization(this IServiceCollection services)
{
var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("SECRET_KEY"));
var tokenValidationParameters = new TokenValidationParameters
{
// The signing key must match!
ValidateIssuerSigningKey = true,
ValidateAudience = false,
ValidateIssuer = false,
IssuerSigningKeys = new List<SecurityKey>{ signingKey },
// Validate the token expiry
ValidateLifetime = true,
};
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(o =>
{
o.IncludeErrorDetails = true;
o.TokenValidationParameters = tokenValidationParameters;
o.Events = new JwtBearerEvents()
{
OnAuthenticationFailed = c =>
{
c.NoResult();
c.Response.StatusCode = 401;
c.Response.ContentType = "text/plain";
return c.Response.WriteAsync(c.Exception.ToString());
}
};
});
return services;
}
}
}
Here is a full working minimal sample with a controller. I hope you can check it using Postman or JavaScript call.
appsettings.json, appsettings.Development.json. Add a section. Note, Key should be rather long and Issuer is an address of the service:
...
,"Tokens": {
"Key": "Rather_very_long_key",
"Issuer": "http://localhost:56268/"
}
...
!!! In real project, don't keep Key in appsettings.json file. It should be kept in Environment variable and take it like this:
Environment.GetEnvironmentVariable("JWT_KEY");
UPDATE: Seeing how .net core settings work, you don't need to take it exactly from Environment. You may use setting. However,instead we may write this variable to environment variables in production, then our code will prefer environment variables instead of configuration.
AuthRequest.cs : Dto keeping values for passing login and password:
public class AuthRequest
{
public string UserName { get; set; }
public string Password { get; set; }
}
Startup.cs in Configure() method BEFORE app.UseMvc() :
app.UseAuthentication();
Startup.cs in ConfigureServices() :
services.AddAuthentication()
.AddJwtBearer(cfg =>
{
cfg.RequireHttpsMetadata = false;
cfg.SaveToken = true;
cfg.TokenValidationParameters = new TokenValidationParameters()
{
ValidIssuer = Configuration["Tokens:Issuer"],
ValidAudience = Configuration["Tokens:Issuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"]))
};
});
Add a controller:
[Route("api/[controller]")]
public class TokenController : Controller
{
private readonly IConfiguration _config;
private readonly IUserManager _userManager;
public TokenController(IConfiguration configuration, IUserManager userManager)
{
_config = configuration;
_userManager = userManager;
}
[HttpPost("")]
[AllowAnonymous]
public IActionResult Login([FromBody] AuthRequest authUserRequest)
{
var user = _userManager.FindByEmail(model.UserName);
if (user != null)
{
var checkPwd = _signInManager.CheckPasswordSignIn(user, model.authUserRequest);
if (checkPwd)
{
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
new Claim(JwtRegisteredClaimNames.Jti, user.Id.ToString()),
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(_config["Tokens:Issuer"],
_config["Tokens:Issuer"],
claims,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: creds);
return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) });
}
}
return BadRequest("Could not create token");
}}
That's all folks! Cheers!
UPDATE: People ask how get Current User. Todo:
In Startup.cs in ConfigureServices() add
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
In a controller add to constructor:
private readonly int _currentUser;
public MyController(IHttpContextAccessor httpContextAccessor)
{
_currentUser = httpContextAccessor.CurrentUser();
}
Add somewhere an extension and use it in your Controller (using ....)
public static class IHttpContextAccessorExtension
{
public static int CurrentUser(this IHttpContextAccessor httpContextAccessor)
{
var stringId = httpContextAccessor?.HttpContext?.User?.FindFirst(JwtRegisteredClaimNames.Jti)?.Value;
int.TryParse(stringId ?? "0", out int userId);
return userId;
}
}
My tokenValidationParameters works when they look like this:
var tokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = GetSignInKey(),
ValidateIssuer = true,
ValidIssuer = GetIssuer(),
ValidateAudience = true,
ValidAudience = GetAudience(),
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
and
static private SymmetricSecurityKey GetSignInKey()
{
const string secretKey = "very_long_very_secret_secret";
var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));
return signingKey;
}
static private string GetIssuer()
{
return "issuer";
}
static private string GetAudience()
{
return "audience";
}
Moreover, add options.RequireHttpsMetadata = false like this:
.AddJwtBearer(options =>
{
options.TokenValidationParameters =tokenValidationParameters
options.RequireHttpsMetadata = false;
});
EDIT:
Dont forget to call
app.UseAuthentication();
in Startup.cs -> Configure method before app.UseMvc();
Asp.net Core 2.0 JWT Bearer Token Authentication Implementation with Web Api Demo
Add Package "Microsoft.AspNetCore.Authentication.JwtBearer"
Startup.cs ConfigureServices()
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(cfg =>
{
cfg.RequireHttpsMetadata = false;
cfg.SaveToken = true;
cfg.TokenValidationParameters = new TokenValidationParameters()
{
ValidIssuer = "me",
ValidAudience = "you",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("rlyaKithdrYVl6Z80ODU350md")) //Secret
};
});
Startup.cs Configure()
// ===== Use Authentication ======
app.UseAuthentication();
User.cs // It is a model class just for example. It can be anything.
public class User
{
public Int32 Id { get; set; }
public string Username { get; set; }
public string Country { get; set; }
public string Password { get; set; }
}
UserContext.cs // It is just context class. It can be anything.
public class UserContext : DbContext
{
public UserContext(DbContextOptions<UserContext> options) : base(options)
{
this.Database.EnsureCreated();
}
public DbSet<User> Users { get; set; }
}
AccountController.cs
[Route("[controller]")]
public class AccountController : Controller
{
private readonly UserContext _context;
public AccountController(UserContext context)
{
_context = context;
}
[AllowAnonymous]
[Route("api/token")]
[HttpPost]
public async Task<IActionResult> Token([FromBody]User user)
{
if (!ModelState.IsValid) return BadRequest("Token failed to generate");
var userIdentified = _context.Users.FirstOrDefault(u => u.Username == user.Username);
if (userIdentified == null)
{
return Unauthorized();
}
user = userIdentified;
//Add Claims
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.UniqueName, "data"),
new Claim(JwtRegisteredClaimNames.Sub, "data"),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("rlyaKithdrYVl6Z80ODU350md")); //Secret
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken("me",
"you",
claims,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: creds);
return Ok(new
{
access_token = new JwtSecurityTokenHandler().WriteToken(token),
expires_in = DateTime.Now.AddMinutes(30),
token_type = "bearer"
});
}
}
UserController.cs
[Authorize]
[Route("api/[controller]")]
public class UserController : ControllerBase
{
private readonly UserContext _context;
public UserController(UserContext context)
{
_context = context;
if(_context.Users.Count() == 0 )
{
_context.Users.Add(new User { Id = 0, Username = "Abdul Hameed Abdul Sattar", Country = "Indian", Password = "123456" });
_context.SaveChanges();
}
}
[HttpGet("[action]")]
public IEnumerable<User> GetList()
{
return _context.Users.ToList();
}
[HttpGet("[action]/{id}", Name = "GetUser")]
public IActionResult GetById(long id)
{
var user = _context.Users.FirstOrDefault(u => u.Id == id);
if(user == null)
{
return NotFound();
}
return new ObjectResult(user);
}
[HttpPost("[action]")]
public IActionResult Create([FromBody] User user)
{
if(user == null)
{
return BadRequest();
}
_context.Users.Add(user);
_context.SaveChanges();
return CreatedAtRoute("GetUser", new { id = user.Id }, user);
}
[HttpPut("[action]/{id}")]
public IActionResult Update(long id, [FromBody] User user)
{
if (user == null)
{
return BadRequest();
}
var userIdentified = _context.Users.FirstOrDefault(u => u.Id == id);
if (userIdentified == null)
{
return NotFound();
}
userIdentified.Country = user.Country;
userIdentified.Username = user.Username;
_context.Users.Update(userIdentified);
_context.SaveChanges();
return new NoContentResult();
}
[HttpDelete("[action]/{id}")]
public IActionResult Delete(long id)
{
var user = _context.Users.FirstOrDefault(u => u.Id == id);
if (user == null)
{
return NotFound();
}
_context.Users.Remove(user);
_context.SaveChanges();
return new NoContentResult();
}
}
Test on PostMan:
Pass TokenType and AccessToken in Header in other webservices.
Best of Luck! I am just Beginner. I only spent one week to start learning asp.net core.
Here is a solution for you.
In your startup.cs, firstly, config it as services:
services.AddAuthentication().AddJwtBearer(cfg =>
{
cfg.RequireHttpsMetadata = false;
cfg.SaveToken = true;
cfg.TokenValidationParameters = new TokenValidationParameters()
{
IssuerSigningKey = "somethong",
ValidAudience = "something",
:
};
});
second, call this services in config
app.UseAuthentication();
now you can use it in your controller by add attribute
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[HttpGet]
public IActionResult GetUserInfo()
{
For full details source code that use angular as Frond-end see here
Here is my implementation for a .Net Core 2.0 API:
public IConfigurationRoot Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
// Add framework services
services.AddMvc(
config =>
{
// This enables the AuthorizeFilter on all endpoints
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
}
).AddJsonOptions(opt =>
{
opt.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
});
services.AddLogging();
services.AddAuthentication(sharedOptions =>
{
sharedOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
sharedOptions.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.Audience = Configuration["AzureAD:Audience"];
options.Authority = Configuration["AzureAD:AADInstance"] + Configuration["AzureAD:TenantId"];
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseAuthentication(); // THIS METHOD MUST COME BEFORE UseMvc...() !!
app.UseMvcWithDefaultRoute();
}
appsettings.json:
{
"AzureAD": {
"AADInstance": "https://login.microsoftonline.com/",
"Audience": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"ClientId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"Domain": "mydomain.com",
"TenantId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
},
...
}
The above code enables auth on all controllers. To allow anonymous access you can decorate an entire controller:
[Route("api/[controller]")]
[AllowAnonymous]
public class AnonymousController : Controller
{
...
}
or just decorate a method to allow a single endpoint:
[AllowAnonymous]
[HttpPost("anonymousmethod")]
public async Task<IActionResult> MyAnonymousMethod()
{
...
}
Notes:
This is my first attempt at AD auth - if anything is wrong, please let me know!
Audience must match the Resource ID requested by the client. In our case our client (an Angular web app) was registered separately in Azure AD, and it used its Client Id, which we registered as the Audience in the API
ClientId is called Application ID in the Azure Portal (why??), the Application ID of the app registration for the API.
TenantId is called Directory ID in the Azure Portal (why??), found under Azure Active Directory > Properties
If deploying the API as an Azure hosted Web App, ensure you set the Application Settings:
eg. AzureAD:Audience / xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
Just to update on the excellent answer by #alerya I had to modify the helper class to look like this;
public static class IHttpContextAccessorExtension
{
public static string CurrentUser(this IHttpContextAccessor httpContextAccessor)
{
var userId = httpContextAccessor?.HttpContext?.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value;
return userId;
}
}
Then I could obtain the userId in my service layer. I know it's easy in the controller, but a challenge further down.

c# web api owin authentication

I am very new to WebAPi Authentication even it seems OWIN being popular use. I dont understand why I should use EntityFramework for OWIN authentication as ApplicationDbContext is inhreting from IdentityDbContext and IdentityDbContext is in EntityFramework namespace. Below is procedure which is created automatically when we choose Individual User Accounts within WebApi project template:
public partial class Startup
{
public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }
public static string PublicClientId { get; private set; }
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context and user manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Configure the application for OAuth based flow
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
// In production mode set AllowInsecureHttp = false
AllowInsecureHttp = true
};
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(OAuthOptions);
// Uncomment the following lines to enable logging in with third party login providers
//app.UseMicrosoftAccountAuthentication(
// clientId: "",
// clientSecret: "");
//app.UseTwitterAuthentication(
// consumerKey: "",
// consumerSecret: "");
//app.UseFacebookAuthentication(
// appId: "",
// appSecret: "");
//app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
//{
// ClientId = "",
// ClientSecret = ""
//});
}
}
Within ConfigureAuth procedure ApplicationDbContext is referenced.
Could you pls help me to write simple Authentication with OWIN and not to use EntityFramework?
Thanks.
you donĀ“t need to use EF, yes, the template uses EF and ASPNET Identity to do the authentication, but you can start using the black template and add it without EF, look the following part of code:
Startup.cs
public class Startup
{
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
ConfigureOAuth(app);
WebApiConfig.Register(config);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWebApi(config);
}
public void ConfigureOAuth(IAppBuilder app)
{
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = new SimpleAuthorizationServerProvider()
};
// Token Generation
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
}
SimpleAuthorizationServerProvider.cs
public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
if (context.UserName != "Admin")
{
context.SetError("upps!", "Wrong data");
return;
}
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim("sub", context.UserName));
identity.AddClaim(new Claim("role", "user"));
context.Validated(identity);
}
}
Also, you can download a simple example here: http://1drv.ms/1mmaqtn
Regards,

Always getting the "Authorization has been denied for this request." message

I'm able to successfully retrieve token, but when trying to authenticate using the token I always get the Authorization has been denied for this request message.
My Startup.cs file contains the following methods
public void Configuration(IAppBuilder app)
{
var config = new HttpConfiguration();
WebApiConfig.Register(config);
app.UseWebApi(config);
ConfigureOAuth(app);
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter().First();
jsonFormatter.SerializerSettings
.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
private void ConfigureOAuth(IAppBuilder app)
{
var oAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/Token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = new DefaultAuthorizationServerProvider()
};
app.UseOAuthAuthorizationServer(oAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
The DefaultAuthorizationServerProvider.cs class contains the following
public class DefaultAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
public override async Task ValidateClientAuthentication
(
OAuthValidateClientAuthenticationContext context
)
{
context.Validated();
}
public override async Task GrantResourceOwnerCredentials
(
OAuthGrantResourceOwnerCredentialsContext context
)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
var identityManager = new IdentityManager();
var identity = identityManager.Get(context.UserName, context.Password,
new IpAddressProvider().Provide(IpAddressType.Forwarding));
if (identity == null)
{
context.SetError("invalid_grant", "Authentication failed. Please make sure you provided the correct username and password.");
}
else
{
identity.AddClaim(new Claim(ClaimTypes.Role, "User"));
context.Validated(identity);
}
}
}
And the IdentityManager.cs class have the following
public class IdentityManager : IIdentityManager
{
public virtual ClaimsIdentity Get
(
string username,
string password,
string ipAddress
)
{
var authenticateUserWorkflowOutput = new AuthenticateUserWorkflowHelper().Execute
(
new AuthenticateUserWorkflowInput
{
Username = username,
Password = password,
IpAddress = ipAddress
},
new AuthenticateUserWorkflowState()
);
if (authenticateUserWorkflowOutput.Message.Exception != null)
{
return null;
}
if (!authenticateUserWorkflowOutput.Authenticated)
{
return null;
}
return authenticateUserWorkflowOutput.User != null ? new Infrastructure.Identity(new[]
{
new Claim(ClaimTypes.Name, authenticateUserWorkflowOutput.MasterUser.EmailAddress),
}, "ApplicationCookie") : null;
}
}
Using Fiddler I can successfully retrieve a token
But when I try to authenticate using the token I get the following response
Ok, I found the problem in my Startup class. I was missing the following
[assembly: OwinStartup(typeof(Yugasat.System.ServiceLayer.Startup))]
namespace Yugasat.System.ServiceLayer
and the ConfigureOAuth(app);call needed to be moved to the top of the Configuration method. Below is my new Startup.cs class.
[assembly: OwinStartup(typeof(Yugasat.System.ServiceLayer.Startup))]
namespace Yugasat.System.ServiceLayer
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureOAuth(app);
var config = new HttpConfiguration();
WebApiConfig.Register(config);
app.UseWebApi(config);
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
private void ConfigureOAuth(IAppBuilder app)
{
var oAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/Token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = new DefaultAuthorizationServerProvider()
};
app.UseOAuthAuthorizationServer(oAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
}
}

Owin Bearer Token Not Working for WebApi

I have gone through loads of documentation on this, My google search shows that I've visited all the links on the first page
Problem
Token Generation works fine. I configured it with a custom provider as such:
public void ConfigureOAuth(IAppBuilder app)
{
var usermanager = NinjectContainer.Resolve<UserManager>();
app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = new AppOAuthProvider(usermanager)
});
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
However when I call a protected URL and pass the bearer token, I always get:
How do I diagnose or fix the problem. If possible, how can I do the token validation myself
UPDATE
Here is my AppOAuthProvider. Both Methods are called when I'm trying to mint a token but not when I'm trying to access a protected resource
public class AppOAuthProvider : OAuthAuthorizationServerProvider
{
private UserManager _user;
public AppOAuthProvider(UserManager user)
{
_user = user;
}
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
}
public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
//Get User Information
var getUser = _user.FindUser(context.UserName);
if (getUser.Status == StatusCode.Failed)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return Task.FromResult<object>(null);
}
var user = getUser.Result;
//Get Roles for User
var getRoles = _user.GetRoles(user.UserID);
if (getRoles.Status == StatusCode.Failed)
{
context.SetError("invalid_grant", "Could not determine Roles for the Specified User");
}
var roles = getRoles.Result;
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim("UserID", user.UserID.ToString()));
identity.AddClaim(new Claim("UserName", user.UserName));
foreach (var role in roles)
{
identity.AddClaim(new Claim(ClaimTypes.Role, role));
}
context.Validated(identity);
return Task.FromResult<object>(null);
}
}
UPDATE 2:
Here is my Account Controller
[RoutePrefix("api/auth/account")]
public class AccountController : ApiController
{
private UserManager _user;
public AccountController(UserManager user)
{
_user = user;
}
[Authorize]
[HttpGet]
[Route("secret")]
public IHttpActionResult Secret()
{
return Ok("Yay! Achievement Unlocked");
}
}
UPDATE 3:
Here is my Startup.cs
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseNinjectMiddleware(NinjectContainer.CreateKernel);
app.UseNinjectWebApi(GlobalConfiguration.Configuration);
GlobalConfiguration.Configure(WebApiConfig.Register);
ConfigureOAuth(app);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWebApi(GlobalConfiguration.Configuration);
app.UseWelcomePage();
}
}
You must configure the OAuth authorization server and OAuth bearer authentication before call UseWebApi on IAppBuilder. The following is from my program.
public void Configuration(IAppBuilder app)
{
app.UseFileServer(new FileServerOptions()
{
RequestPath = PathString.Empty,
FileSystem = new PhysicalFileSystem(#".\files")
});
// set the default page
app.UseWelcomePage(#"/index.html");
ConfigureAuth(app);
HttpConfiguration config = new HttpConfiguration();
config.Routes.MapHttpRoute
(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Formatters.Clear();
config.Formatters.Add(new JsonMediaTypeFormatter());
config.Formatters.JsonFormatter.SerializerSettings =
new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
app.UseCors(CorsOptions.AllowAll);
app.UseWebApi(config);
}
public void ConfigureAuth(IAppBuilder app)
{
OAuthAuthorizationServerOptions oAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = new YourApplicationOAuthProvider()
};
app.UseOAuthAuthorizationServer(oAuthServerOptions);
app.UseOAuthBearerAuthentication
(
new OAuthBearerAuthenticationOptions
{
Provider = new OAuthBearerAuthenticationProvider()
}
);
}
HttpConfiguration config = new HttpConfiguration();
app.UseNinjectMiddleware(NinjectContainer.CreateKernel);
app.UseNinjectWebApi(GlobalConfiguration.Configuration);
ConfigureOAuth(app);
WebApiConfig.Register(config);
//GlobalConfiguration.Configure(WebApiConfig.Register);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
// app.UseWebApi(GlobalConfiguration.Configuration);
app.UseWebApi(config);
app.UseWelcomePage();
I tried this with ur sample application on github and it worked
In your provider you have to:
public override ValidateClientAuthentication(OAuthClientAuthenticationContext context)
{
//test context.ClientId
//if you don't care about client id just validate the context
context.Validated();
}
The reason for this is that if you don't override ValidateClientAuthentication and validate the context, it is assumed as rejected and you'll always get that error.

Categories

Resources