Trying to implement policy authorization in a .NET6 Web Api.
I've added in authentication and authorization via the configuration:
builder.AddCredibleApplicationFramework(assemblies);
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme,
options =>
{
var tokenValidationSettings = builder.Configuration.GetSection("JwtSettings")
.Get<TokenValidationSettings>();
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = tokenValidationSettings.ValidateIssuer,
ValidateAudience = tokenValidationSettings.ValidateAudience,
ValidateIssuerSigningKey = true,
ValidIssuer = tokenValidationSettings.Issuer,
IssuerSigningKey =
new SymmetricSecurityKey(Encoding.ASCII.GetBytes(tokenValidationSettings.SigningKey))
};
});
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("isAdministrator",
policyBuilder =>
{
policyBuilder.AuthenticationSchemes.Add(JwtBearerDefaults.AuthenticationScheme);
policyBuilder.AddRequirements(new IsAdministratorRequirement());
});
});
builder.Services.AddSingleton<IAuthorizationHandler, IsApplicationAdministratorHandler>();
builder.Services.AddDbContext<CDbContext>(options =>
{
var connection = builder.Configuration.GetConnectionString("conn");
options
.UseMySql(connection, ServerVersion.AutoDetect(connection))
.EnableSensitiveDataLogging()
.EnableDetailedErrors()
.UseLoggerFactory(loggerFactory);
});
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseAuthentication();
app.UseAuthorization();
app.UseHttpsRedirection();
app.MapControllers();
app.Run();
The handler success path is executing (the requirement succeeds):
public class IsApplicationAdministratorHandler : AuthorizationHandler<IsAdministratorRequirement>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
IsAdministratorRequirement requirement)
{
if (context.User.HasClaim(c => c.Type.Equals("applicationAdmin")) ||
context.User.HasClaim(c => c.Type.Equals("platformAdmin")))
{
return Task.FromResult(() => context.Succeed(requirement)); <-- This line returns....
}
return Task.FromResult(() => context.Fail());
}
}
I am getting 403 even though the handler succeeds.
You are returning a lambda result rather than calling the actual context method, since your lambda is never executed. Its not necessary in your case, as you can directly call context.Succeed(requirement)
public class IsApplicationAdministratorHandler : AuthorizationHandler<IsAdministratorRequirement>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
IsAdministratorRequirement requirement)
{
if (context.User.HasClaim(c => c.Type.Equals("applicationAdmin")) ||
context.User.HasClaim(c => c.Type.Equals("platformAdmin")))
{
context.Succeed(requirement);
}
else
{
// this isn't strictly necessary, unless you want to fail hard and early
// and not give other policy handlers to be evaluated
context.Fail(requirement)
};
return Task.Completed;
}
}
Related
I implemented a simple app in .Net Core 3.1. I am using JWT token as Authentication and added Antiforgery like this in ConfigureServices()
services.AddAuthentication(options => {
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options => {
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Environment.GetEnvironmentVariable("JWT_SEED"))),
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
context.Token = context.Request.Cookies["JWT"];
return Task.CompletedTask;
}
};
});
services.AddAuthorization(options =>
options.AddPolicy("ValidAccessToken", policy =>
{
policy.AuthenticationSchemes.Add(JwtBearerDefaults.AuthenticationScheme);
policy.RequireAuthenticatedUser();
})
);
services.AddAntiforgery(options => {
options.HeaderName = "X-XSRF-TOKEN";
options.SuppressXFrameOptionsHeader = false;
});
Then, in Configure() I have:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IAntiforgery antiforgery)
{
app.UseMiddleware<ExceptionMiddleware>();
app.UseCors(options => options
.WithOrigins("https://abc.random.com")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.Use(next => context => {
string path = context.Request.Path.Value;
if (path != null && path.ToLower().Contains("/api")) {
var tokens = antiforgery.GetAndStoreTokens(context);
context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken,
new CookieOptions() {
HttpOnly = false,
Secure = true
});
}
return next(context);
});
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
I also have a method to refresh the antiforgery token
[HttpGet("refreshAntiforgery")]
public IActionResult RefreshAntiforgery() {
var antiforgeryTokens = _antiforgery.GetAndStoreTokens(HttpContext);
HttpContext.Response.Cookies.Append(
"XSRF-TOKEN",
antiforgeryTokens.RequestToken,
new CookieOptions
{
HttpOnly = false,
Secure = true
}
);
return NoContent();
}
In my Angular app I registered in app.module.ts
HttpClientXsrfModule.withOptions({
cookieName: 'XSRF-TOKEN',
headerName: 'X-XSRF-TOKEN'
}),
and in the services I want to use the antiforgery token (I also have the interceptor to add credentials for all requests and also have URLs starting with // to avoid relative URLs)
updatePassword(client: Client): Observable<any> {
let xsrfToken = this.xsrfTokenExtractor.getToken() as string;
let headers = new HttpHeaders()
.set('X-XSRF-TOKEN', xsrfToken);
return this.http.put<Client>(
environment.baseUrls.client +
environment.relativeUrls.updatePassword,
user,
{
headers: headers,
withCredentials: true
}
);
}
The problem is that XSRF-TOKEN coming from .net core app is being set as HttpOnly despite I set the cookie as HttpOnly = false
cookie from browser
Any idea why HttpOnly is being set in XSRF-TOKEN? (I have tried different solutions like cookie policies or check Configure() order, clear cookies from browser, but nothing changes the value)
I have a problem, I use nginx is my web server of web application
I have 1 connection from web application to my server by using signalR, but connection usually lost connection and cloudfare return 524 error status code
Can anyone have solution for this problem
Update : I have fix that, I config proxy_pass from localhost to 127.0.0.1 and this reslove my prolem
But I have another problem, when I view request from my website
this is my code
public void ConfigureServices(IServiceCollection services){
//adding swagger
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebApp1", Version = "v1" });
});
// Adding Authentication
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
// Adding Jwt Bearer
.AddJwtBearer(options =>
{
options.SaveToken = true;
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
//ValidAudience = Configuration["JWT:ValidAudience"],
//ValidIssuer = Configuration["JWT:ValidIssuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:Secret"])),
RequireExpirationTime = true,
};
});
//Add mysql connection
services.AddScoped<MySqlConnection>((provider) =>
{
var connection = Configuration.GetConnectionString("MySql");
return new MySqlConnection(connection);
});
services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
{
builder.WithOrigins("http://localhost:4200", "http://localhost:3000")
.AllowAnyHeader()
.AllowAnyMethod()
.SetIsOriginAllowed((x) => true)
.AllowCredentials();
}));
//add signalR
services.AddSignalR(option =>
{
})
.AddJsonProtocol(options =>
{
options.PayloadSerializerOptions.Converters
.Add(new JsonStringEnumConverter());
options.PayloadSerializerOptions.IgnoreNullValues = true;
}); ;
// In production, the React files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp";
});
services.AddControllers()
.AddJsonOptions(opts =>
{
var enumConverter = new JsonStringEnumConverter();
opts.JsonSerializerOptions.Converters.Add(enumConverter);
opts.JsonSerializerOptions.IgnoreNullValues = true;
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseSpaStaticFiles();
// Make sure the CORS middleware is ahead of SignalR.
app.UseRouting();
app.UseAuthentication();
app
.UseCors("MyPolicy");
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json",
"WebApp1 v1"));
app.UseAuthorization();
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
});
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<NotificationHub>("notify");
endpoints.MapHub<MsgHub>("msg");
endpoints.MapControllers();
});
}
I have saw 2 request of signalR client
https://****/notify?id=eTHEGY6Ae9_I2gSthLUcSQ (POST) status code 200
https://****/notify?id=eTHEGY6Ae9_I2gSthLUcSQ&_=1648545303996 (GET) status code 404
How to fix last request, I don't know why server return 404
After migrating from .net core 2.2 to .net core 3.1, and after taking some time to fix all the bugs depending on documentations, after running the app, the authorization method get's hit before it requires the user to be authenticated.
I am using OpenId Connect with AD FS for authentication and a custom method called "PermissionGranted" for authorization. And this method get's hit before it requires for the user to be authenticated.
This is the code of my Startup.cs file:
public class Startup
{
private readonly ConfigSettings settings;
private readonly GetSettings configSettings;
private readonly MyMemoryCache myMemoryCache;
public Startup(IWebHostEnvironment env, IConfiguration configuration)
{
configSettings = new GetSettings();
settings = configSettings.getSettings();
Configuration = configuration;
Environment = env;
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
myMemoryCache = new MyMemoryCache();
Log.Logger = new LoggerConfiguration().Enrich.FromLogContext()
.WriteTo.Console()
.WriteTo.File(settings.LogFile, rollingInterval: RollingInterval.Day)
.WriteTo.ApplicationInsights(new TelemetryConfiguration(settings.AppInsightsConnection), TelemetryConverter.Events)
.CreateLogger();
}
public IConfiguration Configuration { get; }
private IWebHostEnvironment Environment { get; }
public IServiceProvider ServiceProvider { get; set; }
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton(Log.Logger);
services.AddSingleton(settings);
services.AddHttpContextAccessor();
services.AddRouting(options => options.LowercaseUrls = true);
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => false;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies", options =>
{
options.AccessDeniedPath = "/users/denied";
})
.AddOpenIdConnect("oidc", options =>
{
options.SignInScheme = "Cookies";
options.MetadataAddress = settings.MetadataAddress;
options.ClientId = settings.ClientId;
options.GetClaimsFromUserInfoEndpoint = true;
options.ResponseType = OpenIdConnectResponseType.IdToken;
options.SignedOutRedirectUri = settings.PostLogoutUri;
options.SaveTokens = true;
options.UseTokenLifetime = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = true,
ValidAudience = settings.ClientId,
ValidateIssuer = true,
ValidIssuer = settings.Issuer,
ValidateLifetime = true,
RequireExpirationTime = true
};
options.Events = new OpenIdConnectEvents
{
OnRemoteFailure = context =>
{
context.HandleResponse();
context.Response.Redirect("/Login");
return Task.FromResult(0);
},
OnTicketReceived = context =>
{
// Configuration to make the Authentication cookie persistent for 8 hours (after 8 hours it expires and the user has to re-authenticate)
context.Properties.IsPersistent = true;
context.Properties.ExpiresUtc = DateTimeOffset.UtcNow.AddHours(8);
return Task.FromResult(0);
}
};
options.Events.OnRedirectToIdentityProvider = context =>
{
context.ProtocolMessage.Prompt = "login";
return Task.CompletedTask;
};
});
Audit.Core.Configuration.Setup()
.UseSqlServer(config => config
.ConnectionString(settings.ConnectionString)
.TableName("AuditEvents")
.IdColumnName("EventId")
.JsonColumnName("AuditData")
.LastUpdatedColumnName("LastUpdatedDate"));
services.AddAntiforgery(options => options.HeaderName = "X-CSRF-TOKEN");
services.AddApplicationInsightsTelemetry(settings.AppInsightsConnection);
services.AddMvc(options =>
{
var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
options.Filters.Add(new AuthorizeFilter(policy));
})
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
// Use NewtonsoftJson and custom date format
services.AddControllers().AddNewtonsoftJson(options =>
{
options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
});
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(15);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true; // Make the session cookie essential
});
services.AddAuthorization(options =>
{
options.AddPolicy("Permissions", policy => policy.RequireAssertion(context => PermissionGranted(context)));
});
services.AddDbContext<PasswordManagerContext>(options =>
options.UseSqlServer(settings.ConnectionString));
services.AddSingleton<MyMemoryCache>();
services.AddPaging(options =>
{
options.ViewName = "PagerUI";
options.HtmlIndicatorDown = " <span>↓</span>";
options.HtmlIndicatorUp = " <span>↑</span>";
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IAntiforgery antiforgery)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSession();
app.UseCookiePolicy();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Login}/{action=Index}/{id?}");
//endpoints.MapFallbackToController("Index", "Home");
});
ServiceProvider = app.ApplicationServices;
}
According to official docs, the order of these:
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints
matters but in my code they are ordered correctly.
What could be missing or what could possibly be wrong in the configuration?
Thanks in advance
I follow the tutorial link below.
https://fullstackmark.com/post/13/jwt-authentication-with-aspnet-core-2-web-api-angular-5-net-core-identity-and-facebook-login
I am trying to understand how it works and I want to use role-based authentication using this token. so I made another policy in the Startup.cs file as below.
And I tried to use it like [Authorize(Policy = "admin")] the controller but every time I try I get unauthenticated using postman.
What am I missing? how to make roles-based authentication based on the tutorial?
Configure
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.WithOrigins("http://localhost:4200", "http://localhost:44318")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions));
// Configure JwtIssuerOptions
services.Configure<JwtIssuerOptions>(options =>
{
options.Issuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
options.Audience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)];
options.SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256);
});
var tokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)],
ValidateAudience = true,
ValidAudience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)],
ValidateIssuerSigningKey = true,
IssuerSigningKey = _signingKey,
RequireExpirationTime = false,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(configureOptions =>
{
configureOptions.ClaimsIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
configureOptions.TokenValidationParameters = tokenValidationParameters;
configureOptions.SaveToken = true;
});
// api user claim policy
services.AddAuthorization(options =>
{
options.AddPolicy("ApiUser", policy => policy.RequireClaim(Constants.Strings.JwtClaimIdentifiers.Rol, Constants.Strings.JwtClaims.ApiAccess));
});
services.AddAuthorization(options =>
options.AddPolicy("admin", policy => policy.RequireRole("admin"))
);
var builder = services.AddIdentityCore<AppUser>(o =>
{
// configure identity options
o.Password.RequireDigit = false;
o.Password.RequireLowercase = false;
o.Password.RequireUppercase = false;
o.Password.RequireNonAlphanumeric = false;
o.Password.RequiredLength = 6;
});
builder = new IdentityBuilder(builder.UserType, typeof(IdentityRole), builder.Services);
builder.AddEntityFrameworkStores<CDSPORTALContext>().AddDefaultTokenProviders().AddRoles<IdentityRole>();
//.AddRoles<IdentityRole>()
services.AddControllers();
services.AddAutoMapper(typeof(Startup));
services.AddSingleton<IJwtFactory, JwtFactory>();
services.TryAddTransient<IHttpContextAccessor, HttpContextAccessor>();
services.AddScoped<IRegionRepository, RegionRepository>();
services.AddScoped<IRegionService, RegionService>();
services.AddScoped<IEmailHelper, EmailHelper>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseCors("CorsPolicy");
app.UseExceptionHandler(
builder =>
{
builder.Run(
async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
var error = context.Features.Get<IExceptionHandlerFeature>();
if (error != null)
{
context.Response.AddApplicationError(error.Error.Message);
await context.Response.WriteAsync(error.Error.Message).ConfigureAwait(false);
}
});
});
app.UseRouting();
app.UseStaticFiles();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseSpa(spa =>
{
spa.Options.SourcePath = "Client";
spa.UseAngularCliServer(npmScript: "start");
});
}
}
Auth Controller
// POST api/auth/login
[HttpPost("login")]
public async Task<IActionResult> Post([FromBody]CredentialsViewModel credentials)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var identity = await GetClaimsIdentity(credentials.UserName, credentials.Password);
if (identity == null)
{
//return null;
return BadRequest(Error.AddErrorToModelState("login_failure", "Invalid username or password.", ModelState));
}
var id = identity.Claims.Single(c => c.Type == "id").Value;
var user = await _userManager.FindByIdAsync(id);
IList<string> role = await _userManager.GetRolesAsync(user);
var jwt = await Tokens.GenerateJwt(identity, role[0], _jwtFactory, credentials.UserName, _jwtOptions, new JsonSerializerSettings { Formatting = Formatting.Indented });
return new OkObjectResult(jwt);
}
I tried with all method and none of them working
[Authorize(Policy = "ApiUser")]
[HttpGet("getPolicy")]
public string GetPolicy()
{
return "policyWorking";
}
[Authorize(Roles = "admin")]
[HttpGet("getAdmin")]
public string GetAdmin()
{
return "adminWorking";
}
[Authorize ]
[HttpGet("getAuthorize")]
public string GetAuthorize()
{
return "normal authorize Working";
}
Decoded Token
"jti": "840d507d-b2d0-454b-bd1f-007890d3e669",
"iat": 1587699300,
"rol": "api_access",
"id": "1ac370e2-f5e9-4404-b017-8a3c087e2196",
"nbf": 1587699299,
"exp": 1587706499
I forgot to add this to appsetting.
"JwtIssuerOptions": {
"Issuer": "webApi",
"Audience": "http://localhost:4200/"
}
As soon as I connect the SignalR to the application using Install-package Microsoft.AspNetCore.SignalR immediately stops working the POST method of one of the controllers. Without a signal, all works fine. Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options => options.UseMySql(configuration.GetConnectionString("DefaultConnection")));
var section = configuration.GetSection("AppSettings");
var settings = section.Get<AppSettings>();
services.Configure<AppSettings>(section);
var builder = services.AddIdentityCore<ApplicationUser>(user =>
{
user.Password.RequireDigit = true;
user.Password.RequireLowercase = false;
user.Password.RequireUppercase = false;
user.Password.RequireNonAlphanumeric = false;
user.Password.RequiredLength = 6;
});
builder = new IdentityBuilder(builder.UserType, typeof(IdentityRole), builder.Services);
builder.AddSignInManager<SignInManager<ApplicationUser>>();
builder.AddRoleValidator<RoleValidator<IdentityRole>>();
builder.AddRoleManager<RoleManager<IdentityRole>>();
builder.AddEntityFrameworkStores<ApplicationDbContext>();
builder.AddDefaultTokenProviders();
services.AddCors(options => options.AddPolicy("CorsPolicy", policy =>
{
policy
.AllowAnyMethod()
.AllowAnyHeader()
.AllowAnyOrigin()
.AllowCredentials();
}));
services.AddSignalR();
services.AddOData();
services.AddMvc();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = settings.issuer,
ValidAudience = settings.issuer,
IssuerSigningKey = JwtSecurityKey.Create(settings.key)
};
options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
if (context.Request.Path.Value.StartsWith("/chatHub") &&
context.Request.Query.TryGetValue("token", out StringValues token)
)
{
context.Token = token;
}
return Task.CompletedTask;
},
OnAuthenticationFailed = context =>
{
Console.WriteLine("OnAuthenticationFailed: " + context.Exception.Message);
return Task.CompletedTask;
},
OnTokenValidated = context =>
{
Console.WriteLine("OnTokenValidated: " + context.SecurityToken);
return Task.CompletedTask;
}
};
});
services.AddAuthorization(options =>
{
options.AddPolicy("user", policy => policy.RequireClaim("id"));
});
services.AddSingleton<ISendGridClient, SendGridClient>(serviceProvider =>
{
return new SendGridClient(settings.sendGridKey);
});
services.AddSingleton<ILogger>(serviceProvider =>
{
return loggerFactory.CreateLogger("logger");
});
services.AddSingleton<IEmailSender, EmailSender>();
services.AddSingleton<IUploader, Uploader>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();
app.UseAuthentication();
app.UseCors("CorsPolicy");
app.UseSignalR(routes =>
{
routes.MapHub<SignalRHub>("/chatHub");
});
app.UseMvc(routebuilder =>
{
routebuilder.MapRoute(name: "DefaultApi", template: "api/{controller=Home}/{action=Index}/{id?}");
});
}
Controller:
[Authorize(Policy = "user")]
public class UserFilesController : Controller
{
[HttpPost]
public async Task<IActionResult> SaveAvatar(AvatarModel avatar)
{
// Some code here, here the call does not even come
}
}
Calling in JavaScript
$.ajax({
method: 'POST',
url: serviceUrl + 'api/userfiles/saveavatar',
data: data,
headers: getHeaders()
}).done(function (UploadResult) {
// some code here
});