There is one web application created using Spring 3.2 + Hibernate 4 + maven.
Now I want to do authenticate and authorization based on user role. As of now I am not concentrating on authentication. Lets say user is valid and I have a roles somewhere in the object.
Now I want to get started with the authorization part. I am new and not sure how to proceed. I did some R & D on net but it seems quite tough.
I have one document in which how I need to do is written.There are some question I would like to ask :
A Role Based Access Control framework is adopted to control permission : Please explain little bit. I think it is talking about authorization based on role.
UI Level Permissions, Method Level Permissions, Object Level Permissions : I search on net and found Object level permission is something like create ACL( access control list ) and it seems very complex. why it s required to have object level permission.
Dynamic permission evaluation on object : Why it is required.
I search on net found #PreAuthorize and #PostAuthorize is there on method level permission. Is Spring AOP is required to do this. As of now we are now using Spring AOP in application.
Please help me how to start.
for authorization you need to configure few things in security.xml file
first you need to load the roles on which you want to authorize
<sec:authentication-manager alias="authenticationManager">
<sec:authentication-provider ref="preauthAuthProvider"/>
</sec:authentication-manager>
<bean id="preauthAuthProvider" class="org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider">
<property name="preAuthenticatedUserDetailsService">
<bean id="userDetailsServiceWrapper" class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper">
<property name="userDetailsService" ref="userDetailsService"/>
</bean>
</property>
</bean>
You need create a bean name userDetailsService to fetch all the roles from DB or any other source.
Now you need to configure a decision manager by configuring a role voter saying that on which type of roles you want to authorize
<bean id="httpRequestAccessDecisionManager" class="org.springframework.security.access.vote.AffirmativeBased">
<property name="allowIfAllAbstainDecisions" value="false"/>
<property name="decisionVoters">
<list>
<ref bean="roleVoter"/>
after that you need to configure a filter security interceptor where you need to define a intercept url where you need to define a protected resource uri and access with the roles you want to protect
<bean id="fsi" class="org.springframework.security.web.access.intercept.FilterSecurityInterceptor">
<property name="authenticationManager" ref="authenticationManager"/>
<property name="accessDecisionManager" ref="httpRequestAccessDecisionManager"/>
<property name="securityMetadataSource">
<sec:filter-security-metadata-source lowercase-comparisons="true">
<sec:intercept-url pattern='/test**' access='testRole'/>
Related
I'm using Spring Security and Spring Boot. I'm using too a UserDetails and UserDetailsService.
When execution passed into DaoAuthenticationProvider class and the method additionalAuthenticationChecks(...), the SaltSource is null.
Do you know why ? Perhaps a configuration is needed ?
Thx.
You have to set the salt source. See for example this question as a possible way to do that: https://stackoverflow.com/a/26149525/185031
A SaltSource is needed to be configured. You can use one of its available implementations: SystemWideSaltSource or ReflectionSaltSource.
If you choose ReflectionSaltSource, you have to specify which property of UserDetails will be used for the salt. You may use any existing property of your UserDetails implementation (i.e username) or a specific salt field.
From security perspective, you should better consider a securely generated random salt. In that case, BCryptPasswordEncoder does the job for you (generating salt + storing it with the password).
Here are samples configurations found here.
In XML:
<bean id="authProvider"
class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<property name="userDetailsService" ref="customUserService" />
<property name="passwordEncoder" ref="encoder" />
</bean>
<bean id="encoder"
class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>
In java:
auth.jdbcAuthentication().dataSource(dataSource)
.passwordEncoder(passwordEncoder())
.usersByUsernameQuery("sql...")
.authoritiesByUsernameQuery("sql...");
I wanted to know how I can perform user locking (or the best way to perform the same) i.e. if a user is already logged in from a device and tries to login from another device, he/she should be notified that a session is already available for that user and an option to close other session and start a new one.
Framework Used Spring-MVC + hibernate 4.1.
And one more thing: how can I set a list of some user hashmap object in application context?
That can be done with Spring Security and Conncurrent Session Control. You can define how many sessions may exist concurrently and decide what to do if the maximum exceeds.
Their is a simple xml configuration in spring security for the same. First you have to register the SessionRegistry bean. I have used default class of SessionRegistryImpl of spring security for Session registry like :
<bean id="sessionRegistry"
class="org.springframework.security.core.session.SessionRegistryImpl" />
After that we have to register the ConcurrentSessionControlStrategy with container and tell it the maximum session allowed per user.
Example:
<bean id="sessionStrategy"
class="org.springframework.security.web.authentication.session.ConcurrentSessionControlStrategy">
<constructor-arg name="sessionRegistry" ref="sessionRegistry" />
<property name="maximumSessions"
value="${security.config.sessionStrategy.maximumSessions.value}" />
<property name="exceptionIfMaximumExceeded" value="true" />
</bean>
security.config.sessionStrategy.maximumSessions.value is the integer value specified in property file. By varying the maximumSessions property value we can define maximum concurrent users easily.
I am developing a web application using spring MVC, Hiberbate and MySQL database. I am trying to send data to server from a client, but I can not do it.
In detail,
I want to send my JSON data to http://localhost:8080/app/test . In my test controller I want to get the data which comes from the client and write it to screen or save it to db. I have been searching about 3 days and I have tried many strategies to do it, but I can not.
You must explicitly tell spring to use a json parser.
For instance, here is a piece of my DispatcherServlet config :
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jsonConverter" />
</list>
</property>
</bean>
<bean id="jsonConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes" value="application/json" />
</bean>
Jackson Must be in your classpath.
Then you write a method like this one in your annotated controller :
#RequestMapping(value = "/test", method = RequestMethod.POST)
public void myMethod(#RequestBody MyObject object) {
//... do what you want with the object
}
You just have to send an JSON object with properties that match the ones in MyObject, via a POST request.
lets say, I have a lot of stuff within my spring application context which looks like that
<bean name="foo.0001" class="com.example.MyClass">
<property name="name" value="foo.name.0001"/>
<property name="zap">
<bean class="com.example.Other">
<property name="name" value="foo.name.0001"/>
</bean>
</property>
<property name="bar">
<bean class="com.example.NextOther">
<property name="name" value="foo.name.0001"/>
</bean>
</property>
</bean>
so the string foo.name.0001 appears within the bean definition several times. Because it is a larger system with several blocks of this configuration, it is quite annoying to modify each of those ids. Ideally I would want to set it only once within a block. Is there a possibility to set some kind of property which exists only in a local scope of a bean definition?
I'm not sure how that would logically work, as you would still have to reference that value somehow to pass it to the nested beans. If you are worried about defining it multiple times, you can have a look at Springs PropertyPlaceholderConfigurer. It will allow you to the following:
<property name="bar">
<bean class="com.example.NextOther">
<property name="name" value="${foo.name.001}"/>
</bean>
</property>
This would allow you to define it once, and reference it from multiple locations.
It depends how much effort you want to put into to this but your requirements could be fufilled by a spring custom namespace. These are ideal when you have lots of identical blocks of beans each configured differently.
Basically you'd define the xml schema then write a bean definition parser that sets up the beans as required.
See here for more details:
http://www.javaworld.com/javaworld/jw-02-2008/jw-02-springcomponents.html
This is how Spring security simplified its xml configuration.
I need to load a specific applicationContext.xml file according to a given system property. This itself loads a file with the actual configuration. Therefore I need two PropertyPlaceHolderConfigurer, one which resolves the system param, and the other one within the actual configuration.
Any ideas how to do this?
Yes you can do more than one. Be sure to set ignoreUnresolvablePlaceholders so that the first will ignore any placeholders that it can't resolve.
<bean id="ppConfig1" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="locations">
<list>
<value>classpath*:/my.properties</value>
</list>
</property>
</bean>
<bean id="ppConfig2" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="false"/>
<property name="locations">
<list>
<value>classpath*:/myOther.properties</value>
</list>
</property>
</bean>
Depending on your application, you should investigate systemPropertiesMode, it allows you to load properties from a file, but allow the system properties to override values in the property file if set.
Another solution is to use placeholderPrefix property of PropertyPlaceholderConfigurer. You specify it for the second (third, fourth...) configurer, and then prefix all your corresponding placeholders, thus there will be no conflict.
<bean id="mySecondConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="classpath:/myprops.properties"
p:placeholderPrefix="myprefix-"/>
<bean class="com.mycompany.MyClass" p:myprop="${myprefix-value.from.myprops}"/>
Beware -- there might be a bug related to multiple configurers. See http://jira.spring.io/browse/SPR-5719 for more details.
I'm unable to get multiple to work locally... but I'm not yet blaming anyone but myself.
On my own side, playing with PropertyPlaceholderConfigurer both properties :
order (should be lower for first accessed/parsed PPC)
ignoreUnresolvablePlaceholders ("false" for first accessed/parsed PPC, "true" for next one)
and also give 2 distinct id(s) to both PPC (to avoid one to be overwritten by the other)
works perfectly
Hope it helps
You can't do this directly, and this JIRA issue from Spring explains why (check the comment from Chris Beams for a detailed explanation):
https://jira.springsource.org/browse/SPR-6428
However, he does provide a workaround using Spring 3.1 or later, which is to use the PropertySourcesPlaceholderConfigurer class instead of PropertyPlaceholderConfigurer class.
You can download a Maven-based project that demonstrates the problem and the solution from the Spring framework issues github:
https://github.com/SpringSource/spring-framework-issues
Look for the issue number, SPR-6428, in the downloaded projects.
We have the following approach working:
<util:properties id="defaultProperties">
<prop key="stand.name">DEV</prop>
<prop key="host">localhost</prop>
</util:properties>
<context:property-placeholder
location="file:${app.properties.path:app.properties}"
properties-ref="defaultProperties"/>
System property app.properties.path can be used to override path to config file.
And application bundles some default values for placeholders that cannot be defined with defaults in common modules.
Just giving 2 distinct ids worked for me. I am using spring 3.0.4.
Hope that helps.
In case, you need to define two PPC's (like in my situation) and use them independently. By setting property placeholderPrefix, you can retrieve values from desired PPC. This will be handy when both set of PPC's properties has same keys, and if you don't use this the property of ppc2 will override ppc1.
Defining your xml:
<bean name="ppc1"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="properties" ref="ref to your props1" />
<property name="placeholderPrefix" value="$prefix1-{" />
</bean>
<bean name="ppc2"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="properties" ref="ref to your props2" />
<property name="placeholderPrefix" value="$prefix2-{" />
</bean>
Retrieving during Run time:
#Value(value = "$prefix1-{name}")
private String myPropValue1;
#Value(value = "$prefix2-{name}")
private String myPropValue2;