Skip to content

Instantly share code, notes, and snippets.

@gsedubun
Created December 12, 2018 08:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gsedubun/e9707d5f99590584d1c802bc0f0acf95 to your computer and use it in GitHub Desktop.
Save gsedubun/e9707d5f99590584d1c802bc0f0acf95 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using Smart_Office.Data;
using Smart_Office.Data.ViewModels;
using Smart_Office.Models;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
namespace Smart_Office.Controllers
{
public class LoginController : Controller
{
private UserDataAccess da;
private IConfiguration _config;
private Authentication _auth;
private ILogger _logger;
public LoginController(UserDataAccess dataaccess, Authentication authentication, IConfiguration config, ILogger<LoginController> logger)
{
this.da = dataaccess;
this._config = config;
this._auth = authentication;
this._logger = logger;
}
public IActionResult Index()
{
return View();
//var room = da.GetUser();
//return View(room);
}
public IActionResult Register()
{
return View();
}
public IActionResult ForgotPassword()
{
return View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Index(LoginViewModel loginViewModel, [FromQuery] string ReturnUrl)
{
var userInfo = _auth.AuthenticateUser(loginViewModel);
if (userInfo != null)
{
var claims = new List<Claim>(){ new Claim(ClaimTypes.Name, userInfo.username),
new Claim(ClaimTypes.Email, userInfo.useremail),
new Claim(ClaimTypes.NameIdentifier, userInfo.username)
};
ClaimsIdentity identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
ClaimsPrincipal principal = new ClaimsPrincipal(identity);
var authProps = new AuthenticationProperties
{
IsPersistent = false,
};
// tabel log user login.
// insert into log_user_login values(.. .. .. .)
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, authProps);
return RedirectToAction("Index", "Home");
}
else
{
return View(loginViewModel);
}
}
[HttpPost]
public async Task<IActionResult> Logout()
{
var authProps = new AuthenticationProperties
{
IsPersistent = false,
};
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme, authProps);
// SignOut( new AuthenticationProperties(){ RedirectUri="/" }, CookieAuthenticationDefaults.AuthenticationScheme);
return RedirectToAction("Index", "Home");
}
[HttpPost]
public IActionResult Register(RegisterViewModel registerViewModel)
{
return View(registerViewModel);
}
[HttpPost]
public IActionResult ForgotPassword(ForgetPasswordViewModel forgetPasswordViewModel)
{
return View(forgetPasswordViewModel);
//var reg = da.GetUser();
//return View(reg);
}
[AllowAnonymous]
[HttpPost]
[Route("/api/login/token")]
public IActionResult Token([FromBody]LoginViewModel login)
{
IActionResult response = Unauthorized();
_logger.LogInformation("validating token for : " + login.username);
var user = _auth.AuthenticateUser(login);
if (user != null)
{
var tokenString = GenerateJSONWebToken(user);
response = Ok(new { token = tokenString });
}
return response;
}
private string GenerateJSONWebToken(TabelUser userInfo)
{
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:key"]));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
var claims = new List<Claim>(){ new Claim(ClaimTypes.Name, userInfo.username),
new Claim(ClaimTypes.Email, userInfo.useremail),
new Claim(ClaimTypes.NameIdentifier, userInfo.username)
};
var token = new JwtSecurityToken(_config["Jwt:issuer"],
_config["Jwt:issuer"],
claims,
expires: DateTime.Now.AddMinutes(1),
signingCredentials: credentials);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using Smart_Office.Data;
using Smart_Office.Models;
using Swashbuckle.AspNetCore.Swagger;
namespace Smart_Office
{
public class Startup
{
public Startup(IConfiguration configuration, ILogger<Startup> logger)
{
Configuration = configuration;
_Logger = logger;
}
public IConfiguration Configuration { get; }
private readonly ILogger _Logger;
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, d =>
{
d.LoginPath = new PathString("/Login/Index");
d.LogoutPath = new PathString("/Login/Logout");
d.SlidingExpiration = false;
d.ExpireTimeSpan = TimeSpan.FromMinutes(10);
}).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, opt =>
{
opt.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration["jwt:issuer"],
ValidAudience = Configuration["jwt:issuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["jwt:key"]))
};
});
services.AddScoped<UserDataAccess>(d => new UserDataAccess());
services.AddScoped<Authentication>(d => new Authentication(new UserDataAccess()));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddScoped<MeetingRoomDataAccess>(d => new MeetingRoomDataAccess());
services.AddScoped<FacilityDataAccess>(d => new FacilityDataAccess());
services.AddScoped<AttendeesDataAccess>(d => new AttendeesDataAccess());
services.AddScoped<MeetingTransactionDataAccess>(d => new MeetingTransactionDataAccess());
services.AddScoped<ListOfMeeting>(d => new ListOfMeeting());
services.AddScoped<BookingDataAccess>(d => new BookingDataAccess());
services.AddScoped<DetailDataAccess>(d => new DetailDataAccess());
// Register the Swagger generator, defining 1 or more Swagger documents
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "SmartOffice API", Version = "v1" });
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UsePathBase("/smartoffice");
app.Use((context, next) =>
{
context.Request.PathBase = "/smartoffice";
return next();
});
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseAuthentication();
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/smartoffice/swagger/v1/swagger.json", "SmartOffice API V1");
});
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment