Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Text;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Authentication.JwtBearer;
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.DependencyInjection;
- using Microsoft.Extensions.Hosting;
- using Microsoft.IdentityModel.Tokens;
- using Microsoft.OpenApi.Models;
- using Simple_RPG_API.BAL;
- namespace Simple_RPG_API
- {
- public class Startup
- {
- public Startup(IConfiguration configuration)
- {
- Configuration = configuration;
- }
- public IConfiguration Configuration { get; }
- // This method gets called by the runtime. Use this method to add services to the container.
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddScoped<IUserService, UserService>();
- services.AddControllers();
- services.AddCors(options =>
- {
- options.AddDefaultPolicy(
- builder =>
- {
- builder.WithOrigins("http://localhost:4200")
- .AllowAnyHeader()
- .AllowAnyMethod();
- });
- });
- services.AddSwaggerGen(c =>
- {
- c.SwaggerDoc("v1", new OpenApiInfo { Title = "Simple_RPG_API", Version = "v1" });
- });
- services.AddScoped<IUserService, UserService>();
- var key = Encoding.ASCII.GetBytes(Configuration["AppSettings:Secret"]);
- services.AddAuthentication(x =>
- {
- x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
- x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
- })
- .AddJwtBearer(x =>
- {
- x.Events = new JwtBearerEvents
- {
- OnTokenValidated = context =>
- {
- var userService = context.HttpContext.RequestServices.GetRequiredService<IUserService>();
- var userId = int.Parse(context.Principal.Identity.Name);
- var user = userService.GetById(userId);
- if (user == null)
- {
- // return unauthorized if user no longer exists
- context.Fail("Unauthorized");
- }
- return Task.CompletedTask;
- }
- };
- x.RequireHttpsMetadata = false;
- x.SaveToken = true;
- x.TokenValidationParameters = new TokenValidationParameters
- {
- ValidateIssuerSigningKey = true,
- IssuerSigningKey = new SymmetricSecurityKey(key),
- ValidateIssuer = false,
- ValidateAudience = false
- };
- });
- }
- // 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();
- app.UseSwagger();
- app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Simple_RPG_API v1"));
- }
- app.UseHttpsRedirection();
- app.UseRouting();
- app.UseCors(x => x
- .AllowAnyOrigin()
- .AllowAnyMethod()
- .AllowAnyHeader());
- app.UseAuthorization();
- app.UseEndpoints(endpoints =>
- {
- endpoints.MapControllers();
- });
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement