Hello i have problem with java config in spring. I was trying to complete it by learning from mutliple tutorials but still i have something wrong. Any clue ?
error
AppConfig.java
package org.spring.mvc.libraryDemo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
/**
* Created by wiktor on 28.12.2015.
*/
#Configuration //adnotacja oznaczajaca plik konfiguracyjny
#EnableWebMvc
#ComponentScan(basePackages = "org.spring.mvc.libraryDemo") //enable skan komponentow
#Import({AppConfig.class}) //na co musi jeszcze uwazac Spring
public class AppConfig {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/pages/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
SpringConfigInit
package org.spring.mvc.libraryDemo.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class SpringConfigInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { AppConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
Controller
package org.spring.mvc.libraryDemo.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Created by wiktor on 28.12.2015.
*/
#Controller
public class HomeController {
#RequestMapping(value="/",method= RequestMethod.GET)
public String sayHello(ModelMap modelMap)
{
modelMap.addAttribute("greeting","witaj");
return "index";
}
}
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.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>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
With this type of servlet mapping, I think you will find your app at http://localhost:8080/{warfile name}/, not at http://localhost:8080/
You are mixing up two approaches here (as seen is your web.xml):
ContextLoaderListener with /WEB-INF/applicationContext.xml : this means that your spring application will be configured by the xml stuff in applicationContext.xml.
But obviously you want to use the Java Config, that is the beans defined under #Configuration annotated classes. To enable this, one way is to change your web xml for something like this:
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
<init-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>SpringRootConfig</param-value>
</init-param>
</servlet>
AnnotationConfigWebApplicationContext is the key here. That will scan your classpath and take the #Configuration stuff into account.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>org.spring.mvc.libraryDemo.config.AppConfig</param-value>
</context-param>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
Related
I am new to Spring and trying to make integration between spring and primefaces. I am getting 404 page no found when I run the project on tomcat after adding the ContextLoaderListener and RequestContextListener.
My web.xml file:
<?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_2_5.xsd"
id = "WebApp_ID" version="2.5">
<welcome-file-list>
<welcome-file>login.xhtml</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/spring.xml
</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
</web-app>
and this is my faces-config.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<faces-config
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_3.xsd"
version="2.3">
<application>
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
</application>
<navigation-rule>
<display-name>/login.xhtml</display-name>
<from-view-id>/login.xhtml</from-view-id>
</navigation-rule>
<navigation-rule>
<display-name>/login.xhtml</display-name>
<from-view-id>/login.xhtml</from-view-id>
<navigation-case>
<from-outcome>viewRecords</from-outcome>
<to-view-id>view.xhtml</to-view-id>
<redirect/>
</navigation-case>
</navigation-rule>
</faces-config>
and following is my controller class:
package com.testtask.nagarro.controller;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.validation.Valid;
import org.hibernate.annotations.Source;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.testtask.nagarro.forms.LoginForm;
import com.testtask.nagarro.forms.StatementForm;
import com.testtask.nagarro.interfaces.StatementRepository;
import com.testtask.nagarro.interfaces.UserService;
import com.testtask.nagarro.models.Statement;
#Controller
public class NagarroController {
#Autowired
private UserService userService;
public UserService getUserService() {
return userService;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
#RequestMapping(value= "/", method=RequestMethod.GET)
public String loginPage() {
return "login";
}
#RequestMapping(value="/login", method=RequestMethod.GET)
public ModelAndView login() {
ModelAndView model = new ModelAndView();
model.setViewName("login");
return model;
}
#RequestMapping(value="/viewRecords", method = RequestMethod.POST)
public String showHomePage(StatementForm form) {
System.out.println("In view records controller");
List<Statement> records = getUserService().getRecordsByAccountId(form.getAccountId());
return "view";
}
#RequestMapping(method=RequestMethod.POST)
public String processForm(#Valid LoginForm loginForm, BindingResult result,
Map<String, LoginForm> model) {
String username = "UserName";
String password = "password";
if(result.hasErrors()) {
return "loginform";
}
loginForm = (LoginForm) model.get("loginForm");
if(!loginForm.getUsername().equals(username) || !loginForm.getPassword().equals(password)) {
return "loginForm";
}
model.put("loginForm", loginForm);
return "home";
}
}
I tried to find a solution online but I am confused because most of the examples are using jsps.
please point me to the problem, I am attaching the github link.
Your views are NOT in webapp/WEB-INF folder as you defined in your InternalViewResolver bean.
They are located in webapp folder.
I am doing a university work, i need to do a simple login system that reject direct URL access to some pages if there is no login, i tried to use a filter, but when i load any page, the filter is called at least 20 times, and then is called more times, if i let it be, in 30 seconds is called 80 times because it wants, i need help please, here is my code.
The filter
package edu.eci.pdsw.misc;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import edu.eci.pdsw.view.LoginBean;
public class LoginFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
// Get the loginBean from session attribute
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
HttpSession session = request.getSession(false);
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(String.valueOf(LoginBean.mas()));
boolean loggedIn = (session != null) && (session.getAttribute("user") != null);
if (!loggedIn) {
String contextPath = ((HttpServletRequest)request).getContextPath();
((HttpServletResponse)response).sendRedirect(contextPath + "/Inicio.xhtml");
}
chain.doFilter(request,response);
}
public void init(FilterConfig config) throws ServletException {}
public void destroy() {}
}
the web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<context-param>
<param-name>primefaces.THEME</param-name>
<param-value>omega</param-value>
</context-param>
<!-- Login filter -->
<filter>
<filter-name>LoginFilter</filter-name>
<filter-class>edu.eci.pdsw.misc.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>LoginFilter</filter-name>
<url-pattern>*.xhtml</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>faces/Inicio.xhtml</welcome-file>
</welcome-file-list>
<listener>
<listener-class>edu.eci.pdsw.guice.GuiceContextListener</listener-class>
</listener>
</web-app>
if anything else is needed please tell i will put it here, thank you for the help
I am getting error
No bean named 'springSecurityFilterChain' available
when I don't include spring security configuration my code works fine. This project is created using spring annotation based configuration. When I created project using Maven pom.xml, web.xml, MvcConfiguration automatically gets created. Now I want to implement Spring-security with the same project and configuration. My configuration files are shown below.
MvcConfiguration.java
#Configuration
#ComponentScan(basePackages="com.mywebsite.emusicstore")
#EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter
{
#Bean
public ViewResolver getViewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Bean
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver resolver=new CommonsMultipartResolver();
Long maxUploadSize = 2048000L;
resolver.setMaxUploadSize(maxUploadSize);
return resolver;
} }
SpringSecurity.java
#Configuration
#EnableWebSecurity
public class SpringSecurity extends WebSecurityConfigurerAdapter{
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/admin**").access("ROLE_USER")
.and().formLogin().loginPage("/login").defaultSuccessUrl("/admin/").failureUrl("/login?error").usernameParameter("username").passwordParameter("password")
.and().logout().logoutSuccessUrl("/login?logout");
//http.csrf().disable();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
HibernateConfig hc = new HibernateConfig();
String authoritiesByUsernameQuery = "SELECT username,authorities FROM authorities WHERE username = ?";
String usersByUsernameQuery = "SELECT username,password,enabled FROM users WHERE username = ?";
auth.jdbcAuthentication().dataSource(hc.dataSource()).authoritiesByUsernameQuery(authoritiesByUsernameQuery).usersByUsernameQuery(usersByUsernameQuery);
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<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">
<display-name>emusicstore</display-name>
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>SpringDispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.mywebsite.emusicstore</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringDispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<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>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
Error
SEVERE: Exception starting filter springSecurityFilterChain
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean
named 'springSecurityFilterChain' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:687)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1207)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:284)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1086)
at org.springframework.web.filter.DelegatingFilterProxy.initDelegate(DelegatingFilterProxy.java:327)
at org.springframework.web.filter.DelegatingFilterProxy.initFilterBean(DelegatingFilterProxy.java:235)
at org.springframework.web.filter.GenericFilterBean.init(GenericFilterBean.java:236)
at org.apache.catalina.core.ApplicationFilterConfig.initFilter(ApplicationFilterConfig.java:279)
at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:260)
at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:105)
at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4598)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5223)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:155)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1404)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1394)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Please add this class as well.
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer{
}
I followed tutorial on http://shazsterblog.blogspot.com.es/2014/07/spring-security-custom-filterchainproxy.html to create a security filter using Java configuration instead of XML.
The bean is not being created and the application fails to load:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'springSecurityFilterChain' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:575)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1111)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:276)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1123)
at org.springframework.web.filter.DelegatingFilterProxy.initDelegate(DelegatingFilterProxy.java:323)
at org.springframework.web.filter.DelegatingFilterProxy.initFilterBean(DelegatingFilterProxy.java:235)
at org.springframework.web.filter.GenericFilterBean.init(GenericFilterBean.java:194)
at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:234)
at org.apache.catalina.core.ApplicationFilterConfig.setFilterDef(ApplicationFilterConfig.java:332)
at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:90)
at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:3783)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4409)
at org.jboss.web.tomcat.service.deployers.TomcatDeployment.performDeployInternal(TomcatDeployment.java:313)
at org.jboss.web.tomcat.service.deployers.TomcatDeployment.performDeploy(TomcatDeployment.java:145)
at org.jboss.web.deployers.AbstractWarDeployment.start(AbstractWarDeployment.java:461)
at org.jboss.web.deployers.WebModule.startModule(WebModule.java:122)
at org.jboss.web.deployers.WebModule.start(WebModule.java:97)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:157)
at org.jboss.mx.server.Invocation.dispatch(Invocation.java:96)
This is the web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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_2_5.xsd">
<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.config.SecurityConfig</param-value>
</context-param>
<servlet>
<servlet-name>Dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>dispatchOptionsRequest</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Dispatcher</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/application-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<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>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>test</realm-name>
</login-config>
<security-role>
<role-name>ADMIN</role-name>
</security-role>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<security-constraint>
<web-resource-collection>
<web-resource-name>COMUN</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>ADMIN</role-name>
</auth-constraint>
</security-constraint>
</web-app>
This is the SecurityConfig class:
#Configuration
#EnableWebMvc
public class SecurityConfig extends WebMvcConfigurerAdapter implements ResourceLoaderAware{
private ResourceLoader resourceLoader;
#Bean
public FilterChainProxy springSecurityFilterChain() throws Exception {
AuthenticationManager am = authenticationManager();
SecurityContextPersistenceFilter sif = getSecurityContextPersistenceFilter();
J2eePreAuthenticatedProcessingFilter j2eePreAuthFilter = getJ2eePreAuthenticatedProcessingFilter(am);
LogoutFilter logoutFilter = getLogoutFilter();
ExceptionTranslationFilter etf = getExceptionTranslationFilter();
FilterSecurityInterceptor fsi = getFilterSecurityInterceptor(am);
FilterChainProxy fcp = new FilterChainProxy(new DefaultSecurityFilterChain(
new AntPathRequestMatcher("/**"),
sif, j2eePreAuthFilter, logoutFilter, etf, fsi
));
return fcp;
}
private FilterSecurityInterceptor getFilterSecurityInterceptor(AuthenticationManager am) {
AccessDecisionVoter<Object> roleVoter = new RoleVoter();
List<AccessDecisionVoter> decisionVoters = new LinkedList<AccessDecisionVoter>();
decisionVoters.add(roleVoter);
AffirmativeBased httpRequestAccessDecisionManager = new AffirmativeBased(decisionVoters);
httpRequestAccessDecisionManager.setAllowIfAllAbstainDecisions(false);
FilterSecurityInterceptor filterSecurityInterceptor = new FilterSecurityInterceptor();
filterSecurityInterceptor.setAuthenticationManager(am);
filterSecurityInterceptor.setAccessDecisionManager(httpRequestAccessDecisionManager);
LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap = new LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>>();
List<ConfigAttribute> configs = new ArrayList<ConfigAttribute>();
configs.add(new org.springframework.security.access.SecurityConfig("hasRole(ADMIN)"));
requestMap.put(new AntPathRequestMatcher("/**"), configs);
FilterInvocationSecurityMetadataSource filterInvocationSecurityMetadataSource = new ExpressionBasedFilterInvocationSecurityMetadataSource(
requestMap, new DefaultWebSecurityExpressionHandler());
filterSecurityInterceptor
.setSecurityMetadataSource(filterInvocationSecurityMetadataSource);
return filterSecurityInterceptor;
}
private LogoutFilter getLogoutFilter() {
org.springframework.security.web.authentication.logout.LogoutFilter logoutFilter = new LogoutFilter("/", new SecurityContextLogoutHandler());
return logoutFilter;
}
private ExceptionTranslationFilter getExceptionTranslationFilter() {
ExceptionTranslationFilter exceptionTranslationFilter = new ExceptionTranslationFilter(
new Http403ForbiddenEntryPoint());
return exceptionTranslationFilter;
}
private SecurityContextPersistenceFilter getSecurityContextPersistenceFilter() {
return new org.springframework.security.web.context.SecurityContextPersistenceFilter();
}
private J2eePreAuthenticatedProcessingFilter getJ2eePreAuthenticatedProcessingFilter(AuthenticationManager am) throws Exception {
WebXmlMappableAttributesRetriever mappableRolesRetriever = new WebXmlMappableAttributesRetriever();
mappableRolesRetriever.setResourceLoader(this.resourceLoader);
mappableRolesRetriever.afterPropertiesSet();
SimpleAttributes2GrantedAuthoritiesMapper userRoles2GrantedAuthoritiesMapper = new SimpleAttributes2GrantedAuthoritiesMapper();
userRoles2GrantedAuthoritiesMapper.setConvertAttributeToUpperCase(true);
J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource j2eeBasedPreAuthenticatedWebAuthenticationDetailsSource
= new J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource();
j2eeBasedPreAuthenticatedWebAuthenticationDetailsSource.setMappableRolesRetriever(mappableRolesRetriever);
j2eeBasedPreAuthenticatedWebAuthenticationDetailsSource.setUserRoles2GrantedAuthoritiesMapper(userRoles2GrantedAuthoritiesMapper);
J2eePreAuthenticatedProcessingFilter j2eePreAuthenticatedProcessingFilter = new J2eePreAuthenticatedProcessingFilter();
j2eePreAuthenticatedProcessingFilter.setAuthenticationManager(am);
j2eePreAuthenticatedProcessingFilter.setAuthenticationDetailsSource(j2eeBasedPreAuthenticatedWebAuthenticationDetailsSource);
return j2eePreAuthenticatedProcessingFilter;
}
#Bean
public AuthenticationManager authenticationManager() throws Exception {
PreAuthenticatedGrantedAuthoritiesUserDetailsService preAuthenticatedGrantedAuthoritiesUserDetailsService = new PreAuthenticatedGrantedAuthoritiesUserDetailsService();;
PreAuthenticatedAuthenticationProvider preAuthenticatedAuthenticationProvider = new PreAuthenticatedAuthenticationProvider();
preAuthenticatedAuthenticationProvider.setPreAuthenticatedUserDetailsService(preAuthenticatedGrantedAuthoritiesUserDetailsService);
List<AuthenticationProvider> lProviders = new LinkedList<AuthenticationProvider>();
lProviders.add(preAuthenticatedAuthenticationProvider);
AuthenticationManager am = new ProviderManager(lProviders);
return am;
}
#Override
public void setResourceLoader(ResourceLoader arg0) {
this.resourceLoader = arg0;
}
}
Any help please?
Bit different from the example and simplified for this case, the filter class is created if its package is set on component-scan
The following part of the web.xml is not needed:
<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.config.SecurityConfig</param-value>
</context-param>
The web.xml defines the application context which will scan the class and create an instance of the filter. Later the instance is used in the web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/application-context-${environment}.xml</param-value>
</context-param>
If the ${environment} variable is "DEV", it uses an application context that has the security defined in XML, if the ${environment} variable is "PRO", it uses the following application context which has the logic defined in Java:
<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:jee="http://www.springframework.org/schema/jee"
xmlns:sec="http://www.springframework.org/schema/security"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd>
<context:component-scan base-package="com.config" />
</beans>
The filter only needs created in PRO so it needs the component-scan only for its package from within the application-context used in PRO.
i know that this post is duplicate and there are a lot of solutions yet, but i wasn't able to use them to resolve the problem.
I am trying to use spring + wildflyAS + resteasy. I have problems with resteasy integration, here is error which i am getting while trying to access controller:
javax.ws.rs.NotFoundException: Could not find resource for full path: http://localhost:8080/BQP/rest/student/test/1/pass/1
Controller:
#Controller
#RequestMapping(value = "student")
public class StudentController {
#Autowired
StudentService studentService;
public StudentController() {
}
#RequestMapping(value = "/test/{id}/pass/{testId}", method = RequestMethod.GET, produces = "application/json")
public
#ResponseBody
Response getCurrentTest(#PathVariable("id") String id,#PathVariable("testId") String testId){
TestDTO testDTO = studentService.getCurrentTest(id,testId);
return Response.status(200).entity(testDTO).build();
}
}
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<display-name>BQP</display-name>
<!--Spring-->
<servlet>
<servlet-name>Spring MVC Servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc-context.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Spring MVC Servlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<!--/Spring-->
<!--RestEASY-->
<servlet>
<servlet-name>Resteasy</servlet-name>
<servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Resteasy</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.bionic.rest.ApplicationConfiguration</param-value>
</context-param>
<context-param>
<param-name>resteasy.servlet.mapping.prefix</param-name>
<param-value>/rest</param-value>
</context-param>
<listener>
<listener-class>org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
</listener>
<!--/RestEASY-->
ApplicationConfiguration:
package com.bionic.rest;
import javax.ws.rs.core.Application;
import java.util.HashSet;
import java.util.Set;
public class ApplicationConfiguration extends Application {
private Set<Object> singletons = new HashSet<Object>();
private Set<Class<?>> empty = new HashSet<Class<?>>();
public ApplicationConfiguration() {
singletons.add(new StudentController());
}
#Override
public Set<Class<?>> getClasses() {
return empty;
}
#Override
public Set<Object> getSingletons() {
return singletons;
}
}
Moreover, i can access this controller without /rest in url.