· 9 years ago · Jun 08, 2016, 05:24 PM
1public class Startup
2 {
3 public IConfigurationRoot Configuration { get; }
4
5 public Startup(IHostingEnvironment env)
6 {
7 IConfigurationBuilder builder = new ConfigurationBuilder().SetBasePath(env.ContentRootPath)
8 .AddJsonFile("appsettings.json", true, true)
9 .AddJsonFile($"appsettings.{env.EnvironmentName}.json", true)
10 .AddEnvironmentVariables();
11 //---
12 Configuration = builder.Build();
13 }
14
15 public void ConfigureServices(IServiceCollection services)
16 {
17 services.AddMvc();
18 }
19
20 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
21 {
22 app.Use(async (context, next) =>
23 {
24 try
25 {
26 await next();
27 }
28 catch (Exception ex)
29 {
30 if (context.Response.HasStarted)
31 {
32 throw;
33 }
34 context.Response.StatusCode = 500;
35 await context.Response.WriteAsync(ex.ToString());
36 }
37 });
38 //---
39 app.UseMvc();
40 //---
41 const string secretKey = "mysupersecret_secretkey!123";
42 SymmetricSecurityKey signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));
43 SigningCredentials signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
44 //---
45 const string audience = "Audience";
46 const string issuer = "Issuer";
47 //---
48 TokenValidationParameters tokenValidationParameters = new TokenValidationParameters
49 {
50 ValidateIssuerSigningKey = true,
51 IssuerSigningKey = signingKey,
52
53 ValidateIssuer = false,
54 ValidIssuer = issuer,
55
56 ValidateAudience = true,
57 ValidAudience = audience,
58
59 ValidateLifetime = true,
60
61 ClockSkew = TimeSpan.Zero,
62 AuthenticationType = JwtBearerDefaults.AuthenticationScheme
63 };
64 //---
65 app.UseJwtBearerAuthentication(new JwtBearerOptions
66 {
67 AutomaticAuthenticate = true,
68 AutomaticChallenge = true,
69 TokenValidationParameters = tokenValidationParameters,
70 AuthenticationScheme = JwtBearerDefaults.AuthenticationScheme,
71 });
72 //---
73 app.UseSimpleTokenProvider(new TokenProviderOptions
74 {
75 Path = "/api/token",
76 Audience = audience,
77 Issuer = issuer,
78 SigningCredentials = signingCredentials,
79 Expiration = TimeSpan.FromDays(1),
80 IdentityResolver = GetIdentity
81 });
82 }
83
84 private Task<ClaimsIdentity> GetIdentity(string username, string password)
85 {
86 if (username == "TEST" && password == "TEST123")
87 {
88 return Task.FromResult(new ClaimsIdentity(new GenericIdentity(username, "Token"), new Claim[] { }));
89 }
90
91 return Task.FromResult<ClaimsIdentity>(null);
92 }
93 }