I want the session to be checked before sending a
user to the login - whereby each URL request results in checking whether
this is from a valid session - if not, send them to the login page,
else process as normal. If the user already has an active session, we
will not show them the login page but take them to a pre-defined main
page.
I searched on google related to it, and come to know that it will done by using #Before annotaion in controller but dont know about #Before working and how to use? I'm using play 1.2.5.
You can use the #Before this way:
#Before
static void addUser() {
User user = connected();
if(user != null) {
renderArgs.put("user", user);
}
}
static User connected() {
if(renderArgs.get("user") != null) {
return renderArgs.get("user", User.class);
}
// Find your user from session
String username = session.get("user");
if(username != null) {
return User.find("byUsername", username).first();
}
return null;
}
// ~~render your login if the user is not finded in session
public static void index() {
if(connected() != null) {
render();
}
login();
}
You can find this sample code in YOUR_PLAY_DIR/samples-and-tests/booking.
As #emt14 said, you can do this with the Play secure module more easily. Check out the forum apps samples in YOUR_PLAY_DIR/samples-and-tests/forum.
The Play secure module does exactly that out of the box. It is used by most applications and integrates with different plugins as well. Check out the documentation here.
If you still want to implement it yourself you can use the secure code as an example.
Otherwise #Before can be used on any of your controller static methods and has access to all the scope Objects, including session.
Related
I'm trying to do logging for different user roles (admin, developers, end users, etc.), and I want to show a different/filtered log for end-users. How can I achieve that?
How can I approach this problem?
You could probably tackle this problem with using something like a ThreadLocal variable in your logging filter. That is set by the code that does the authentication. And based on that do your different logging.
A simple example, in your filter class you could have something like this:
private static final ThreadLocal<String> ROLE = new ThreadLocal<>();
public void doTheFiltering() {
String role = ROLE.get();
if (role == null) {
// not authenticated...
} else if (role.equals("ADMIN") {
// filter based on admin privileges
} else ...
}
public static void setRole(String role) {
ROLE.set(role);
}
public static void clearRole() {
ROLE.remove();
}
And in your authentication code:
try {
String role = ... // find out role
MyFilter.setRole(role);
// continue with whatever you're doing
} finally {
// clean up the role on this thread.
// this is especially needed when you're using a thread pool that handles requests.
MyFilter.clearRole();
}
In my application, users can log in as users or admins.
Is it possible to implement this using events in Java EE 7?
Right now, my code looks like this:
a) ManagedBean for JSF-View
public String validateUsernamePassword() {
Admin admin = new Admin();
admin.setPassword(pwd);
admin.setUserName(userName);
adminLoginEvent.fire(admin);
return Pages.CONSOLE;
}
b) Service that listens for the event:
public void onAdminLogin(#Observes final Admin admin) {
List<Admin> foundAdmin = adminLoginDao.login(admin);
if (foundAdmin != null) {
HttpSession session = sessionController.getSession();
session.setAttribute("username", foundAdmin.get(0).getUserName());
consoleController.setAdmin(foundAdmin.get(0));
}
}
The problem, of course is, that in the managed bean I cant tell whether login was successful. I could fire another event in the onAdminLogin method but where should I listen for that?
Do I have to do this by having onAdminLogin return a boolean value which I then use in the validateUsernamePassword method?
I have been playing around with authentication. I want to be able to have some extra functions on certain pages available for those who log in. The problem is that if I don't use the #Security.Authenticated(Secured.class) annotation for the controller class I cannot get the username from the session so I cannot check if the user is logged in or not.
How should I go about this? Should I make sure all pages are authenticated and then have some sort of a guest login that automatically gets used for those other sessions or is there a way to check if the user is logged in even on a class without the #Security.Authenticated(Secured.class) annotation.
It would be great if someone could point me in the right direction, if there is a tutorial available that does this or just some guidance.
You should do two things:
Prevent unauthenticated users from viewing the functionality in your template:
#if(session().containsKey(Secured.SESSION_AUTH_KEY)) { /* Your comment form */ }
Prevent unauthenticated users from accessing your action:
#Security.Authenticated(Secured.class)
public static Result submitComment() {
...
}
With:
public class Secured extends Security.Authenticator {
public static final String SESSION_AUTH_KEY = "email";
public String getUsername(Http.Context context) {
return context.session().get(SESSION_AUTH_KEY);
}
public Result onUnauthorized(Http.Context context) {
...
}
}
I'm using Java Mail API:
PasswordAuthentication valid = new PasswordAuthentication(txtEmail.getText(),
txtPassword.getText());
if (valid != null) {
lblInvalid.setText("Correct information!");
} else {
lblInvalid.setText("Invalid username or password!");
}
What I want it to do, I want the user to login with their gmail username and password. I want to check if that email username and password is the real gmail login information. How do I check if the email and password enters is the users gmail account.
In Java, doing new Anything() will NEVER return null.
Also, this class seems to only be a placeholder data structure, used by other parts of the JDK. It does not intrinsically do validation.
Validating an email address is usually done with regex, and kept simple. You should then send the user a confirmation message to verify their email address if that's important to you.
Passwords can also be validated for correct form using regex.
Update
Looking more closely at the error messages you are trying to emit, it looks like you want to handle authentication yourself. There are tons of ways to do this but a very simple prototype-only solutions is something like:
// create a static mapping of user/passwords:
private static Map<String, String> logins = new HashMap<String, String>();
Then in your handler:
if (txtPassword.getText().equals(logins.get(txtEmail.getText()))) {
lblInvalid.setText("Correct information!");
} else {
lblInvalid.setText("Invalid username or password!");
}
For something you're going to use in production I'd highly recommend Spring Security.
To validate email address you can refer this link
http://www.mkyong.com/regular-expressions/how-to-validate-email-address-with-regular-expression/
For validating password: You just need to retrieve the stored password for a user from some database or other security frameworks and validate against the input done by the user.
This is a pretty large topic.
Authentication, Authorization and validation are three different things (but pretty much related).
If you are a beginner and you are just trying some mock authentication with hard-coded credentials you could improve a little on your code with something like this:
public class Authenticator {
public boolean authenticateWithCredentials(String email, String password) {
boolean areValidCredentials = false;
//Validate credentials here with database or hardcoded
if(email.equals("my_email#emailprovider.com") && password.equals("mypassword")) {
areValidCredentials = true;
}
return areValidCredentials;
}
}
if you are going to use just one instance of this class you might use the Singleton pattern:
public class Authenticator {
//Singleton pattern
private static Authenticator instance;
public static Authenticator getInstance() {
if(instance == null) {
instance = new Authenticator();
}
return instance;
}
private Authenticator() {
//Block creation of Authenticator instances
}
public boolean authenticateWithCredentials(String email, String password) {
boolean areValidCredentials = false;
//Validate credentials here with database or hardcoded
if(email.equals("my_email#emailprovider.com") && password.equals("mypassword")) {
areValidCredentials = true;
}
return areValidCredentials;
}
}
I am building a community website in grails (using Apache Shiro for security and authentication system) and I would like to implement the feature "who is online?".
This url http://cksource.com/forums/viewonline.php (see snapshot below if you do not have acess to this Url) gives an example of what I would like to achieve.
How can I do that in the most simple way? Is there any existing solution in Grails or in Java ?
Thank you.
Snapshot : Snapshot of Who is online page http://www.freeimagehosting.net/uploads/th.2de8468a86.png or see here : http://www.freeimagehosting.net/image.php?2de8468a86.png
You need to collect all logged in users in a Set<User> in the application scope. Just hook on login and logout and add and remove the User accordingly. Basically:
public void login(User user) {
// Do your business thing and then
logins.add(user);
}
public void logout(User user) {
// Do your business thing and then
logins.remove(user);
}
If you're storing the logged-in users in the session, then you'd like to add another hook on session destroy to issue a logout on any logged-in user. I am not sure about how Grails fits in the picture, but talking in Java Servlet API, you'd like to use HttpSessionListener#sessionDestroyed() for this.
public void sessionDestroyed(HttpSessionEvent event) {
User user = (User) event.getSession().getAttribute("user");
if (user != null) {
Set<User> logins = (Set<User>) event.getSession().getServletContext().getAttribute("logins");
logins.remove(user);
}
}
You can also just let the User model implement HttpSessionBindingListener. The implemented methods will be invoked automagically whenever the User instance is been put in session or removed from it (which would also happen on session destroy).
public class User implements HttpSessionBindingListener {
#Override
public void valueBound(HttpSessionBindingEvent event) {
Set<User> logins = (Set<User>) event.getSession().getServletContext().getAttribute("logins");
logins.add(this);
}
#Override
public void valueUnbound(HttpSessionBindingEvent event) {
Set<User> logins = (Set<User>) event.getSession().getServletContext().getAttribute("logins");
logins.remove(this);
}
// #Override equals() and hashCode() as well!
}
This has been discussed some time ago on the mailing list: http://grails.1312388.n4.nabble.com/Information-about-all-logged-in-users-with-Acegi-or-SpringSecurity-in-Grails-td1372911.html