Steps:
1.Solution explorer -> App start ->Startup.Auth.cs
after open this file:
// 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 {
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Authentication/Login")
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Configure the application for OAuth based flow
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/login"),
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 = ""
//});
}
--------------------------------------Authentication controller----------------------------------------------------
public class AuthenticationController : Controller
{
public AuthenticationController()
: this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
{
}
public AuthenticationController(UserManager<ApplicationUser> userManager)
{
UserManager = userManager;
}
public UserManager<ApplicationUser> UserManager { get; private set; }
private Entities db = new Entities();
// GET: Authentication
public ActionResult Login()
{
return View();
}
// GET: Authentication/Details/5
public ActionResult Details(int id)
{
return View();
}
// GET: Authentication/Create
public ActionResult Create()
{
return View();
}
[HttpPost, ActionName("Login")]
public async Task<ActionResult> LoginPost(LoginModel model)
{
if(!ModelState.IsValid)
{
return View(model);
}
try {
var user = await UserManager.FindAsync(model.UserName, model.Password);
if ((user != null) && (UserManager.IsInRole(user.Id, Enum.GetName(typeof(Enums.Role), 1))))
{
await SignInAsync(user,true);
return RedirectToAction("Index", "Home");
}
else if ((user != null))
{
//ViewBag.ErrorMessage = ErrorMessage.AccessDenied; //ErrorMessage.AccessDenied;
ModelState.AddModelError("Authentication", ErrorMessage.AccessDenied);
}
else
{
ModelState.AddModelError("Authentication", ErrorMessage.InvalidCredentials);
//ViewBag.ErrorMessage = ErrorMessage.InvalidCredentials; //"Incorrect password";
}
return View(model);
}
catch (Exception ex)
{
ErrorLog.HandleException(ex);
return RedirectToAction("Index", "Error");
}
}
public ActionResult Logout()
{
try
{
AuthenticationManager.SignOut();
HttpCookieCollection cookieCollection = Request.Cookies;
}
catch(Exception ex)
{
ErrorLog.HandleException(ex);
}
return RedirectToAction("Login", "Authentication");
}
[HttpGet]
public ActionResult ResetPassword(string userId, string code)
{
ResetPasswordModel model = new ResetPasswordModel();
model.UserId = userId;
model.Code = code;
if( string.IsNullOrWhiteSpace(userId) && string.IsNullOrWhiteSpace(code) )
{
//ModelState.AddModelError(ErrorMessage.ErrorCode, ErrorMessage.InvalidUser);
return RedirectToAction("PageNotFound", "Error");
}
var user = UserManager.FindById(userId);
if (user == null)
{
return RedirectToAction("PageNotFound", "Error");
}
var codeReplace = code.Replace(" ", "+");
if (! db.Users.Any(x => x.Email ==user.Email && x.ResetToken== codeReplace))
{
ViewBag.ErrorMessage = ErrorMessage.AlreadyPasswordReset;
return View(model);
}
return View(model);
}
private IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.GetOwinContext().Authentication;
}
}
private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
//// Add more custom claims here if you want. Eg HomeTown can be a claim for the User
////var homeclaim = new Claim(ClaimTypes.Country, user.HomeTown);
////identity.AddClaim(homeclaim);
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}
// POST: Authentication/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Authentication/Edit/5
public ActionResult Edit(int id)
{
return View();
}
// POST: Authentication/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// TODO: Add update logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Authentication/Delete/5
public ActionResult Delete(int id)
{
return View();
}
// POST: Authentication/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
------------------------------Helper class for getting current user details --------------
public static class AuthenticationHelper
{
public static async Task<LoggedinUser> GetLoggedinUserDetails(HttpContext context)
{
try
{
var db=new YourDbEntity()
var userrights = await db.tbl_userrights.FirstOrDefaultAsync(x => x.Userid == HttpContext.Current.User.Identity.Name && x.Delmark == null);
var user = new LoggedinUser();
if (userrights != null)
{
user.Userid = userrights.Userid;
user.AddConfig = userrights.AddConfig;
user.DeleteConfig = userrights.DeleteConfig;
user.EditConfig = userrights.EditConfig;
user.Email = userrights.Email;
user.Category = userrights.Category;
user.MenuConfig = userrights.MenuConfig;
user.Name = userrights.Name;
}
string loggedUser = JsonConvert.SerializeObject(user);
context.Response.Cookies["CurrentUser"].Value = loggedUser;
return user;
}
catch
{
throw;
}
}
---------------------------------------------------------home controller----------------------------------------------
// [Authorize(Roles = GlobalVariable.ADMIN)]
[Authorize]
public class HomeController : Controller
{
var user = AuthenticationHelper.GetLoggedinUserDetails(HttpContext.Current).GetAwaiter().GetResult();
}
1.Solution explorer -> App start ->Startup.Auth.cs
after open this file:
// 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 {
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Authentication/Login")
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Configure the application for OAuth based flow
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/login"),
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 = ""
//});
}
--------------------------------------Authentication controller----------------------------------------------------
public class AuthenticationController : Controller
{
public AuthenticationController()
: this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
{
}
public AuthenticationController(UserManager<ApplicationUser> userManager)
{
UserManager = userManager;
}
public UserManager<ApplicationUser> UserManager { get; private set; }
private Entities db = new Entities();
// GET: Authentication
public ActionResult Login()
{
return View();
}
// GET: Authentication/Details/5
public ActionResult Details(int id)
{
return View();
}
// GET: Authentication/Create
public ActionResult Create()
{
return View();
}
[HttpPost, ActionName("Login")]
public async Task<ActionResult> LoginPost(LoginModel model)
{
if(!ModelState.IsValid)
{
return View(model);
}
try {
var user = await UserManager.FindAsync(model.UserName, model.Password);
if ((user != null) && (UserManager.IsInRole(user.Id, Enum.GetName(typeof(Enums.Role), 1))))
{
await SignInAsync(user,true);
return RedirectToAction("Index", "Home");
}
else if ((user != null))
{
//ViewBag.ErrorMessage = ErrorMessage.AccessDenied; //ErrorMessage.AccessDenied;
ModelState.AddModelError("Authentication", ErrorMessage.AccessDenied);
}
else
{
ModelState.AddModelError("Authentication", ErrorMessage.InvalidCredentials);
//ViewBag.ErrorMessage = ErrorMessage.InvalidCredentials; //"Incorrect password";
}
return View(model);
}
catch (Exception ex)
{
ErrorLog.HandleException(ex);
return RedirectToAction("Index", "Error");
}
}
public ActionResult Logout()
{
try
{
AuthenticationManager.SignOut();
HttpCookieCollection cookieCollection = Request.Cookies;
}
catch(Exception ex)
{
ErrorLog.HandleException(ex);
}
return RedirectToAction("Login", "Authentication");
}
[HttpGet]
public ActionResult ResetPassword(string userId, string code)
{
ResetPasswordModel model = new ResetPasswordModel();
model.UserId = userId;
model.Code = code;
if( string.IsNullOrWhiteSpace(userId) && string.IsNullOrWhiteSpace(code) )
{
//ModelState.AddModelError(ErrorMessage.ErrorCode, ErrorMessage.InvalidUser);
return RedirectToAction("PageNotFound", "Error");
}
var user = UserManager.FindById(userId);
if (user == null)
{
return RedirectToAction("PageNotFound", "Error");
}
var codeReplace = code.Replace(" ", "+");
if (! db.Users.Any(x => x.Email ==user.Email && x.ResetToken== codeReplace))
{
ViewBag.ErrorMessage = ErrorMessage.AlreadyPasswordReset;
return View(model);
}
return View(model);
}
private IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.GetOwinContext().Authentication;
}
}
private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
//// Add more custom claims here if you want. Eg HomeTown can be a claim for the User
////var homeclaim = new Claim(ClaimTypes.Country, user.HomeTown);
////identity.AddClaim(homeclaim);
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}
// POST: Authentication/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Authentication/Edit/5
public ActionResult Edit(int id)
{
return View();
}
// POST: Authentication/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// TODO: Add update logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Authentication/Delete/5
public ActionResult Delete(int id)
{
return View();
}
// POST: Authentication/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
------------------------------Helper class for getting current user details --------------
public static class AuthenticationHelper
{
public static async Task<LoggedinUser> GetLoggedinUserDetails(HttpContext context)
{
try
{
var db=new YourDbEntity()
var userrights = await db.tbl_userrights.FirstOrDefaultAsync(x => x.Userid == HttpContext.Current.User.Identity.Name && x.Delmark == null);
var user = new LoggedinUser();
if (userrights != null)
{
user.Userid = userrights.Userid;
user.AddConfig = userrights.AddConfig;
user.DeleteConfig = userrights.DeleteConfig;
user.EditConfig = userrights.EditConfig;
user.Email = userrights.Email;
user.Category = userrights.Category;
user.MenuConfig = userrights.MenuConfig;
user.Name = userrights.Name;
}
string loggedUser = JsonConvert.SerializeObject(user);
context.Response.Cookies["CurrentUser"].Value = loggedUser;
return user;
}
catch
{
throw;
}
}
---------------------------------------------------------home controller----------------------------------------------
// [Authorize(Roles = GlobalVariable.ADMIN)]
[Authorize]
public class HomeController : Controller
{
var user = AuthenticationHelper.GetLoggedinUserDetails(HttpContext.Current).GetAwaiter().GetResult();
}
No comments:
Post a Comment