Error in my simple struts application - struts

Error: inconvertible types
my loginAction file's code:
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception
{
LoginForm loginForm = (LoginForm) form;
if (loginForm.getUserName().equals(loginForm.getPassword()))
{
return mapping.findForward(SUCCESS);
}
else
{
return mapping.findForward(FAILURE);
}
}
my struts-config file's code:
<action-mappings>
<action input="/login.jsp" name="LoginForm" path="/Login" scope="session" type="com.strutsmyaction.LoginAction">
<forward name="success" path="/success.jsp" />
<forward name="failure" path="/failure.jsp" />
</action>
</action-mappings>
my loginform file's code
public class LoginForm
{ String userName; String password;
public String getUserName() {
System.out.println("Inside getter "+userName);
return userName;
}
public void setUserName(String userName) {
System.out.println("Inside setter "+userName);
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

I think This will work ..
if (loginForm.getUserName().equals(loginForm.getPassword()))
{
return mapping.findForward("success");
}
else
{
return mapping.findForward("failure");
}

Related

Configure PrimeFaces with IntelliJ IDEA

So this is my first time building an Java EE application. I watched a lot of tutorials but most of them are using eclipse.
So the problem is this:
<h:panelGroup layout="block">
<p:commandButton ajax="false" action="#{loginBean.login()}"
styleClass="btn btn-info" value="Login" />
</h:panelGroup>
When I start Wildfly server and try to access the login page. If there are no
brackets after the login method I get:
The class 'LoginBean' does not have the property login.
If I try it with the brackets. The method is invoked when page is initialized and I get exception that the values for username and pass are null.
When I commented the method content I got the page to initialize properly, but another issue occured.
The JSF components like:
<h:panelGroup>
<h3 class="loginTitle">#{msgs['default.title']}</h3>
</h:panelGroup>
Are rendered correctly, but the Primefaces components
<h:panelGroup layout="block">
<p:inputText value="#{loginBean.username}" id="username"
styleClass="loginInputField" required="true"
requiredMessage="Username is required field">
<p:watermark for="username" value="Username" />
</p:inputText>
</h:panelGroup>
Are rendered with 0px height and width.
Here is my LoginBean.java
public class LoginBean implements Serializable {
private static final String SUCCESS_LOGIN_REDIRECT = "/pages/success?faces-redirect=true";
private static final String LOGIN_PAGE_REDIRECT = "/pages/login?faces-redirect=true";
private static final long serialVersionUID = 1L;
#Inject
private HttpServletRequest request;
private String username;
private String password;
#PostConstruct
public void init() {
//TODO
}
public String login() {
username = "";
password = "";
if(StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Invalid Credentials"));
return "";
} else if ("admin".equals(username) && "123".equals(password)) {
request.getSession().setAttribute("LOGGED_USER", username);
return SUCCESS_LOGIN_REDIRECT;
}
MessageUtils.addErrorMessage("login.error.invalid.credentials");
return "";
}
public String logout() {
request.getSession().invalidate();
return LOGIN_PAGE_REDIRECT;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
And last here is my project structure https://github.com/M-Veselinov/Java-EE
I think that I'm doing something wrong with web.xml or other config files, but I have no idea what.
I'll appreciate some help. Thanks.
Client Source:
<p:inputtext id="username" styleclass="loginInputField" required="true" requiredmessage="Username is required field">
<p:watermark for="username" value="Username"></p:watermark>
</p:inputtext>

How to merge records together

i am able to update the database so for each section a user saves it saves there work fine, in the correct column of the database, but what i am now trying to achieve is instead of saving into a new row, check there studentNumber and if it already has a record in the table (which it will have to to get this far ) update the columns to that record rather than starting a new one
how can i do that ?
currently this is my code :
this is the u.i. where they select the value and press submit
<p:spinner id="ajaxspinner80-100" value="#{editMarkingBean.markSectionTwo.markSectionTwo}"
stepFactor="1" min="80" max="100" disabled="#{formBean.number != 8}">
<p:ajax update="ajaxspinnervalue" process="#this" />
</p:spinner>
the save button
<p:commandButton action="#{editMarkingBean.markSectionTwo}" value="#{bundle.buttonSave}" update=":growl" icon="ui-icon-disk"/>
the backing bean is :
#Named(value = "editMarkingBean")
#ViewScoped
public class EditMarkingController {
private String searchString;
private String ordering;
private String criteria;
private String match;
private Date today;
private String caseMatch;
private int spinnerField;
private Marking markSectionOne;
private Marking studentNumber;
private Marking markSectionTwo;
private MarkingService markingService;
private Marking markToEdit;
#Inject
private MarkingFacade markingFacade;
#PostConstruct
public void init() {
//this.markToEdit = this.markingFacade.find(studentNumber);
this.markSectionTwo = new Marking();
}
public String markSectionTwo() {
this.markingFacade.edit(markSectionTwo);
this.setMessage("Mark Saved");
markSectionTwo = new Marking();
this.setMessage("Mark Saved");
// now navigating to the next page
return "/lecturer/marking/marking-section-three";
}
private void setMessage(String message) {
FacesContext fc = FacesContext.getCurrentInstance();
fc.addMessage(null, new FacesMessage(message, ""));
}
public Marking getMarkSectionTwo() {
return markSectionTwo;
}
public void setMarkSectionTwo(Marking markSectionTwo) {
this.markSectionTwo = markSectionTwo;
}
public String getSearchString() {
return searchString;
}
public void setSearchString(String searchString) {
this.searchString = searchString;
}
public String getOrdering() {
return ordering;
}
public void setOrdering(String ordering) {
this.ordering = ordering;
}
public String getCriteria() {
return criteria;
}
public void setCriteria(String criteria) {
this.criteria = criteria;
}
public String getMatch() {
return match;
}
public void setMatch(String match) {
this.match = match;
}
public Date getToday() {
return today;
}
public void setToday(Date today) {
this.today = today;
}
public String getCaseMatch() {
return caseMatch;
}
public void setCaseMatch(String caseMatch) {
this.caseMatch = caseMatch;
}
public int getSpinnerField() {
return spinnerField;
}
public void setSpinnerField(int spinnerField) {
this.spinnerField = spinnerField;
}
public Marking getMarkSectionOne() {
return markSectionOne;
}
public void setMarkSectionOne(Marking markSectionOne) {
this.markSectionOne = markSectionOne;
}
public Marking getStudentNumber() {
return studentNumber;
}
public void setStudentNumber(Marking studentNumber) {
this.studentNumber = studentNumber;
}
public MarkingService getMarkingService() {
return markingService;
}
public void setMarkingService(MarkingService markingService) {
this.markingService = markingService;
}
public MarkingFacade getMarkingFacade() {
return markingFacade;
}
public void setMarkingFacade(MarkingFacade markingFacade) {
this.markingFacade = markingFacade;
}
}
but currently only adds a new row with the data to the database rather than trying to merge it with the data already contained in the database for a student with a certain student number
how can i achieve this ? thanks guys for your help :)
EDIT :
I have tried :
private Marking markToEdit;
#Inject
private MarkingFacade markingFacade;
#PostConstruct
public void init() {
this.markToEdit = this.markingFacade.find(studentNumber);
//this.markSectionTwo = new Marking();
}
public String markSectionTwo() {
this.markingFacade.edit(markSectionTwo);
this.setMessage("Mark Saved");
// markSectionTwo = new Marking();
//this.setMessage("Mark Saved");
// now navigating to the next page
return "/lecturer/marking/marking-section-three";
}
but get the error :
exception
javax.servlet.ServletException: WELD-000049 Unable to invoke public void sws.control.EditMarkingController.init() on sws.control.EditMarkingController#4109691f
root cause
org.jboss.weld.exceptions.WeldException: WELD-000049 Unable to invoke public void sws.control.EditMarkingController.init() on sws.control.EditMarkingController#4109691f
root cause
java.lang.reflect.InvocationTargetException
root cause
javax.ejb.EJBException
root cause
java.lang.IllegalArgumentException: An instance of a null PK has been incorrectly provided for this find operation.
I use a quite similar approach as yours, but with different names. I'll post it here, so I think you can have some idea.
My way is to check the entity explicitly before merging it.
My JSF CRUD looks like this
xhtml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>DataSource Manager</title>
</h:head>
<h:body>
<h:form id="ds">
<p:spacer height="10" />
<p:fieldset legend="Insert/Edit Data Source">
<p:panel id="insertUpdateForm">
<h:panelGrid columns="2">
<p:outputLabel for="name" value="Data Source Name:" style="width:100px;"/>
<p:inputText id="name" value="#{dataSourceMB.dataSource.name}"/>
<p:outputLabel for="user" value="User:" style="width:100px;"/>
<p:inputText id="user" value="#{dataSourceMB.dataSource.user}"/>
<p:outputLabel for="driver" value="Driver:" style="width:100px;"/>
<p:inputText id="driver" value="#{dataSourceMB.dataSource.driver}" />
</h:panelGrid>
</p:panel>
<p:panel>
<p:commandButton value="Save" action="#{dataSourceMB.saveDataSource}" update="dsList,insertUpdateForm" />
<p:commandButton value="Clear" action="#{dataSourceMB.clearDataSource}" update="insertUpdateForm" />
<p:commandButton value="Test Connection" action="#{dataSourceMB.testConnection}"/>
</p:panel>
</p:fieldset>
<p:spacer height="10" />
<p:fieldset legend="Data Sources">
<p:panel>
<p:dataTable
var="ds"
value="#{dataSourceMB.listDataSources}"
paginator="true" rows="10"
paginatorTemplate="{RowsPerPageDropdown} {FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink} {LastPageLink}"
rowsPerPageTemplate="10,50,100"
id="dsList">
<p:column headerText="ID">
<h:outputText value="#{ds.id}" />
</p:column>
<p:column headerText="Name">
<h:outputText value="#{ds.name}" />
</p:column>
<p:column headerText="JDBC">
<h:outputText value="#{ds.jdbc} " />
</p:column>
<!-- check http://jqueryui.com/themeroller/ for icons -->
<p:column headerText="" style="width:2%">
<p:commandButton icon="ui-icon-pencil" action="#{dataSourceMB.editDataSource}" title="Edit" update=":ds:insertUpdateForm">
<f:setPropertyActionListener value="#{ds}" target="#{dataSourceMB.selectedDataSource}" />
</p:commandButton>
</p:column>
<p:column headerText="" style="width:2%">
<p:commandButton icon="ui-icon-trash" action="#{dataSourceMB.removeDataSource}" title="Remove" update=":ds:insertUpdateForm,dsList">
<f:setPropertyActionListener value="#{ds}" target="#{dataSourceMB.selectedDataSource}" />
</p:commandButton>
</p:column>
</p:dataTable>
</p:panel>
</p:fieldset>
</h:form>
</h:body>
</html>
my managed bean
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import org.apache.log4j.Logger;
import DataSourceEJB;
import JSFUtilEJB;
import DataSource;
#ManagedBean
#ViewScoped
public class DataSourceMB implements Serializable {
private static final long serialVersionUID = 871363306742707990L;
private static Logger log = Logger.getLogger(DataSourceMB.class);
#EJB
private JSFUtilEJB jsfUtilEJB;
#EJB
private DataSourceEJB dataSourceEJB;
private DataSource dataSource;
private DataSource selectedDataSource;
private List<DataSource> listDataSources;
#PostConstruct
public void init() {
try {
this.dataSource = new DataSource();
this.listDataSources = this.dataSourceEJB.listDataSources();
} catch (Exception e) {
jsfUtilEJB.addErrorMessage(e,"Could not list");
}
}
public void removeDataSource(){
try {
this.dataSourceEJB.removeDataSource(this.selectedDataSource);
jsfUtilEJB.addInfoMessage("Removed "+this.selectedDataSource.getName());
if (this.dataSource != null && this.dataSource.getId() != null && this.dataSource.getId().equals(this.selectedDataSource.getId())){
this.dataSource = null;
}
this.listDataSources = this.dataSourceEJB.listDataSources();
} catch (Exception e) {
jsfUtilEJB.addErrorMessage(e,"Could not remove");
}
}
public void saveDataSource(){
try {
this.dataSourceEJB.saveDataSource(this.dataSource);
jsfUtilEJB.addInfoMessage("Saved "+this.dataSource.getName());
this.dataSource = new DataSource();
this.listDataSources = this.dataSourceEJB.listDataSources();
} catch (Exception e) {
jsfUtilEJB.addErrorMessage(e,"Could not save");
}
}
public void editDataSource(){
this.dataSource = this.selectedDataSource;
}
public void clearDataSource(){
this.dataSource = new DataSource();
}
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public DataSource getSelectedDataSource() {
return selectedDataSource;
}
public void setSelectedDataSource(DataSource selectedDataSource) {
this.selectedDataSource = selectedDataSource;
}
public List<DataSource> getListDataSources() {
return listDataSources;
}
public void setListDataSources(List<DataSource> listDataSources) {
this.listDataSources = listDataSources;
}
}
my EJB
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import javax.ejb.Stateless;
import javax.inject.Inject;
import DataSource;
#Stateless
public class DataSourceEJB {
#Inject
private BaseService baseService;
public List<DataSource> listDataSources() {
return this.baseService.getDataSourceDAO().getAll();
}
public void removeDataSource(DataSource ds) throws Exception {
DataSource a = this.baseService.getDataSourceDAO().find(ds.getId());
this.baseService.getDataSourceDAO().delete(a);
}
public void saveDataSource(DataSource ds) throws Exception {
DataSource a = this.baseService.getDataSourceDAO().find(ds.getId());
if (a == null){
this.baseService.getDataSourceDAO().add(ds);
}else{
this.baseService.getDataSourceDAO().edit(ds);
}
}
public DataSource getById(long id) {
return this.baseService.getDataSourceDAO().find(id);
}
public DataSource getByName(String name) {
return this.baseService.getDataSourceDAO().findByName(name);
}
}
DAO
public E find(Long id) {
return (E)entityManager.find(clazz, id);
}
public void add(E entity) throws Exception {
entityManager.persist(entity);
}
public E edit(E entity) throws Exception {
return entityManager.merge(entity);
}
public void delete(E entity) throws Exception {
entityManager.remove(entity);
}

Class serialization and namespace (xmlns)

I have a class that I am serializing
public partial class Security : MessageHeader
{
private Assertion assertionField;
[System.Xml.Serialization.XmlElementAttribute(Namespace = "urn:oasis:names:tc:SAML:2.0:assertion")]
public Assertion Assertion
{
get
{
return this.assertionField;
}
set
{
this.assertionField = value;
}
}
public override string Name
{
get { return "Security"; }
}
public override string Namespace
{
get { return "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"; }
}
[XmlIgnoreAttribute]
public string UserID { get; set; }
[XmlIgnoreAttribute]
public string FirstName { get; set; }
[XmlIgnoreAttribute]
public string LastName { get; set; }
[XmlIgnoreAttribute]
public string ReasonForSearch { get; set; }
public Security()
{
Assertion = new Assertion(UserID, FirstName, LastName, ReasonForSearch);
}
protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("saml", "urn:oasis:names:tc:SAML:2.0:assertion");
XmlSerializer serializer = new XmlSerializer(typeof(Assertion));
serializer.Serialize(writer, Assertion, ns);
}
}
this is how i am adding code header
using (OperationContextScope scope = new OperationContextScope(healthixClient.InnerChannel))
{
Security msgHdr = new Security();
msgHdr.UserID = "TestUserID";
msgHdr.FirstName = "TestUserFirstName";
msgHdr.LastName = "TestUserLastName";
msgHdr.ReasonForSearch = "ReasonForSearch";
OperationContext.Current.OutgoingMessageHeaders.Add(msgHdr);
}
when i serialize this and add in my code header it looks like this
<Security xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<saml:Assertion ID="saml_6691a2b1-2a08-4d10-9d90-b006727d0e02" IssueInstant="2013-09-09T15:38:16Z" Version="2.0" xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">
< rest of the Xml is correct >
Now if I only change my override OnWriteHeaderContents method to
protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("saml", "urn:oasis:names:tc:SAML:2.0:assertion");
XmlSerializer serializer = new XmlSerializer(typeof(Security));
serializer.Serialize(writer, new Security(), ns);
}
the header looks like this
<Security xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<Security xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">
<saml:Assertion ID="saml_6691a2b1-2a08-4d10-9d90-b006727d0e02" IssueInstant="2013-09-09T15:29:09Z" Version="2.0">
< rest of the Xml is correct >
What i want the header to look like is this
<Security xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">
<saml:Assertion ID="saml_6691a2b1-2a08-4d10-9d90-b006727d0e02" IssueInstant="2013-07-29T20:17:30.846Z" Version="2.0" xmlns="urn:oasis:names:tc:SAML:2.0:assertion">
Try this option in OnWriteHeaderContents method
writer.WriteStartElement("saml", "Assertion", "urn:oasis:names:tc:SAML:2.0:assertion");
writer.WriteString("Value");
writer.WriteEndElement();

Override the User.IsInRole and [Authorize(Roles = "Admin")] for MVC4 application

I have created a custom role provider for my MVC4 application where I have been successfully able to override CreateRole, GetAllRoles and RoleExists methods and link them to my existing database as follows:
namespace Project.Providers
{
public class MyProvider : System.Web.Security.SqlRoleProvider
{
private MyContext dbcontext = new MyContext(System.Configuration.ConfigurationManager.ConnectionStrings["MyContext"].ConnectionString);
private Repository<MyUser> userRepository;
private Repository<Role> roleRepository;
public MyProvider()
{
this.userRepository = new Repository<MyUser>(dbcontext);
this.roleRepository = new Repository<Role>(dbcontext);
}
public override string[] GetAllRoles()
{
IEnumerable<Role> dbRoles = roleRepository.GetAll();
int dbRolesCount = roleRepository.GetAll().Count();
string[] roles = new string[dbRolesCount];
int i = 0;
foreach(var role in dbRoles)
{
roles[i] = role.Name;
i++;
}
return roles;
}
public override bool RoleExists(string roleName)
{
string[] roles = { "Admin", "User", "Business" };
if(roles.Contains(roleName))
return true;
else
return false;
}
public override void CreateRole(string roleName)
{
Role newRole = new Role();
newRole.Name = roleName;
roleRepository.Add(newRole);
roleRepository.SaveChanges();
}
public override bool IsUserInRole(string userName, string roleName)
{
MyUser user = userRepository.Get(u => u.Username == userName).FirstOrDefault();
Role role = roleRepository.Get(r => r.Name == roleName).FirstOrDefault();
if (user.RoleID == role.RoleID)
return true;
else
return false;
}
}
}
I have been unable to find a way to override the
User.IsInRole(string roleName)
What else must I do so that When I use:
[Authorize(Roles = "Admin")]
It will be based on the role provider that I have set up and not the asp default.
My user class is now as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.Collections;
using System.Security.Principal;
namespace Project.Data
{
public class MyUser : IPrincipal
{
[Key]
public int UserID { get; set; }
[StringLength(128)]
public string Username { get; set; }
.....other properties
public IIdentity Identity { get; set; }
public bool IsInRole(string role)
{
if (this.Role.Name == role)
{
return true;
}
return false;
}
public IIdentity Identity
{
get { throw new NotImplementedException(); }
}
}
}
My stack trace seems to be following over at:
System.Web.Security.RolePrincipal.IsInRole(String role)
So I have tried to implement a custom RolePrincipal in the same manner I set the custom Provider any ideas how I can do this? Not sure what constructor params it takes. Here is my attempt:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration.Provider;
using Project.Data;
using System.Web.Security;
using System.Security.Principal.IIdentity;
namespace Project.Principal
{
public class MyPrincipal : System.Web.Security.RolePrincipal
{
private MyContext dbcontext = new MyContext(System.Configuration.ConfigurationManager.ConnectionStrings["MyContext"].ConnectionString);
private Repository<MyUser> userRepository;
private Repository<Role> roleRepository;
public MyPrincipal()
{
this.userRepository = new Repository<MyUser>(dbcontext);
this.roleRepository = new Repository<Role>(dbcontext);
}
public override bool IsInRole(string role)
{
//code to be added
return true;
}
}
}
You just need to override method GetRolesForUser in your custom role provider, instead of the more logical IsUserInRole, because that is what is called by the default implementation that does some unwanted caching.
You override IsInRole in your IPrincipal class, mine in EF looks like this:
public class MyUser : IPrincipal {
//Properties
...
public bool IsInRole(string role) {
if (Roles.Any(m=>m.NameKey.ToLower().Equals(role.ToLower()))) {
return true;
}
return false;
}
}
Then once you add the appropriate sections to your webconfig for both RoleProvider and MembershipProvider you should be good for Authorize attribute.
UPDATE in response to your comments
web Config should look like:
...
<authentication mode="Forms">
<forms loginUrl="~/Login" timeout="2880"></forms>
</authentication>
<authorization>
</authorization>
..
<membership defaultProvider="MyMembershipProvider">
<providers>
<add name="MyMembershipProvider" type="MyApp.Infrastructure.MyMembershipProvider" connectionStringName="connectionstring" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="true" />
</providers>
</membership>
<roleManager defaultProvider="MyRoleProvider" enabled="true" cacheRolesInCookie="true">
<providers>
<clear />
<add name="MyRoleProvider" type="MyApp.Infrastructure.MyRoleProvider" />
</providers>
</roleManager>
...
In the provider, is the User your IPrincipal?
public MyUser User { get; private set; }
User should have and IIdentity
in MyUser.cs:
...
public virtual ICollection<Role> Roles { get; set; }
public IIdentity Identity { get; set; }
I don't have much additional advice to help troubleshoot from your comments.
UPDATE
Some examples I have been through and found helpful when setting mine up:
http://www.brianlegg.com/post/2011/05/09/Implementing-your-own-RoleProvider-and-MembershipProvider-in-MVC-3.aspx
http://www.mattwrock.com/post/2009/10/14/Implementing-custom-MembershipProvider-and-Role-Provider-for-Authinticating-ASPNET-MVC-Applications.aspx
http://blogs.msdn.com/b/rickandy/archive/2012/03/23/securing-your-asp-net-mvc-4-app-and-the-new-allowanonymous-attribute.aspx?Redirected=true
I read many other articles and SO posts on my first run through, but these were things I bothered to bookmark. I took a roles/rights approach to authorization, which is why one of them is geared that way.
To fix this, you need to do 4 updates to your application.
1. Create a class that extends RoleProvider.
namespace MyApp
{
public class MyRoleProvider : RoleProvider
{
public override string ApplicationName
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public override void AddUsersToRoles(string[] usernames, string[] roleNames)
{
throw new NotImplementedException();
}
public override void CreateRole(string roleName)
{
throw new NotImplementedException();
}
public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
{
throw new NotImplementedException();
}
public override string[] FindUsersInRole(string roleName, string usernameToMatch)
{
throw new NotImplementedException();
}
public override string[] GetAllRoles()
{
throw new NotImplementedException();
}
public override string[] GetRolesForUser(string username)
{
using (ApplicationDbContext db = new ApplicationDbContext())
{
// get user roles here using user name.
}
}
public override string[] GetUsersInRole(string roleName)
{
throw new NotImplementedException();
}
public override bool IsUserInRole(string username, string roleName)
{
return GetRolesForUser(username).Contains(roleName);
}
public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
{
throw new NotImplementedException();
}
public override bool RoleExists(string roleName)
{
throw new NotImplementedException();
}
}
}
2. Create a custom filter that extends AuthorizeAttribute and overwrite its methods.
public class MyAuthFilter : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
var routeValues = new RouteValueDictionary(new
{
controller = "Account",
action = "Login",
});
filterContext.Result = new RedirectToRouteResult(routeValues);
base.HandleUnauthorizedRequest(filterContext);
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
string[] roles = Roles.Split(',');
string userName = HttpContext.Current.User.Identity.Name;
MyRoleProvider myProvider = new MyRoleProvider();
foreach (string role in roles)
{
bool success = myProvider.IsUserInRole(userName, role);
if (success == true)
{
return true;
}
}
return false;
}
3. Configure your custom role provider in your web.config.
<system.web>
<roleManager defaultProvider="MyRoleProvider" enabled="true" cacheRolesInCookie="true">
<providers>
<clear />
<add name="MyRoleProvider" type="MyApp.MyRoleProvider" />
</providers>
</roleManager>
</system.web>
Note: The type here uses the fully qualified namespace and your class name = MyApp.MyRoleProvider. Yours can be different
4. Use your custom filter instead of the default Authorize attribute for your controllers and actions. E.g
[MyAuthFilter]
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Title = "Home Page";
return View();
}
}

Can't get Form Validation working

I was learning Struts 1.1 and trying to do some form validation with my code.
But the errors that I had described in the MessageResources.properties file do not get displayed on the JSP. I tried a lot of options but couldn't get it off the ground. I have attached some of the code.
MessageResources.properties
error.name.required = Please mention your name.
error.email.incorrect = You E-Mail ID is Incorrect.
error.phone.numericError = Phone number should consist only of digits.
error.phone.lengthIncorrect = Phone number should be only of 10 digits.
struts-config.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
<struts-config>
<form-beans>
<form-bean name="detailsForm" type="com.example.form.DetailsForm"/>
</form-beans>
<action-mappings>
<action input="/detailsEntry.jsp" name="detailsForm" path="/DetailsForm" type="com.example.action.DetailsAction" validate="true">
<forward name="success" path="/displayDetails.jsp"/>
<forward name="failure" path="/failure.jsp"/>
</action>
</action-mappings>
</struts-config>
Form Class:
package com.example.form;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
public class DetailsForm extends ActionForm {
private String name;
private String email;
private String phone;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
#Override
public void reset(ActionMapping mapping, HttpServletRequest request) {
this.name = null;
this.email = null;
this.phone = null;
}
#Override
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
ActionErrors actionErrors = new ActionErrors();
if (this.name.equals(null) || this.name.length() == 0) {
actionErrors.add("name", new ActionError("error.name.required"));
}
return actionErrors;
}
private boolean isNumeric(String phoneNumber) {
try {
Integer.parseInt(phoneNumber);
return true;
}
catch (NumberFormatException numberFormatException) {
return false;
}
}
}
The default resource filename is ApplicationResources.properties.
Using a different (or multiple) resource files requires configuration in struts-config.xml:
<message-resource parameter="MessageResources" null="false" />
Don't forget to add the following to your jsp:
<html:errors />
Your error messages will appear where ever you put this tag on on your jsp.
And if you want your error message to be displayed next to the field they relates to then use the following:
<html:errors property="custName" />
where "custName" is the name you gave the error message when you created it in your form ex:
ActionMessages errors = new ActionMessages();
errors.add("custName", new ActionMessage("custName.invalid"));
request.setAttribute(Globals.ERROR_KEY, errors);