isAuthenticated() not working with my custom authentication provider .? - spring-mvc

I'm new with spring security ,
I have made a custom authentication provider to check if the user haw access to the secured page or not via database.
every thing was ok, but when I added <intercept-url pattern="/home" access="isAuthenticated()" /> to security configuration an error occurs !
this is my userService :
public Authentication authenticate(Authentication auth) throws AuthenticationException {
Logger logger = null;
logger = Logger.getLogger(Logger.class.getName());
PropertyConfigurator.configure("src/main/resources/log4j.properties");
ResultSet resultSet = null;
PreparedStatement preparedStatement = null;
Connection connection = null;
name= auth.getName();
pwd=auth.getCredentials().toString();
UsernamePasswordAuthenticationToken ret=null;
String select_auth= "select username,password from users where username=? and password=?";
try {
connection = dataSource1.getConnection();
preparedStatement = connection.prepareStatement(select_auth);
preparedStatement.setString(1,name);
preparedStatement.setString(2,pwd);
resultSet = preparedStatement.executeQuery();
if(resultSet.next()){
logger.info("user <"+name+"> is connected");
ret= new UsernamePasswordAuthenticationToken(name, null);}
else
{
ret= null;
}
} catch (SQLException e) {
logger.error("SQLException: " + e.getMessage());
e.printStackTrace();
}
and this is my seurity-config
<http use-expressions="true" auto-config="true">
<form-login login-page="/login.jsp" default-target-url="/home"
authentication-failure-url="/403" />
<logout logout-success-url="/login" />
<intercept-url pattern="/home" access="isAuthenticated()" />
</http>
could someone help me ,or explain me what's the cause of the problem ?
Thanks in advance.

Related

org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource 'verificationEmail.vm'

I have seen the solution regarding this question but i did not found any solution for my scenario.
my mailsender.xml is
<bean id="velocityEngine"
class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
<property name="resourceLoaderPath" value="/email_Templates" />
<property name="preferFileSystemAccess" value="false" />
</bean>
and my velocity implementation code is..
public void sendUserActivationMail(User user, String requestUrl) throws Exception {
String plainText = System.currentTimeMillis() + "##" + user.getUserId();
userDao.insertRegistraionToken(user.getUserId(), plainText, "123456");
String token = AESEncrypter.encrypt(plainText);
String url = requestUrl + "/activateUser.htm?token=" + URLEncoder.encode(token, "UTF-8");
try {
Map<String, Object> storemap = new HashMap<String, Object>();
storemap.put("toUserName", user.getName());
storemap.put("fromUseerName", ApplicationConstants.TEAM_NAME);
storemap.put("url", url);
String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "verificationEmail.vm", "UTF-8", storemap);
mailService.sendMail(senderMailId, new String[] { user.getEmail() }, null, "Registration Activation", text);
} catch (Exception e) {
logger.println(IMessage.ERROR,new StringBuilder(CLASS_NAME).append("::runProfileIncompleteCron() exception ==" + e));
}
}
my folder structure is-
src/main/resources
|_email_Templates
|
|__verificationEmail.vm
But is shows error
org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource 'verificationEmail.vm'

How to get current user ID

I'm developing a web page and when you sign up and login you need to complete your information (name, last name, career, gender).
I've created a stored procedure:
ALTER PROCEDURE [dbo].[añadirinfocontacto]
#id int,#apellidoP nvarchar(50),#apellidoM nvarchar(50),#nombre nvarchar(50),#idEspecialidad int,#sexo nvarchar(10)
AS
BEGIN
if(#id=1)
begin
update Tbl_alumnos set nombre=#nombre,apellido_paterno=#apellidoP,apellido_materno=#apellidoM,id_especialidad=#idEspecialidad,sexo=#sexo where id_usuarios=#id
end
else
if(#id=2)
begin
update Tbl_Maestros set nombre=#nombre,apellido_paterno=#apellidoP,apellido_materno=#apellidoM,id_especialidad=#idEspecialidad,sexo=#sexo where id_usuarios=#id
end
else
begin
update Tbl_Administradores set nombre=#nombre,apellido_paterno=#apellidoP,apellido_materno=#apellidoM,id_especialidad=#idEspecialidad,sexo=#sexo where id_usuarios=#id
end
END
Code:
public static EntUsuario Actualizar(int idU,string nombre, string Apellidop,string ApellidoM,int IdEsp,string sexo)
{
EntUsuario obj = null;
SqlCommand cmd = null;
SqlDataReader dr = null;
try
{
Conexion cn = new Conexion( );
SqlConnection cnx = cn.conectar();
cmd = new SqlCommand("añadirinfocontacto", cnx);
cmd.Parameters.AddWithValue("#id", idU);
cmd.Parameters.AddWithValue("#nombre", nombre);
cmd.Parameters.AddWithValue("#apellidoP", Apellidop);
cmd.Parameters.AddWithValue("#apellidoM", ApellidoM);
cmd.Parameters.AddWithValue("#idEspecialidad", IdEsp);
cmd.Parameters.AddWithValue("#sexo", sexo);
cmd.CommandType = CommandType.StoredProcedure;
cnx.Open();
cmd.ExecuteNonQuery();
cnx.Close();
}
catch (Exception e)
{
obj = null;
}
finally
{
cmd.Connection.Close();
}
return obj;
}
And the Cick button event
protected void btnConfirmar_Click(object sender, EventArgs e)
{
Guid guid = (Guid)Membership.GetUser().ProviderUserKey;
EntUsuario obj = GbUsuario.Actualizar(Convert.ToInt32(guid),txtNombre.Text,txtApP.Text,txtApM.Text,Convert.ToInt32(dpEspecialidad.SelectedValue),RadioButtonList1.SelectedValue);
}
I want to get de user's ID but I don't know what to do, I've read about Session["user_id"], Membership.getUser, I also read that I need to configure web.config.
If I use the sample code above I use Membership.getUser but appears an error saying that it couldn't conect to database
enter code hereYou can get the current user with the following code:
var user = System.Web.HttpContext.Current.User
You can force users to log in by adding this to the web.config:
<configuration>
<system.web>
<authentication mode="Windows" />
<authorization>
<deny users="?"/>
</authorization>
</system.web>
</configuration>

Mailbox name not allowed

I am having a problem to send out a test email using "system.net.mail". The error message " Mailbox name not allowed. The server response was: 5.3.0 Relaying denied check mail first" every time I press the submit button. Thank you in advance.
Code_behind:
public class MailHelper
{
public static void SendMailMessage(string from, string to, string bcc,
string cc, string subject, string body)
{
MailMessage mMailMessage = new MailMessage();
mMailMessage.From = new MailAddress(from);
mMailMessage.To.Add(new MailAddress(to));
if ((bcc != null) && (bcc != string.Empty))
{
mMailMessage.Bcc.Add(new MailAddress(bcc));
}
if ((cc != null) && (cc != string.Empty))
{
mMailMessage.CC.Add(new MailAddress(cc));
}
mMailMessage.Subject = subject;
mMailMessage.Body = body;
mMailMessage.IsBodyHtml = true;
mMailMessage.Priority = MailPriority.Normal;
string smtpServer = "";
//Read the Web.config to get configuration setting
smtpServer=System.Web.Configuration.WebConfigurationManager.AppSettings["smtp"];
// Instantiate a new instance of SmtpClient
SmtpClient mSmtpClient = new SmtpClient(smtpServer);
// Send the mail message
mSmtpClient.Send(mMailMessage);
}
}
Web_config:
<appSettings>
<add key="smtp" value="smtp.mydomain.com"/>
</appSettings>
<system.net>
<mailSettings>
<smtp from="defaultEmail#mydomain.com">
<network host="smtp.mydomain.com" port="25" userName="yourUserName" password="yourPassword"/>
</smtp>
</mailSettings>
</system.net>
Sumbit_Click:
protected void Sumbit_Click(object sender, EventArgs e)
{
MailHelper.SendMailMessage("from#email.com", "to#email.com", null, null,
"subject", "textEnquiry.Text");
}

connecting to access database and query user login information not pulling data back

any help would be great thank you. not sure why its all ways returning a null
I'm not sure if its even connecting to the database.
my web config file
<configuration>
<connectionStrings>
<add name="accessConnectionString" providerName="Microsoft.Jet.OLEDB.4.0" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\***\Desktop\pratice\AccessTest\App_Data\TheList.mdb;Persist Security Info=True"/>
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
</system.web>
</configuration>
middle tier code to check if user is in the database if they are return something if not return null
OleDbConnection sconn = new OleDbConnection();
OleDbCommand scmd = new OleDbCommand();
public DBMiddleTier()
{
try
{
// set up the connection strings
sconn.ConnectionString = ConfigurationManager.ConnectionStrings["accessConnectionString"].ToString();
}
catch(Exception ex)
{
throw ex;
}
}//end of constructor
//class to check membership
public object checkMembership(string logid, string password)
{
try
{
sconn.Open();
//set propertiers of the command
scmd.Connection = sconn;
scmd.CommandType = CommandType.Text;
scmd.CommandText = "select * from SubDealers where LoginID = #InputUsername and Password = #InputPassword";
scmd.Parameters.Clear();
OleDbParameter checkUsername = scmd.Parameters.Add("#InputUsername", OleDbType.VarChar, 50);
checkUsername.Value = logid;
OleDbParameter checkPassword = scmd.Parameters.Add("#InputPassword", OleDbType.VarChar, 50);
checkPassword.Value = password;
object result = scmd.ExecuteScalar();
return result;
}
catch (OleDbException sqx)
{
throw sqx;
}
finally
{
sconn.Close();
}
}//end of method
my code behind page
try
{
object result = dm.checkMembership(txtLoginID.Text, txtPassword.Text);
if (result != null)
{
Response.Redirect("https://www.google.com/");
}
else
{
txtLoginID.Text = "";
txtPassword.Text = "";
Page.ClientScript.RegisterStartupScript(this.GetType(), "notAmember", "alert('Sorry wrong id or password');", true);
}
}
catch (Exception ex)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + ex.Message + "');", true);
}
have you tried this?
select * from [SubDealers] where [LoginID] = #InputUsername and [Password] = #InputPassword"

ConnectionStringSettings NullReference Error

I have the following settings in my web.config, as a child of the configuration element:
<connectionStrings>
<clear />
<add name="GingerlimeDB"
connectionString="Data Source=localhost;
Integrated Security=False;
Initial Catalog=dbname;
User Id=accountname;
Password=password;"
providerName="System.Data.SqlClient" />
</connectionStrings>
In the code behind where I wish to retrieve the connection string, I placed:
using System.Configuration
...
var connStringObject = ConfigurationManager.ConnectionStrings["GingerlimeDB"];
string connectionString = connStringObject.ConnectionString;
Console.WriteLine(connectionString);
I don't get to the console output, instead it shows:
Object reference not set to an instance of an object.
How do I get the Connection String out of the web config?
Assuming your web.config file looks like this:
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<clear />
<add name="GingerlimeDB"
connectionString="Data Source=localhost;
Integrated Security=False;
Initial Catalog=dbname;
User Id=accountname;
Password=password;"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
You should be able to access the connection string exactly like you showed in your code. I use something nearly identical:
using System.Configuration;
....
internal bool OpenDatabaseConnection()
{
try
{
string connectionString = ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;
dbConnection = new SqlCeConnection(connectionString);
dbConnection.Open();
return true;
}
catch (SqlCeException ex)
{
this.errorLogging = new ErrorLogging(ex.Message, ex.Source, ex.HelpLink, ex.GetType().ToString());
}
catch (InvalidOperationException ex)
{
this.errorLogging = new ErrorLogging(ex.Message, ex.Source, ex.HelpLink, ex.GetType().ToString());
}
catch (ArgumentException ex)
{
this.errorLogging = new ErrorLogging(ex.Message, ex.Source, ex.HelpLink, ex.GetType().ToString());
}
catch (ConfigurationErrorsException ex)
{
this.errorLogging = new ErrorLogging(ex.Message, ex.Source, ex.HelpLink, ex.GetType().ToString());
}
return false;
}
Which line is actually causing the NullReference exception? (object not set to an instance of an object)?

Resources