JSP/Tomcat secure login with sessionstorage - spring

I have a system running on Tomcat, with HTML/JSP in front-end, and java/Spring/Struts in backend.
I made a login-feature where the user enters his username and password.
In backend, I validate the username and password to the stored user in DB.
If match, I store the username in HTTPsession:
session.setAttribute( "username", name );
Then, on every class-action in backend, I add the following code:
HttpSession session = request.getSession();
if(session.getAttribute("username") == null) {
return mapping.findForward("invalidUser");
}
the invalidUSer-mapping redirects the user back to the login-page.
How secure is this?
Is there a way to check the httpsession without adding my validation-code to every class?
Do you guys have tips (or examples/tutorials) on how to do this differently? The system is already created and in production, so I do not want to do too many architecural changes.

As you are already using Spring in your project, you may want to look into Spring Security to replace your bespoke security mechanisms. You can configure it to protect certain resources within your application, authenticate against bespoke database back-ends, LDAP directories, etc. This will allow you to remove all manual checking of the session to see if the user is authenticated, and will redirect anonymous users to the specified login page when they attempt to access protected resources.
Along with the spring security filter definition in web.xml, the configuration can be specified in a single spring-security.xml file (imported into your root app config) using the security:http namespace to define the login page, protected resources, logout page, security headers etc. You could use a org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl instance configured as a bean to define the user service which can be referenced by the authentication-provider - see the docs, its very flexible.
Hope that's useful.

Related

Spring security - Is username and password must for creating authentication

I am using spring security to authenticate a user. The user is authenticated by a third party and will already be authenticated when he reaches my application.
To implemented this, I have simulated a Authentication object.
I don't have any username and password and instead just have identifier. I check if this identifier is valid or not using my custom code.
My query is as follows:
Do I require a username and password to create a authentication object.
I have done without providing username and password and my application works fine.
I just want to ensure that I am using spring-security correctly.
Is there any impact of not putting username and password in Authentication object. I read below in AbstractUserDetailsAuthenticationProvider:
// Ensure we return the original credentials the user supplied,
// so subsequent attempts are successful even with encoded passwords.
I have also implemented a custom provider.
What does above comments means?
Is my approach correct?
The Authentication interface in Spring Security represents a token for carrying out validations against the configured security rules and the current call context. This interface has six methods of interest - getPrincipal, getCredentials, getDetails, getAuthorities, isAuthenticated and setAuthenticated.
Since you are authenticating users on your own, you should be mostly concerned with calling setAuthenticated(true) at an appropriate stage in the flow so that isAuthenticated starts returning true to indicate an authenticated user. Additionally, you may add GrantedAuthoritys to the Authentication for any role-based checks to work correctly.
However, it will be useful to make sure that getPrincipal (username in the case of form login) returns a unique value per user or per session. This will prevent the possibility of user sessions getting interchanged due to non-unique principal, which is used by the framework to identify users uniquely.
You may leave getCredentials and getDetails unimplemented. In fact, getCredentials (password in the case of form login) should be left unimplemented in your case because your application does not have the credentials used to actually authenticate the user; plus, it is a security risk to keep the credentials around after the user has been authenticated successfully.

How to bypass the login form page in spring security?

I am using a custom UsernamePasswordAuthenticationFilter (which is called before the login page). I am considering the session id of the already logged in user in this filter. If the auth_token exists for the corresponding session id I want to bypass the login page.
How can I do that ?.
You just have to populate the security context with an authenticated Authencation once you have checked the auth_token. Something like that (in your custom filter):
... // first check the existence of the auth_token and extract some information from it like user name and roles
String login = ...
String role = ...
PreAuthenticatedAuthenticationToken preAuthenticatedAuthenticationToken
= new PreAuthenticatedAuthenticationToken(login, auth_token, Collections.singleton(new SimpleGrantedAuthority(role)));
SecurityContextHolder.getContext().setAuthentication(preAuthenticatedAuthenticationToken);
//At this point : the security context contains an authenticated Authentication and other security filters won't have any impact anymore
I don't say it is the best approach for your needs, but it will works with a more or less standard spring security configuration.

Spring Security REST Api for non-authorized connections

I have an application and API. I am using Spring and Spring security for both. Authentication is required to access API.
I configured RESTFUL web service only respond when authentication is successful (handling with JSESSIONID after login) which makes querying database not possible if user is not logged in or credentials are wrong. But somehow, I need to access database and make some changes for forgotten password. I need to check if requested email is on the record. Also, update the database after password change. eg; If I make 'UPDATE USER' action permitAll(), there will be a security problem.
Can you give me some ideas to handle that problem?
You can create some user with permissions to change password and later when changing password automaticly login this user -> send request ->logout user and all of that behind user view.

Programmatic authentication

I am using Spring Security in my application.
I have all the pages secured. But couple of URL needs to be available both for system user and anonymous user.
But anonymous user should not have direct access to the URLs. He gets a link with unique token and gets access to some URLS if this token is valid.
What I want to do is:
In controller check if token in URL is valid
If it is - authenticate user in the system programmatically using some predefined login and password. This user will be configured to have authority to access necessary URLs.
The question is:
Is this a correct approach to perform user authentication programatically with some roles in controller if token is valid? Is this safe approach?
Security is an aspect. An aspect can be decoupled from your main code (controller) to reduce code duplication and improve flexibility. Move authentication code from controller to new filter (be sure that this filter executed after spring security filter chain). You will be able secure new URLs via web.xml (zero lines of code).
I think the better way to do this is:
move the shared operations into service layer
define a controller for those anonymous user and make its authority
as anonymous
check the validity of token in this controller
if valid, call some services method to perform the operations.
render the result in this controller

Spring Security Recommended Design To Request User Login to Different User With Different Role

I have the following use case and need recommendations on the proper implementation. To be clear can this be done through configuration or do I need to implement new code?
Business Use Case
The business wants to allow a user to login via social media sites and access some of their pages. But in order to access pages that deal with $$ the user must login via the applications local account.
Technical Use Case
Allow users to login via Facebook or other provider and provide role USER_PARTIAL_RIGHTS
If user accesses a page with role USER_FULL_RIGHTS prompt the user to login to an account that is a local JDBC stored account.
This authentication must also ensure that the page is protected by USER_FULL_RIGHTS role and not other roles.
I am using grail spring security plugin, but I am expecting to have to customize the plugin.
So what are recommendations for doing this? A couple of ideas that I have are:
Technical Ideas
custom spring access denied handler
custom access denied controller instead of the stock jsp page
From what i understand from your question, here is my suggestion.
For login via Facebook use Spring Social. Here is the documentation. The implementations are straightforward. Write a custom signin method and set the authorities for partial rights, something like this:
public void signin(String userId) {
authorities = new ArrayList<GrantedAuthority>();
//set your partial rights authority
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(userId, null, authorities));
}
And do a method level security implementation using the #secured annotation to access the page that needs full rights. Something like this
#Secured("USER_FULL_RIGHTS ")
yourMethod(){
//code
}
This would prompt for a login where can use authentication from applications local account.
What we ended up implementing is a controller that looks at the role and redirects the user to the correct landing page. Kinda messy, but it works.
Collection<GrantedAuthority> inferred = SpringSecurityUtils.findInferredAuthorities(SpringSecurityUtils.getPrincipalAuthorities());
if(ifAnyGranted('ROLE_FOO', inferred)) {
redirect(controller: 'foo',action: 'home')
return
}

Resources