Security in Spring MVC and JSON - json

I want to provide security one way or another for Sending and Getting JSON Data,but I don't know how to do this.
Our System has roles of users (System admin, General Members, etc.)
We decided send data as JSON using the Spring MVC URL pattern. I don't want everybody that outside from system to use this URL, only users can use the URL.
Example
www.example.com/services/"hereUserPass"/"hereUserName"/category/3
Each request time for different URLs, Should I control the username and password whether registered before? or What should I do for Security?

You want to implement security into your Spring Web application. You can do this at two ways:
Url Based Security
Method Based Security
Try to make another xml file as like applicationContext-security.xml Here is an example:
<http use-expressions="true">
<intercept-url pattern="/" access="permitAll"/>
<intercept-url pattern="/static/**" filters="none" />
<intercept-url pattern="/**" access="isAuthenticated()" />
<form-login />
<logout />
</http>
Here we see that permitAll means permit everybody who wants to reach that URL. filters = none has the same effect but it means that user will not go over Spring Security(Previous one goes over Spring Security but has access, filtering doesn't applied). isAuthenticated means that user can reach there if authenticated. You can also apply role based acces to urls.
Other security implementation base on middle tier security. You should add this line at your application context security file:
<global-method-security pre-post-annotations="enabled" />
so you can use method based security as like:
#PreAuthorize("hasRole('ROLE_SUPERVISOR')")
void storeVisit(Visit visit) throws DataAccessException;
You can start to reading with Spring Security implementation of Spring's Pet Clinic example: http://static.springsource.org/spring-security/site/petclinic-tutorial.html
Also I recommend you read here: http://www.mularien.com/blog/2008/07/07/5-minute-guide-to-spring-security/

Related

CAS X.509 auth with attributes from database

I want to configure Apereo CAS 6.0.x to perform X.509 authentication and then retrieve principal attributes from a database table.
Rudimentary X.509 authentication is working with these lines in application.properties (and appropriate reverse proxy setup):
cas.authn.x509.extractCert=true
cas.authn.x509.sslHeaderName=SSL_CLIENT_CERT
cas.authn.x509.principalDescriptor=SUBJECT_DN
The default "Log In Successful" page shows that it knows how to get my certificate's subject DN.
But I can't figure out how to tell CAS to then use that subject DN value to query my database for additional attributes.
This page explicitly mentions my need (though with LDAP instead of JDBC), but does not say specifically how to achieve it:
In many cases it is necessary to perform authentication by one means and resolve principals by another. The PrincipalResolver component provides this functionality. A common use case for this this mix-and-match strategy arises with X.509 authentication. It is common to store certificates in an LDAP directory and query the directory to resolve the principal ID and attributes from directory attributes. The X509CertificateAuthenticationHandler may be be combined with an LDAP-based principal resolver to accommodate this case.
What properties need to be set so that the X509 authentication handler resolves the principal against the database?
The missing ingredient was this line in application.properties:
cas.authn.x509.principalType=SUBJECT_DN
Without it, CAS does not attempt to query any attributeRepository settings that you may have.

Add additional validation for logins using LexikJWTAuthenticationBundle

I want to add additional validation to allow the login, ie, not just check that the username and password match but do other validations on the user before allowing him to login.
I tried extending JWTTokenAuthenticator but it seems none of its methods are called during the login.
I thought of using a custom "AuthenticationSuccessHandler" but I'm not sure if this is the place I should do this and how could I report from there that the "login" is actually invalid.
Where should I put this logic?
I end up replacing the "login_form" authentication shown on the LexikJWTAuthenticationBundle bundle documentation for a custom guard authentication just for the login, i.e. different than the guard authentication used to validate the JWT tokens.
In the past, I had a similar requirement. Within the alternatives I chose to implement a custom user provider. Symfony documentation on custom user provider creation is more than enough to accomplish the task. Moreover, "Configuring the user provider" section of the LexikJwt documentation explains how to configure lexik_jwt accordingly.

How to get query parameters in ExceptionHandler?

In our project (JBoss 7.0.2, JSF 2), we work on a solution to catch all exceptions during user navigation and redirect them to nice error pages.
I used an ExceptionHandler, inspired by a lot of examples and tutorials online.
I managed to do a redirection feature without too much difficulty: in the ExceptionHandler.handle() method, for some exceptions (expired view/session, unauthenticated user asking a denied page, ...) I redirect the user on the login page through a good old
FacesContext.getCurrentInstance().getExternalContext().redirect(myRedirectPage);
with an additional query parameter containing the original url base64 encoded, and after a successful authentication I use the same redirection mechanism to send the user back to their page.
The problem is with ViewExpiredException on JSF actions, by example when the user click after their view has expired on any button or link with action or actionListener, synchronous or ajax-style, like
<h:commandButton action="#{myBean.myAction}" value="do that" />
or
<h:commandLink value="do that too">
<f:ajax render=":aZone" execute="#form" listener="#{myBean.myOtherAction}" />
</h:commandLink>
I cannot manage to obtain the query parameters in my ExceptionHandler.handle() method.
I tried to put my parameters in a f:metadata section, like
<f:metadata>
<f:viewParam name="myParam" value="#{myBean.myParam}" />
</f:metadata>
and to include them in the action, so in the method bound to button action I returned
"myPage.xhtml?includeViewParams=true"
but it changed nothing :-/
Am I doing something wrong? Where am I supposed to find the query paremeters? Is it in
FacesContext.getCurrentInstance().getExternalContext().getRequest()
** UPDATE **
As said in comments, view params are no more available after a ViewExpiredException (quite obvious, in fact), so params are to be stored elsewhere (#BalusC quickly suggested in a request scope or through cookie).
The request parameters are available by ExternalContext#getRequestParameterMap().
Map<String, String> params = externalContext.getRequestParameterMap();
// ...
Or if your application uses same parameter name with multiple values (which is usually the case for <h:selectManyXxx> components), use ExternalContext#getRequestParameterValuesMap() instead
Map<String, String[]> params = externalContext.getRequestParameterValuesMap();
// ...
Please note that this only returns the parameters of the current request, not of the initial request in case of postbacks.
As to the ExternalContext#getRequest(), it returns in case of JSF applications running on a servlet container an instance of HttpServletRequest which you'd need to cast, but you should rarely have the need to get it. The ExternalContext, while following the Facade design pattern, has a lot of methods which are delegating to the underlying raw HTTP servlet request, session and context. You'd namely ultimately like to end up with zero javax.servlet imports in your backing beans.
Update as per your comment, you actually want to get only the view parameters which are been registered by <f:viewParam>. You can get them by ViewMetadata#getViewParameters() wherein you pass the current UIViewRoot.
Collection<UIViewParameter> viewParameters = ViewMetadata.getViewParameters(FacesContext.getCurrentInstance().getViewRoot());
// ...

How can I change an html output of wcf service with my own content?

I wrote a wcf service that uses BasicHttpBinding with some url and a client using this service.
Users should launch a client application and specify the same url that is specified in server endpoint.
However, if a user inadvertently opens this url in a web browser, he/she sees information on how to retrieve service metadata, which is absolutely useless to them.
What should be done in order for him/her to see, for example a help topic?
You need to turn off the publication of the service's metadata.
You can disable it in the Web.config:
<serviceMetadata httpGetEnabled="false" />
You can find more information on MSDN here:
http://msdn.microsoft.com/en-us/library/system.servicemodel.description.servicemetadatabehavior.httpgetenabled.aspx
http://msdn.microsoft.com/en-us/library/ms731317.aspx
Of course this will still generate a default landing page if a user manually enters the service's URL in the address bar (e.g.: http://www.examle.com/service.svc). However now it will mention that the metadata is currently disabled.
If you want to customize that page I'd suggest you check out the following thread, it contains a complete code sample on how to set it up:
http://social.msdn.microsoft.com/forums/en-US/wcf/thread/5778651a-b212-438a-b3e8-f7029775d52a/
If you want to have custom help page instead of default one you need to modify ServiceDebug behavior:
<behaviors>
<serviceBehaviors>
<behavior name="...">
<serviceDebug httpHelpPageEnabled="true" httpHelpPageUrl="Your custom page url" />
</behavior>
</serviceBehaviors>
<behaviors>
The same properties also exist for HTTPS and in case of some special requirements you can also control their "binding".

Spring3, Security3, Hibernate, MYSQL - How to install user tracking into database

First Project: Spring3, Security3, Hibernate, MYSQL - How to install user tracking into database
I am working on my first project with Spring3, Security3, Hibernate, MYSQL.
I have the system working great I use Spring3 and Security3 goign to MySQL for the login and
using Spring3 MVC, Hibernate and MYSQL for system data.
I have a number of questions. Once I login does Spring Security save the user object somewhere that I can have
Hibrernate access it. I want Hibernate to put the user name or role into each insert to the database so as
I do my searches the system knows to only show data for that user and only that user?
this somes like it should be easy. Spring should be saving the user somewhere the hibernate can access.
please help me out
Once the user is authenticated, you can access the user's authentication session details:
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
SecurityContext will allow you to grab the Authentication object, and from that you can retrieve the principal (an object representing the authenticated user), roles, etc. You could inspect this information and determine what data should be stored/displayed for each user.
If you can add a request filter or interceptor (the vocabulary may vary between frameworks), you could probably make these security checks abstract/generic enough to be applied across your entire web app (instead of adding a few lines of code to every resource method you're attempting to secure). Either way, SecurityContext should get you closer to what you want.