I already create a OAuth Server and i would like to make a login to this site.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LocalLogin(LoginViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var member = memberService.VaildateMmember(model.UserName, model.Password);
if (member == null)
{
ModelState.AddModelError("", "Account or Password Error!");
return View(model);
}
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
var claims = new List<Claim>
{
new Claim(ClaimsIdentity.DefaultNameClaimType, member.AccountName),
new Claim(ClaimTypes.Name, member.AccountName),
new Claim(ClaimTypes.Email, member.Email),
new Claim(ClaimTypes.NameIdentifier, member.Id.ToString())
};
var claimsIdentity = new ClaimsIdentity(
claims,
DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignIn(
new AuthenticationProperties
{
IsPersistent = true,
IssuedUtc = DateTime.UtcNow,
ExpiresUtc = DateTime.UtcNow.Add(TimeSpan.FromMinutes(30))
},
claimsIdentity);
return RedirectToAction("Index", "Home");
}
And i create my own AuthorizeAttribute.
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext == null)
return false;
var user = httpContext.User.Identity;
if (!user.IsAuthenticated) //here Always false
return false;
//CheckUser
if (Users.Length > 0 && !Users.Split(',').Contains(user.Name, StringComparer.OrdinalIgnoreCase))
return false;
//CheckRole
if (!IsHasRoles(user))
return false;
//CheckScope
if (!IsHasScope(user))
return false;
return true;
}
I don't know what's wrong here.
Why httpContext.User.Identity.IsAuthenticated always return false.
Related
I generate a session in my code but then when using it in another file the session returns null, thx all!
this linux server primefaces,payara 5
public Usuarios loginUsuario(String usuario, String password) {
Usuarios user = null;
try {
UsuariosDAO us = new UsuariosDAO();
user = us.loginUsuario(usuario, password);
if (user != null) {
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("usuario", user); // here set user ok! not null
FacesContext.getCurrentInstance().getExternalContext().redirect("index.xhtml");
} else {
FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atencion!", "User o Password Inconrrectos"));
}
} catch (Exception e) {
System.out.println(e);
}
return user;
}
public void probarSession() {
try {
FacesContext esta = FacesContext.getCurrentInstance();
System.err.println(esta.getExternalContext().getSessionMap().get("usuario")+"this is null!!!");
Usuarios us = (Usuarios) esta.getExternalContext().getSessionMap().get("usuario");
if (us == null) {
esta.getExternalContext().redirect("login.xhtml");
}
} catch (IOException e) {
System.err.println(e);
}
}
I'm checking, if a given user is part of a group by this code below. I'm getting
unauthorized exception
(0x80070005)
and I do not understand why? I'm using SPSecurity.RunWithElevatedPrivileges, so why it is giving me this exception!? Anybody a hint for me? Thanks in advance!
public bool IsUserInGroup(SPWeb web, string groupName, string user)
{
try
{
bool returnValue = false;
SPSecurity.RunWithElevatedPrivileges(() =>
{
if (web.Groups.OfType<SPGroup>().Where(g => g.Name == groupName).Count() > 0)
{
SPGroup spGroup = web.Groups[groupName];
if (spGroup.Users.OfType<SPUser>().Where(u => u.LoginName.Equals(user)).Count() > 0)
{
returnValue = true;
}
else
{
returnValue = false;
}
}
else
{
returnValue = false;
}
});
return returnValue;
}
catch (Exception exp)
{
Classes.Logs.Error.Log_Error("IsUserInGroup", "DocumentCenterItem.cs", exp.Message, DateTime.Now);
return false;
}
}
You need to create a new instance of SP Web inside elevated privileges. In your current implementation, you are reusing the web object which runs in current user context.
So, try and modify the below code as per your requirement :
public bool IsUserInGroup(SPWeb web, string groupName, string user)
{
try
{
bool returnValue = false;
SPSecurity.RunWithElevatedPrivileges(() =>
{
using(SPSite site = new SPSite(web.Site.ID))
{
using(SPWeb elevatedWeb = site.OpenWeb(web.ID))
{
if (elevatedWeb.Groups.OfType<SPGroup>().Where(g => g.Name == groupName).Count() > 0)
{
SPGroup spGroup = elevatedWeb.Groups[groupName];
if (spGroup.Users.OfType<SPUser>().Where(u => u.LoginName.Equals(user)).Count() > 0)
{
returnValue = true;
}
else
{
returnValue = false;
}
}
else
{
returnValue = false;
}
}
}
});
return returnValue;
}
catch (Exception exp)
{
Classes.Logs.Error.Log_Error("IsUserInGroup", "DocumentCenterItem.cs", exp.Message, DateTime.Now);
return false;
}
}
I have a self-hosted Web API OData v3 service:
public class Startup
{
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
ODataModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Product>("Products");
config.MapODataServiceRoute(
routeName: "ODataRoute",
routePrefix: null,
model: builder.GetEdmModel());
app.UseWebApi(config);
}
}
I also have the following Controller, which exposes a full CRUD:
public class ProductsController : ODataController
{
ApplicationDbContext db = new ApplicationDbContext();
private bool ProductExists(int key)
{
return db.Products.Any(p => p.Id == key);
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
[EnableQuery]
public IQueryable<Product> Get()
{
return db.Products;
}
[EnableQuery]
public SingleResult<Product> Get([FromODataUri] int key)
{
IQueryable<Product> result = db.Products.Where(p => p.Id == key);
return SingleResult.Create(result);
}
public async Task<IHttpActionResult> Post(Product product)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Products.Add(product);
await db.SaveChangesAsync();
return Created(product);
}
public async Task<IHttpActionResult> Patch([FromODataUri] int key, Delta<Product> product)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var entity = await db.Products.FindAsync(key);
if (entity == null)
{
return NotFound();
}
product.Patch(entity);
try
{
await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductExists(key))
{
return NotFound();
}
else
{
throw;
}
}
return Updated(entity);
}
public async Task<IHttpActionResult> Put([FromODataUri] int key, Product update)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (key != update.Id)
{
return BadRequest();
}
db.Entry(update).State = EntityState.Modified;
try
{
await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductExists(key))
{
return NotFound();
}
else
{
throw;
}
}
return Updated(update);
}
public async Task<IHttpActionResult> Delete([FromODataUri] int key)
{
var product = await db.Products.FindAsync(key);
if (product == null)
{
return NotFound();
}
db.Products.Remove(product);
await db.SaveChangesAsync();
return StatusCode(HttpStatusCode.NoContent);
}
}
I am able to access this feed from a browser without any issues.
However, when I try to get Excel 2013 to use this data feed (using this url: http://localhost:8080/Products), I get this error:
"We can't use the data from this feed. Make sure the external data feed server is available and your connection information is correct"
What can I do to make Excel 2013 to work with this data feed?
I have the following OData Controller, which provides for all common CRUD operations:
public class ProductsController : ODataController
{
ApplicationDbContext db = new ApplicationDbContext();
private bool ProductExists(int key)
{
return db.Products.Any(p => p.Id == key);
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
[EnableQuery]
public IQueryable<Product> Get()
{
return db.Products;
}
[EnableQuery]
public SingleResult<Product> Get([FromODataUri] int key)
{
IQueryable<Product> result = db.Products.Where(p => p.Id == key);
return SingleResult.Create(result);
}
public async Task<IHttpActionResult> Post(Product product)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Products.Add(product);
await db.SaveChangesAsync();
return Created(product);
}
public async Task<IHttpActionResult> Patch([FromODataUri] int key, Delta<Product> product)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var entity = await db.Products.FindAsync(key);
if (entity == null)
{
return NotFound();
}
product.Patch(entity);
try
{
await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductExists(key))
{
return NotFound();
}
else
{
throw;
}
}
return Updated(entity);
}
public async Task<IHttpActionResult> Put([FromODataUri] int key, Product update)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (key != update.Id)
{
return BadRequest();
}
db.Entry(update).State = EntityState.Modified;
try
{
await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductExists(key))
{
return NotFound();
}
else
{
throw;
}
}
return Updated(update);
}
public async Task<IHttpActionResult> Delete([FromODataUri] int key)
{
var product = await db.Products.FindAsync(key);
if (product == null)
{
return NotFound();
}
db.Products.Remove(product);
await db.SaveChangesAsync();
return StatusCode(HttpStatusCode.NoContent);
}
}
Is it possible to use MS Excel's OData client capabilities to use Excel as a data management tool to perform addition, deletion, complete and partial updates of the data exposed via my controller?
How can we display login page in Ajax popup box on homepage load in Magento that to popup box need to come only one time until browser is closed and i also need to place FB connect to same popup box .can any reply me soon please
Hi you can use any lightbox plugin to display the code, and to show login in popup you can override the customer AccountController.php like this
protected $_validActions = array('create','login','logoutSuccess','forgotpassword','forgotpasswordpost','confirm','confirmation','resetpassword','resetpasswordpost');
protected $_customActions = array('signupformpopup','ajaxLogin','ajaxCreate');
public function preDispatch()
{
// a brute-force protection here would be nice
$action = $this->getRequest()->getActionName();
if (preg_match('/^('.$this->_getCustomActions().')/i', $action))
{
$this->getRequest()->setActionName($this->_validActions[1]);
}
parent::preDispatch();
if ($action != $this->getRequest()->getActionName())
{
$this->getRequest()->setActionName($action);
}
if (!$this->getRequest()->isDispatched()) {
return;
}
if (!preg_match('/^('.$this->_getValidActions().')/i', $action)) {
if (!$this->_getSession()->authenticate($this)) {
$this->setFlag('', 'no-dispatch', true);
}
} else {
$this->_getSession()->setNoReferer(true);
}
}
protected function _getValidActions()
{
return implode("|", array_merge($this->_validActions, $this->_customActions));
}
protected function _getCustomActions()
{
return implode("|", $this->_customActions);
}
/**
* Login post action
*/
public function ajaxLoginAction() {
if ($this->_getSession()->isLoggedIn()) {
$this->_redirect('*/*/');
return;
}
$session = $this->_getSession();
$result=array();
if ($this->getRequest()->isPost()) {
$login = $this->getRequest()->getPost('login');
if (!empty($login['username']) && !empty($login['password'])) {
try {
$session->login($login['username'], $login['password']);
if ($session->getCustomer()->getIsJustConfirmed()) {
$this->_welcomeCustomer($session->getCustomer(), true);
}
$result['success'] = true;
$result['redirecturl'] = Mage::getUrl('customer/account/edit');
} catch (Mage_Core_Exception $e) {
switch ($e->getCode()) {
case Mage_Customer_Model_Customer::EXCEPTION_EMAIL_NOT_CONFIRMED:
/*$message = Mage::helper('customer')->__('This account is not confirmed. Click here to resend confirmation email.', Mage::helper('customer')->getEmailConfirmationUrl($login['username']));*/
$result['success'] = false;
$result['message'] = Mage::helper('customer')->__('This account is not confirmed.');
break;
case Mage_Customer_Model_Customer::EXCEPTION_INVALID_EMAIL_OR_PASSWORD:
$message = $e->getMessage();
$result['success'] = false;
$result['message'] = Mage::helper('customer')->__($message);
break;
default:
$message = $e->getMessage();
$result['success'] = false;
$result['message'] = Mage::helper('customer')->__($message);
}
//$session->addError($message);
$session->setUsername($login['username']);
} catch (Exception $e) {
// Mage::logException($e); // PA DSS violation: this exception log can disclose customer password
}
} else {
//$session->addError($this->__('Login and password are required.'));
$result['success'] = false;
$result['message'] = Mage::helper('customer')->__('Login and password are required.');
}
}
$this->getResponse()->setBody(Zend_Json::encode($result));
//$this->_loginPostRedirect();
}
/**
* Login post action
*/
public function ajaxCreateAction()
{
$session = $this->_getSession();
if ($session->isLoggedIn()) {
$this->_redirect('*/*/');
return;
}
$session->setEscapeMessages(true); // prevent XSS injection in user input
if ($this->getRequest()->isPost()) {
$errors = array();
if (!$customer = Mage::registry('current_customer')) {
$customer = Mage::getModel('customer/customer')->setId(null);
}
/* #var $customerForm Mage_Customer_Model_Form */
$customerForm = Mage::getModel('customer/form');
$customerForm->setFormCode('customer_account_create')
->setEntity($customer);
$customerData = $customerForm->extractData($this->getRequest());
if ($this->getRequest()->getParam('is_subscribed', false)) {
$customer->setIsSubscribed(1);
}
/**
* Initialize customer group id
*/
$customer->getGroupId();
if ($this->getRequest()->getPost('create_address')) {
/* #var $address Mage_Customer_Model_Address */
$address = Mage::getModel('customer/address');
/* #var $addressForm Mage_Customer_Model_Form */
$addressForm = Mage::getModel('customer/form');
$addressForm->setFormCode('customer_register_address')
->setEntity($address);
$addressData = $addressForm->extractData($this->getRequest(), 'address', false);
$addressErrors = $addressForm->validateData($addressData);
if ($addressErrors === true) {
$address->setId(null)
->setIsDefaultBilling($this->getRequest()->getParam('default_billing', false))
->setIsDefaultShipping($this->getRequest()->getParam('default_shipping', false));
$addressForm->compactData($addressData);
$customer->addAddress($address);
$addressErrors = $address->validate();
if (is_array($addressErrors)) {
$errors = array_merge($errors, $addressErrors);
}
} else {
$errors = array_merge($errors, $addressErrors);
}
}
try {
$customerErrors = $customerForm->validateData($customerData);
if ($customerErrors !== true) {
$errors = array_merge($customerErrors, $errors);
} else {
$customerForm->compactData($customerData);
$customer->setPassword($this->getRequest()->getPost('password'));
$customer->setConfirmation($this->getRequest()->getPost('confirmation'));
$customerErrors = $customer->validate();
if (is_array($customerErrors)) {
$errors = array_merge($customerErrors, $errors);
}
}
$validationResult = count($errors) == 0;
$result = array();
if (true === $validationResult) {
$customer->save();
if ($customer->isConfirmationRequired()) {
$customer->sendNewAccountEmail('confirmation', $session->getBeforeAuthUrl());
// $session->addSuccess($this->__('Account confirmation is required. Please, check your email for the confirmation link. To resend the confirmation email please click here.', Mage::helper('customer')->getEmailConfirmationUrl($customer->getEmail())));
//$this->_redirectSuccess(Mage::getUrl('*/*/index', array('_secure'=>true)));
//return;
$result['success'] = true;
$result['message'] = $this->__('Account confirmation is required. Please, check your email for the confirmation link. To resend the confirmation email please click here.', Mage::helper('customer')->getEmailConfirmationUrl($customer->getEmail()));
} else {
$session->setCustomerAsLoggedIn($customer);
$url = $this->_welcomeCustomer($customer);
//$this->_redirectSuccess($url);
//return;
$result['success'] = true;
$result['message'] = $this->__('You are successfully registered');
}
} else {
$session->setCustomerFormData($this->getRequest()->getPost());
if (is_array($errors)) {
$result['success'] = false;
foreach ($errors as $errorMessage) {
//$session->addError($errorMessage);
$result['message'] .= $errorMessage;
}
} else {
//$session->addError($this->__('Invalid customer data'));
$result['success'] = false;
$result['message'] = $this->__('Invalid customer data');
}
}
} catch (Mage_Core_Exception $e) {
$session->setCustomerFormData($this->getRequest()->getPost());
if ($e->getCode() === Mage_Customer_Model_Customer::EXCEPTION_EMAIL_EXISTS) {
$url = Mage::getUrl('customer/account/forgotpassword');
$result['success'] = false;
$result['message'] = $this->__('There is already an account with this email address. If you are sure that it is your email address.');
} else {
$result['success'] = false;
$result['message'] = $e->getMessage();
}
//$session->addError($message);
} catch (Exception $e) {
// $session->setCustomerFormData($this->getRequest()->getPost())
// ->addException($e, $this->__('Cannot save the customer.'));
$result['success'] = false;
$result['message'] = $this->__('Cannot save the customer.');
}
}
//$this->_redirectError(Mage::getUrl('*/*/create', array('_secure' => true)));
$this->getResponse()->setBody(Zend_Json::encode($result));
}
}