Custom Permission Evaluator is not getting invoked : Spring security 3.2 - java

I am trying to implement custom permission evaluator in my project. I have configured spring security 3.2 and spring 4. However, I am not able to get it working.
springframework.version : 4.0.2.RELEASE
springsecurity.version : 3.2.1.RELEASE
I have annotated all my controller methods with #PreAuthorize("hasPermission()") annotation. But the call is not going into hasPermission() method in my custom evaluator.
My code is pasted below :
spring-security.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd">
<global-method-security pre-post-annotations="enabled" jsr250-annotations="enabled">
<expression-handler ref="expressionHandler"/>
</global-method-security>
<http auto-config="true" use-expressions="true" access-denied-page="/auth/auth/denied" >
<intercept-url pattern="/auth/auth/login" access="denyAll"/>
<intercept-url pattern="/auth/main/admin" access="hasRole('ROLE_ADMIN')"/>
<intercept-url pattern="/auth/main/common" access="hasRole('ROLE_USER')"/>
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="user" password="123456" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
<beans:bean class="org.springframework.security.authentication.encoding.Md5PasswordEncoder" id="passwordEncoder"/>
<!-- A custom service where Spring will retrieve users and their corresponding access levels -->
<!--<bean id="customUserDetailsService" class="com.cj.customAuthProvider"/>-->
<beans:bean id="expressionHandler" class="org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler">
<beans:property name="permissionEvaluator" ref="permissionEvaluator"/>
</beans:bean>
<beans:bean id="permissionEvaluator" class="com.mycompany.common.evaluators.AuthorizationEvaluatorController"/>
</beans:beans>
rest-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="com.reactore.common.web.controller"/>
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="order" value="1"/>
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes" value="application/json"/>
</bean>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes" value="text/plain;charset=UTF-8"/>
</bean>
</list>
</property>
</bean>
</beans>
web.xml
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:domain-config.xml /WEB-INF/spring-security.xml</param-value>
</context-param>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/rest-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/auth/*</url-pattern>
</servlet-mapping>
</web-app>
Permission Evaluator
public class AuthorizationEvaluatorController extends ModuleController implements PermissionEvaluator{
private boolean checkPermission(Long userId, String permissionId){
//get user details and check if access is there.
return false;
}
#Override
public boolean hasPermission(Authentication authentication, Object userId, Object permissionId) {
System.out.println("Checking the permission......");
return checkPermission((Long)userId, (String)permissionId);
}
#Override
public boolean hasPermission(Authentication authentication, Serializable serializable, String s, Object o) {
return false;
}
}
Controller
#Controller
public class RoleController {
#RequestMapping(value="/role/{roleId}", method = RequestMethod.GET)
#ResponseBody
**#PreAuthorize("hasPermission(#roleId,3)")**
public ResponseEntity<Object> getRoleFromId(#PathVariable("roleId") Long roleId) throws Exception {
return getRoleService(roleId);
}
}

Finally, the issue got resolved for me.
I added the line <aop:config proxy-target-class="true" /> to my config file and now the evaluator is getting invoked.

Related

Spring security custom Authenticator not called after spring/spring security version upgrade

I upgrade spring and spring security to latest versions, in testing out basic functionality my Authenticator (which works with spring and spring security version 3) doesn't work with spring security 4. (I am moving to jdk 8 so due to asm conflicts I can't use old versions anymore). What config change do I need to make to support the new version of spring:
here is my web.xml:
<!--?xml version="1.0" encoding="UTF-8"?-->
<web-app
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID"
version="3.0">
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>excludePatterns</param-name>
<param-value>/resources/*</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/springapp-servlet.xml
/WEB-INF/springapp-security.xml
</param-value>
</context-param>
<display-name>template</display-name>
<servlet>
<servlet-name>springapp</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springapp</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
<session-config>
<session-timeout>90000</session-timeout>
</session-config>
<error-page>
<error-code>404</error-code>
<location>/login.jsp</location>
</error-page>
</web-app>
here is spring xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:security="http//www.springframework.org/schema/security"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-4.1.xsd">
<context:component-scan base-package="com.spring" />
<mvc:resources mapping="/resources/**" location="/resources/"/>
<mvc:annotation-driven/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages"></property>
<property name="defaultEncoding" value="UTF-8"></property>
</bean>
</beans>
here is spring security xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-4.1.xsd">
<beans:bean id="SpringAuthenticationProvider" class="com.spring.SpringAuthenticationProvider"></beans:bean>
<authentication-manager alias="authenticationManager">
<authentication-provider ref="SpringAuthenticationProvider"></authentication-provider>
</authentication-manager>
<!-- ############################################# -->
<http auto-config="true" use-expressions="true">
<form-login login-page="/login"
default-target-url="/main"
username-parameter="j_username"
password-parameter="j_password"
authentication-failure-url="/login?auth=fail"/>
<intercept-url pattern="/admin/**" access="hasAnyRole('admin')"></intercept-url>
<!-- <intercept-url pattern="/resources/**" access="permitAll"></intercept-url> -->
<intercept-url pattern="/login" access="permitAll"></intercept-url>
<intercept-url pattern="/logout" access="permitAll"></intercept-url>
<intercept-url pattern="/**" access="permitAll"/>
<intercept-url pattern="/main" access="permitAll"></intercept-url>
<intercept-url pattern="/" access="permitAll"></intercept-url>
<logout logout-url="/logout" logout-success-url="/login"></logout>
<access-denied-handler error-page="/403"/>
</http>
</beans:beans>
here is my authenticator:
package com.spring;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
public class SpringAuthenticationProvider implements AuthenticationProvider
{
private static final Logger LOG = LoggerFactory.getLogger( SpringAuthenticationProvider.class );
#Override
public boolean supports( Class<? extends Object> authentication )
{
return true;
}
/*
#Override
public boolean supports(Class<? extends Object> authentication) {
return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
}
*/
#Override
public Authentication authenticate( Authentication authentication ) throws AuthenticationException
{
String username = authentication.getName();
String password = authentication.getCredentials().toString();
List<GrantedAuthority> grants = new ArrayList<GrantedAuthority>();
grants.add( new SimpleGrantedAuthority( "admin" ) );
return new UsernamePasswordAuthenticationToken( username , "" , grants );
}
}
the solution was to change login page to point to /login and previous j_username/j_password to username/password in the jsp

Spring framework, custom function in PreAuthorize of controller

I am new to spring and i'm trying to learn be developing a simple application.
This is the schema of the database:
http://i.imgur.com/69czuV5.png
It is very simple, each user must start by logging in, and once they do it, a list of the teams in which are administrators is displayed. That information is stored in the table team_members
INSERT INTO team_members (user_id, team_id, role) VALUES ('1', '1', 'admin');
INSERT INTO team_members (user_id, team_id, role) VALUES ('1', '2', 'admin');
INSERT INTO team_members (user_id, team_id, role) VALUES ('2', '2', 'player');
INSERT INTO team_members (user_id, team_id, role) VALUES ('2', '3', 'admin');
My problem arises when a user tries to edit or access the page to edit of one of the teams. This is my controller to do it:
#RequestMapping(value="teams/{id}/edit", method=RequestMethod.GET)
public ModelAndView editTeamPage(#PathVariable Integer id) {
ModelAndView modelAndView = new ModelAndView("edit-team-form");
Team team = teamService.getTeam(id);
modelAndView.addObject("team",team);
return modelAndView;
}
To be able to access this page, this user must be authenticated isAuthenticated(), however, I would also like to check if the role of the user in the table team_members is admin.
So my question is, what is the best way to do this? Should I insert an if in the beggining of every controller function that must verify this condition? Is there a cleaner solution for this?
I tried to create
package com.sports.beans;
import org.springframework.stereotype.Component;
#Component("mySecurityService")
public class MySecurityService {
public boolean hasPermission(String key) {
return false;
}
}
and added #PreAuthorize("#mySecurityService.hasPermission('special')") to the controller function but it didn't work. Edit: the method mySecurityService.hasPermission(...) is not called
This is my spring-security.xml
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd">
<global-method-security pre-post-annotations="enabled" />
<!-- enable use-expressions -->
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/admin**" access="hasRole('ROLE_ADMIN')" />
<intercept-url pattern="/user**" access="hasRole('ROLE_USER')" />
<intercept-url pattern="/teams/**" access="isAuthenticated()" />
<!-- access denied page -->
<access-denied-handler error-page="/403" />
<form-login login-page="/login" authentication-failure-url="/login?error"
username-parameter="username" password-parameter="password" />
<logout logout-success-url="/login?logout" />
<!-- enable csrf protection -->
<csrf />
</http>
<authentication-manager>
<authentication-provider user-service-ref="myUserDetailsService">
<password-encoder hash="bcrypt"/>
</authentication-provider>
</authentication-manager>
<beans:bean id="mySecurityService" class="com.sports.beans.MySecurityService" />
</beans:beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Sports</display-name>
<!-- Spring MVC -->
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-database.xml,
/WEB-INF/spring-security.xml
</param-value>
</context-param>
<!-- Spring Security -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>hibernateFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
spring-database.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:sec="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test_sports"/>
<property name="username" value="root"/>
<property name="password" value="lol123" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="annotatedClasses">
<list>
<value>com.sports.models.User</value>
<value>com.sports.models.UserRole</value>
<value>com.sports.models.Team</value>
<value>com.sports.models.TeamMember</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="userDao" class="com.sports.dao.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<context:component-scan base-package="com.sports" />
<bean id="myUserDetailsService" class="com.sports.service.MyUserDetailsService">
<property name="userDao" ref="userDao"/>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="get*" read-only="true"/>
<tx:method name="find*" read-only="true"/>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="userServicePointCut" expression="execution(* com.sports.service.*Service.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="userServicePointCut"/>
</aop:config>
</beans>
mvc-dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.sports.*"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
In order for #PreAuthorize to impact the code, you need to ensure that you enable method security. For example:
<global-method-security pre-post-annotations="enabled" />
A common problem is users will define the security annotations on their controllers and the global-method-security element in the parent context. This will not work.
The global-method-security element must be defined in the same Spring Context as the resource you are trying to secure. So for example, if the root ApplicationContext defines the service bean you are trying to secure, it should also refer to the a configuration that contains global-method-security.
For your example, that likely means that all of the configuration should be picked up by the following in your web.xml:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-database.xml,
/WEB-INF/spring-security.xml
</param-value>
</context-param>

my spring security code is not using the static resources like css,js and images folder

I am trying to access static resource in jsp that i am using in spring security...but it is not accessing those static resources need your ..valuable suggestions ..i am new in springs security ....
my dispacher-servlet is...
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:property-placeholder location="classpath:resources/database.properties" />
<context:component-scan base-package="com.nufame" />
<tx:annotation-driven transaction-manager="hibernateTransactionManager" />
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}
</prop>
</props>
</property>
</bean>
my security.xml is..
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:security="http://www.springframework.org/schema/security"
xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<!-- Non secure URLs -->
<security:http auto-config="true">
<security:intercept-url pattern="/index*" access="ROLE_USER" />
<security:form-login login-page="/login" default-target-url="/index"
authentication-failure-url="/fail2login" />
<security:logout invalidate-session="true"
logout-success-url="/logout" />
<security:access-denied-handler
error-page="/403" />
</security:http>
<security:http pattern="/css/**" security="none" />
<security:authentication-manager>
<security:authentication-provider>
<!-- <security:user-service> <security:user name="dineshonjava" password="sweety"
authorities="ROLE_USER" /> </security:user-service> -->
<security:jdbc-user-service
data-source-ref="dataSource"
users-by-username-query="select username, password, active from users where username=?"
authorities-by-username-query="select us.username, ur.authority from users us, user_roles ur
where us.user_id = ur.user_id and us.username =? " />
</security:authentication-provider>
</security:authentication-manager>
</beans>
my web.xml is...
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<servlet>
<servlet-name>sdnext</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>sdnext</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/sdnext-*.xml,
</param-value>
</context-param>
<welcome-file-list>
<welcome-file>index</welcome-file>
</welcome-file-list>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>
org.springframework.web.filter.DelegatingFilterProxy
</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
</web-app>
please help i AM new in spring security ..
thanks in advance....
In dispatcher-servlet, add resources using <mvc:resources>, e.g.:
<mvc:resources mapping="/css/**" location="/css/">
And also don't forget to add these lines in top <bean: ...> :
xmlns:mvc="http://www.springframework.org/schema/mvc"
...
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
Refer this How to use static resources like js, css?
Откройте доступ к папкам всех статических ресурсов в моём случае это "/assets/**", "/fragments/**", "/node_modules/**", "/stylus/**"
#Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests((requests) -> requests
.antMatchers("/signin", "/assets/**", "/fragments/**", "/node_modules/**", "/stylus/**").permitAll()
.anyRequest().authenticated()
)
.formLogin((form) -> form
.loginPage("/signin").defaultSuccessUrl("/")
.permitAll()
)
.logout((logout) -> logout.permitAll());
return http.build();
enter image description here

Spring security mapping

I want to limit access to my file uploading functionality. I wrote intercept url in security file, but Spring Security doesn't map this URL. I use 3.0.3 version of spring security.
These are my xml files :
security.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.0.xsd">
<security:global-method-security secured-annotations="enabled" />
<http auto-config="true" use-expressions="true" access-denied-page="/forbidden.jsp">
<intercept-url pattern="/files/**"/>
<intercept-url pattern="/resources/**" filters="none"/>
<form-login login-page="/login.htm"
authentication-failure-url = "/login.htm?login_error=1"
default-target-url="/forbidden.htm"/>
<logout logout-success-url="/login.htm" />
<anonymous username="guest" granted-authority="ROLE_ANONYMOUS" />
<remember-me />
</http>
<beans:bean id="accountService" name="accountService" class="com.demo.service.impl.AccountServiceImpl" />
<beans:bean id="daoAuthenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<beans:property name="userDetailsService" ref="accountService"/>
</beans:bean>
<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="accountService" />
</authentication-manager>
</beans:beans>
dispatcher-servlet.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<mvc:annotation-driven />
<context:component-scan base-package="com.demo"/>
<mvc:resources mapping="/resources/**" location="/resources/" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
</beans>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:/application-dao.xml
/WEB-INF/applicationContext.xml
/WEB-INF/security.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- Spring Security -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
Why do you think that Spring doesn't map your URL?
At first glance mapping looks good, but intercept-url is not complete. To give access to URL for someone you should point the rule at access attribute. So correct interceptor will looks like this:
<intercept-url pattern="/files/**" access="isAuthenticated()" />
In this particular case only authenticated users will have access to your URL.
More about basic Spring Security features you can read at official tutorial.
You are missing your namespace on your security tags, I see they are declared as "security", and your intercept tags are missing this namespace

How to configure spring security in a web application?

How to configure Spring Security in a web application?
I added three JAR files to my lib: security-core, security-web and security-config. Now what do I need to add in configuration XML file with a custom login page?
ref : http://www.mkyong.com/spring-security/spring-security-form-login-example/
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Spring</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/app-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Spring</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/spring-security.xml
</param-value>
</context-param>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
spring-security.xml
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.0.3.xsd">
<http auto-config="true">
<intercept-url pattern="/login.jsp" access="ROLE_ANONYMOUS" />
<intercept-url pattern="/**" access="ROLE_USER" />
<form-login login-page="/login.jsp" default-target-url="/" />
<logout logout-url="/logout" logout-success-url="/login.jsp"/>
<intercept-url pattern="/css/**" filters="none"/>
<intercept-url pattern="/js/**" filters="none"/>
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="admin" password="admin" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
app-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<mvc:annotation-driven />
<task:annotation-driven/>
<bean id="viewResolver" class= "org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="cache" value= "true"/>
<property name="prefix" value= ""/>
<property name="suffix" value=".ftl"/>
<property name="contentType" value="text/html;charset=UTF-8"/>
<property name="exposeSpringMacroHelpers" value="true"/>
<property name="requestContextAttribute" value="rc"/>
</bean>
</beans>

Categories