Use API instead of sql query for authenticating users in openfire - openfire

Is it possible to use API instead of following sql query for user authentication in openfire properties:
jdbcAuthProvider.passwordSQL: SELECT username FROM
chat_authentication WHERE username=?
Basically, the chat_authentication table in our mysql database is not functioning properly and hence some users' entries are not there in the table. So I want to hit the API(which has very low failure rate) directly. How can I do that in this case?

You have to create your own class to substitute DefaultAuthProvider.class of Openfire.
Can looks like:
import org.jivesoftware.openfire.auth.AuthProvider
public class MyAuthProvider implements AuthProvider
and implements correctly all the methods.
As alternative you can extends OF's DefaultAuthProvider and override all the methods
public void authenticate(String username, String password) throws UnauthorizedException
public void authenticate(String username, String token, String digest) throws UnauthorizedException
getPassword(String)
public boolean checkPassword(String username, String testPassword) throws UserNotFoundException
public void setPassword(String username, String password).
Finally, make a jar of your class, deploy it in openfireDirectory/lib and change the value of property
provider.auth.className
with your MyAuthProvider fullname.
You can do it
by Admin Console Panel -> Server -> System Property
or by database updating OfProperty table.
After that, you'll must shut down and start Openfire.

Related

IHttpContextAccessor scope

I have IHttpContextAccessor injected in a controller. I am reading user name from IHttpContextAccessor and returning it back to the UI.
My question is is very basic. I need to understand how this will work when multiple users will connect and request User Name.
I just want to make sure that the user names will be returned only for the corresponding user.
I don't want to save the user name in session variable after returned to the client. Whenever is needed, I will request a call and get it from the context.
Is this approach valid?
private IHttpContextAccessor ctx
public EmployeeController(IHttpContextAccessor context)
{
ctx=context;
}
public string GetEmployeeName()
{
return ctx.HttpContext.User.UserName;
}
The HttpContextAccessor will be registered as the Singleton service when you
called AddHttpContextAccessor.
According to the source codes, you could find the HttpContextAccessor will check the _httpContextCurrent value when it call get and set method. It will auto set the _httpContextCurrent.Value when the new request come to the application.

Is there an automated mechanism where I can detect if any email field is missing?

Let's assume this class:
public class AccountInfo
{
public string Email;
public string Username;
public string Password;
}
and this ASP api:
[HttpPost, Route("create")]
public IActionResult CreateUser([FromBody]AccountInfo Info)
{
...
}
If a user passes something like this:
{
"eail" : "ndienw", <--- notice the mispelling
"username" : "djiw",
"password" : "dow"
}
The email field will be null, so I need in each call to check for every fields.
Is there an automated mechanism where I can detect if any field is missing? I'm looking for something generic that can be applied through all calls.
Being able to opt out and mark some parameters optional would be great, but in our case, everything is always needed so far.
In this scenario, the ModelState is still valid; is that the expected behavior?
You can use data annotations on your Email property. RegularExpression attribute will check the field that located on, whether the value which provided is matching with this pattern. Required attribute checks whether this field is empty or not.
[RegularExpression(#"\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = "Email was invalid.")]
[Required]
public string Email;

Get all roles for the current user

Once I have a principal logged in, how can I obtain all roles for a user?
I'm creating a Java EE 6 application, and I'm writing a JAX-RS service to return all the roles for the current user, which will be consumed by a front-end to properly render the screen.
I know that there are multiple interfaces that can return whether the user is a member of a certain role, but what I want is a interface that would allow me to get all roles for that particular user.
Given that all the role names are known at compile time, you can do something like the following :
public final class SecurityRoles {
static final String USER_ROLE = "user";
static final String ADMIN_ROLE = "admin";
static final String SUPPORT_ROLE = "support";
}
and
#DeclareRoles({
USER_ROLE,
ADMIN_ROLE,
SUPPORT_ROLE
})
#Path("/rest")
public class SomeRS {
#Context
SecurityContext securityContext;
#GET
#PermitAll
#Produces(MediaType.APPLICATION_JSON)
public List<String> lookupUserRoles() {
return Arrays.stream(SomeRS.class.getAnnotation(DeclareRoles.class).value())
.filter(roleName -> securityContext.isUserInRole(roleName))
.collect(Collectors.toList());
}
}
which tests to see if the user is in each of the known roles before adding the role name to a list that is returned.
Note that if you do not use #DeclareRoles then the roles used by the application must be declared in either the web.xml or application.xml files (and you will need to declare the names in a String[] array somewhere).

Getting 'Context is not constructible. Add a default constructor or provide an implementation of IDbContextFactory."

I am getting this error when I try to use code first migrations.
My context has a constructor with the connection name.
public class VeraContext : DbContext, IDbContext
{
public VeraContext(string NameOrConnectionStringName = "VeraDB")
: base(NameOrConnectionStringName)
{
}
public IDbSet<User> Users { get; set; }
public IDbSet<Product> Products { get; set; }
public IDbSet<IntCat> IntCats { get; set; }
}
This connection name is injected with ninject when the project runs, I have also specified it as a default as in the above code but this did not help.
kernel.Bind<IDbContext>()
.To<VeraContext>()
.WithConstructorArgument("NameOrConnectionStringName", "VeraDB");
When I try to add migrations with "Enable-Migrations" is throws up the error:
The target context 'VeraData.EF.Infrastructure.VeraContext' is not
constructible. Add a default constructor or provide an implementation
of IDbContextFactory.
If I remove the constructor from VeraContext it will work but creates another database with VeraData.EF.Infrastructure.VeraContext as its name.
I presume that ninject only passes the connection string when the project runs and not when I use code first migrations. Anyway I can inject/provide a default for the connection name when using code first migrations ?
Essentially you need a default ctor (that's the error) - but just implementing it would lead to problems.
You'd have to implement the IDbContextFactory for the results to be consistent (or your migration from code won't work etc.).
Migrations actually call your default constructor to make a
connection. So you're other ctor won't matter much.
Here is the basic factory...
public class MyContextFactory : IDbContextFactory<MyContext>
{
public MyContext Create()
{
return new MyDBContext("YourConnectionName");
}
}
You should combine that with injection, to inject and construct your DbContext as you wish.
If you don't want to spend time looking into the IDbContextFactory option, and to get things working create a default constructor and hard-code the name of the connection string when calling the base DbContext:
public class CustomContext : DbContext
{
public CustomContext() :base("name=Entities") {}
}
SRC: http://www.appetere.com/Blogs/SteveM/April-2012/Entity-Framework-Code-First-Migrations
To complement #nccsbim071 answer, I have to add one more thing... this option doesn't like constructor with default parameters... for instance:
public MyContext(bool paramABC = false) : base("name=Entities") {...}
instead you have to create a non-parameter (default) constructor and the parameter-constructor like old fashion way.
public MyContext() :base("name=Entities") {...}
public MyContext(bool paramABC) : this() {...}
NOTE:
Entities in this case means the connection string name... By convention, the name of the context is the same as the connection string name and since MyContext is not the same as Entities, it's necessary specify it manually.
In my situation I wanted to use the default connection factory, instead of explicitly providing one. Somewhere inside EF6 it'll try to lookup the factory, but it fails with this exception message. Stepping through the EF6 code, I found that Glimpse.Ado was wrapping the connection factory, which made the lookup fail to find a match.

Repositories and Services, MVC Model

So I've been learning about the Repository model, and it seems that it is expected that Repositories do not do a lot of intricate logic. However I also read that most of the business logic should not be inside of my Controllers. So where do I put it?
I've looked at some sample applications and it seems that they have another layer called Services that do more intricate logic for things. So how does this factor into the MVC pattern?
Do I want to build my services to access my repositories, and then my controllers to access my services? Like this?
interface IMembershipService
{
bool ValidateUser(string username, string password);
MembershipCreateStatus Create(string username, string password);
}
interface IMembershipRepository
{
MembershipCreateStatus Create(string username, string password);
}
class MembershipRepository : IMembershipRepository
{
public MembershipRepository(ISession session)
{
**// this is where I am confused...**
}
}
class MembershipService : IMembershipService
{
private readonly IMembershipRepository membershipRepository;
public MembershipService(IMembershipRepository membershipRepository)
{
this.membershipRepository = membershipRepository;
}
public bool ValidateUser(string username, string password)
{
// validation logic
}
public MembershipCreateStatus Create(string username, string password)
{
return membershipRepository.Create(username, password);
}
}
class MembershipController : Controller
{
private readonly IMembershipService membershipService;
public MembershipController(IMembershipService membershipService)
{
this.membershipService = membershipService
}
}
The marked part of my code is what confuses me. Everything I have read said I should be injecting my ISession into my repositories. This means I could not be injecting ISession into my services, so then how do I do Database access from my Services? I'm not understanding what the appropriate process is here.
When I put ValidateUser in my IMembershipRepository, I was told that was 'bad'. But the IMembershipRepository is where the database access resides. That's the intention, right? To keep the database access very minimal? But if I can't put other logic in them, then what is the point?
Can someone shed some light on this, and show me an example that might be more viable?
I am using Fluent nHibernate, ASP.NET MVC 3.0, and Castle.Windsor.
Should I instead do something like ...
class MembershipService
{
private readonly IMembershipRepository membershipRepository;
public MembershipService(ISession session)
{
membershipRepository = new MembershipRepository(session);
}
}
And never give my Controllers direct access to the Repositories?
Everything I have read said I should be injecting my ISession into my repositories.
That's correct. You need to inject the session into the repository constructor because this is where the data access is made.
This means I could not be injecting ISession into my services, so then how do I do Database access from my Services?
You don't do database access in your services. The service relies on one or more repositories injected into its constructor and uses their respective methods. The service never directly queries the database.
So to recap:
The repository contains the simple CRUD operations on your model. This is where the data access is performed. This data access doesn't necessary mean database. It will depend on the underlying storage you are using. For example you could be calling some remote services on the cloud to perform the data access.
The service relies on one or more repositories to implement a business operation. This business operation might depend on one or more CRUD operations on the repositories. A service shouldn't even know about the existence of a database.
The controller uses the service to invoke the business operation.
In order to decrease the coupling between the different layers, interfaces are used to abstract the operations.
interface IMembershipService
{
bool ValidateUser(string username, string password);
MembershipCreateStatus Create(string username, string password);
}
Creating a service like this an anti-pattern.
How many responsibilities does a service like this have? How many reasons could it have to change?
Also, if you put your logic into services, you are going to end up with an anemic domain. What you will end up with is procedural code in a Transaction Script style. And I am not saying this is necessarily bad.
Perhaps a rich domain model is not appropriate for you, but it should be a conscious decision between the two, and this multiple responsibility service is not appropriate in either case.
This should be a HUGE red flag:
public MembershipCreateStatus Create(string username, string password)
{
return membershipRepository.Create(username, password);
}
What is the point? Layers for the sake of layers? The Service adds no value here, serves no purpose.
There are a lot of concepts missing.
First, consider using a Factory for creating objects:
public interface IMembershipFactory {
MembershipCreateStatus Create(string username, string password);
}
The factory can encapsulate any logic that goes into building an instance or beginning the lifetime of an entity object.
Second, Repositories are an abstraction of a collection of objects. Once you've used a factory to create an object, add it to the collection of objects.
var result = _membershipFactory.Create("user", "pw");
if (result.Failed); // do stuff
_membershipRepository.Add(status.NewMembership); // assumes your status includes the newly created object
Lastly, MyEntityService class that contains a method for every operation that can be performed on an Entity just seems terribly offensive to my senses.
Instead, I try to be more explicit and better capture intent by modeling each operation not as a method on a single Service class, but as individual Command classes.
public class ChangePasswordCommand {
public Guid MembershipId { get; set; }
public string CurrentPassword { get; set; }
public string NewPassword { get; set; }
}
Then, something has to actually do something when this command is sent, so we use handlers:
public interface IHandle<TMessageType> {
void Execute(TMessageType message);
}
public class ChangePasswordCommandHandler : IHandle<ChangePasswordCommand> {
public ChangePasswordCommandHandler(
IMembershipRepository repo
)
{}
public void Execute(ChangePasswordCommand command) {
var membership = repo.Get(command.MembershipId);
membership.ChangePassword(command.NewPassword);
}
}
Commands are dispatched using a simple class that interfaces with our IoC container.
This helps avoids monolithic service classes and makes a project's structure and location of logic much clearer.