i have two classes which i want to expose as a restful web services using apache cxf and spring but i am unable expose two web services of two different classes.i got a runtime exception while invoking second service.here are my web.xml,applicationcontext.xml and two classes which i am using in my project.plz any one fix this issue
`enter code here` web.xml
--------
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>ApacheCXF Sample Application</display-name>
<!-- Add for Spring support -->
<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>CXFServlet</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property</param-name>
<param-value>com.iton.restExamples.ServiceOneImpl</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>AnotherCXFServlet</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.iton.restExamples.ServiceTwoImpl</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/base/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>AnotherCXFServlet</servlet-name>
<url-pattern>/another/*</url-pattern>
</servlet-mapping>
</web-app>
applicatin context.xml
------------------------
<?xml version="1.0" encoding="UTF-8"?>
<beans default-autowire="byName"
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
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/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
<context:component-scan base-package="com.example" />
<!-- <import resource="classpath:META-INF/cxf/cxf.xml" />
<import resource="classpath:META-INF/cxf/cxf-extension-jaxrs-binding.xml" />
<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
-->
<jaxrs:server id="restContainer" address="/">
<jaxrs:serviceBeans>
<ref bean="serviceOne"/>
<ref bean="serviceTwo"/>
</jaxrs:serviceBeans>
</jaxrs:server>
<bean id="serviceOne" class="com.iton.restExamples.ServiceOneImpl"></bean>
<bean id="serviceTwo" class="com.iton.restExamples.ServiceTwoImpl"></bean>
</beans>
ServiceOneImpl.java
---------------
package com.iton.restExamples;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
public class ServiceOneImpl implements ServiceOne {
public ServiceOneImpl() {
// TODO Auto-generated constructor stub
}
#Override
#GET
#Produces("text/plain")
#Path("/one")
public String mesgTwo(#QueryParam("msg") String mesgTwo) {
System.out.println(mesgTwo);
System.out.println("welcome message");
return mesgTwo;
}
}
SeriveTwoImpl.java
-------------------
package com.iton.restExamples;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
public class ServiceTwoImpl implements ServiceTwo {
public ServiceTwoImpl() {
// TODO Auto-generated constructor stub
}
#Override
#GET
#Produces("text/plain")
#Path("/two")
public String mesgTwo(String mesg) {
mesg="Welcome";
System.out.println(mesg);
System.out.println("welcome message in Serive two");
return mesg;
}
}
Try using #Path annotation at class level to differentiate between the two service classes.
When you define the service beans in application context, the address for both the beans is "/".
#Path("/ServiceOne")
public class ServiceOneImpl implements ServiceOne {....}
#Path("/ServiceTwo")
public class ServiceTwoImpl implements ServiceTwo {....}
Related
I was trying enable basic authentication for my endpoints in Spring 4. But it does not seem to do anything.
Any idea?
If I put a breakpoint, I can only see the configure method is called when the server starts up.
package org.example;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
#Validated
public class MyController {
#RequestMapping(value = "/health")
public String health() {
return "OK";
}
#RequestMapping(value = "/getdata")
public String getData() {
return "data";
}
}
package org.example;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
#EnableWebSecurity
public class BasicAuthConfig extends WebSecurityConfigurerAdapter {
// Authentication : User --> Roles
#Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.inMemoryAuthentication()
.withUser("appuser")
.password("{noop}apipassword")
.roles("USER");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
//HTTP Basic authentication
.httpBasic()
.and()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/rest/**").hasRole("USER")
.antMatchers(HttpMethod.POST, "/cxf/**").hasRole("USER")
.and()
.csrf().disable()
.formLogin().disable();
}
}
My web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<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>cxf</servlet-name>
<display-name>CXF Servlet</display-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>101</load-on-startup>
<init-param>
<param-name>use-x-forwarded-headers</param-name>
<param-value>true</param-value>
</init-param>
</servlet>
<servlet>
<servlet-name>rest</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>103</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>rest</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>cxf</servlet-name>
<url-pattern>/cxf/*</url-pattern>
</servlet-mapping>
</web-app>
http://localhost:8080/TestWeb3/rest/health
is still accessible without authentication
It turns out I need to hook up a security filter in web.xml as follows
<!-- 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>
After I integrated spring security into vaadin there of course appeared a need to redirect user after successfull authentication.
I integrated spring security using two servlets - one for vaadin and another - for spring security.
Here my web.xml
<?xml version="1.0"?>
<web-app 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"
version="2.5">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:/pmc-web-context.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>
<servlet>
<servlet-name>another-pmc-servlet</servlet-name>
<servlet-class>ru.xpoft.vaadin.SpringVaadinServlet</servlet-class>
<init-param>
<param-name>beanName</param-name>
<param-value>pmcVaadin</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>another-pmc-servlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<!-- Spring Security -->
<servlet>
<servlet-name>login-pmc-servlet</servlet-name>
<servlet-class>ru.xpoft.vaadin.SpringVaadinServlet</servlet-class>
<init-param>
<param-name>beanName</param-name>
<param-value>loginVaadin</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>login-pmc-servlet</servlet-name>
<url-pattern>/login/*</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>
</web-app>
My security context looks like this
<http auto-config="true">
<intercept-url pattern="/*" access="ROLE_USER"/>
<form-login login-page="/login/" default-target-url="/*" authentication-failure-url="/login/?login_error=true"/>
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="user" password="pass" authorities="ROLE_USER"/>
<user name="admin" password="admin" authorities="ROLE_ADMIN, ROLE_USER"/>
</user-service>
</authentication-provider>
</authentication-manager>
On my loginUI(bean name loginVaadin) page there is a login form
public class LoginForm extends Window {
private TextField login;
private TextField password;
private Button enter;
private HorizontalLayout buttonLayout;
private FormLayout formLayout;
private Image facebookIcon;
#Override
public void attach() {
setCaption(StringValues.LOGIN_FORM_CAPTION);
setSizeUndefined();
setResizable(false);
setModal(true);
setContent(createLayout());
super.attach();
}
private FormLayout createLayout() {
login = new TextField("Login");
password = new TextField("Password");
enter = new Button("Enter(close)");
final LoginUi ui = (LoginUi) LoginUi.getCurrent();
enter.addClickListener(new ClickListener() {
#Override
public void buttonClick(ClickEvent event) {
String loginValue = login.getValue();
String passwordValue = password.getValue();
AuthenticationService authenticationService = ui.getAuthenticationService();
String result = authenticationService.authorize(loginValue, passwordValue);
if (StringUtils.isBlank(result)) {
LoginForm.this.close();
}
ui.getPage().setLocation("localhost:8080/pmc-web/");
}
});
buttonLayout = new HorizontalLayout();
String pathToFile = VaadinService.getCurrent().getBaseDirectory()
.getAbsolutePath() + "\\WEB-INF\\images\\facebook_icon.png";
FileResource resource = new FileResource(new File(pathToFile));
facebookIcon = new Image(null, resource);
facebookIcon.addClickListener(new MouseEvents.ClickListener() {
#Override
public void click(com.vaadin.event.MouseEvents.ClickEvent event) {
try {
ui.getPage().setLocation(ui.getAuthenticationService()
.redirect(ui.getProperty("oauth.application"), ui.getProperty("oauth.callback")));
} catch (Exception e) {
Notification.show(e.getMessage());
}
}
});
buttonLayout.addComponent(facebookIcon);
buttonLayout.addComponent(enter);
buttonLayout.setComponentAlignment(enter, Alignment.BOTTOM_LEFT);
formLayout = new FormLayout(login, password, buttonLayout);
formLayout.setComponentAlignment(buttonLayout, Alignment.BOTTOM_LEFT);
formLayout.setMargin(true);
return formLayout;
}
}
But how to make it redirect to required me vaadin page with all components(ui bean name pmcVaadin)? Because when I do like this - it's again being intercepted and it shows me loginform again.
First of all shorten and clean up your "createLayout" method. ;)
Try:
ui.getNavigator().navigateTo("pmc-web");
I started with Spring Security framework. I set the framework. it works fine but my problem is at the logout function ...
when I disconnect. and I come to connect one more time he pass me on page access denied. whenever I am forced to restart tomcat for that he accepts my connection
My second Probleme :I tried to test the thing that speaks of time out session I stayed more than 1 min and when I come back I'm still on the same page. I do not know how to activate this option I think I configured on my security.xml but it doesn't work
This is My Sprinconfiguration
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:sec="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.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<sec:http auto-config="true" use-expressions="true">
<sec:intercept-url pattern="/pagess/**" access="hasRole('ROLE_USER')"/>
<sec:form-login login-page="/login.jsf" authentication-failure-url="/loginFailed.jsf" default-target-url="/pagess/Menu.jsf"/>
<sec:logout logout-success-url="/login.jsf" delete-cookies="JSESSIONID" invalidate-session="true"/>
<sec:session-management invalid-session-url="/login.jsf">
<sec:concurrency-control max-sessions="1"
error-if-maximum-exceeded="true" />
</sec:session-management>
</sec:http>
<sec:authentication-manager alias="authenticationManager">
<sec:authentication-provider>
<sec:jdbc-user-service data-source-ref="DataSource"/>
</sec:authentication-provider>
</sec:authentication-manager>
</beans:beans>
and this is my bean Loginbean
#ManagedBean(name="loginBean")
#SessionScoped
public class LoginBean {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String doLogin() throws ServletException, IOException {
ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
RequestDispatcher dispatcher = ((ServletRequest) context.getRequest())
.getRequestDispatcher("/j_spring_security_check?j_username=" + username
+ "&j_password=" + password);
dispatcher.forward((ServletRequest) context.getRequest(),
(ServletResponse) context.getResponse());
FacesContext.getCurrentInstance().responseComplete();
return null;
}
public String dologout() throws IOException {
FacesContext.getCurrentInstance().getExternalContext()
.invalidateSession();
this.username = "";
this.password = "";
ExternalContext context =FacesContext.getCurrentInstance().getExternalContext();
context.redirect(context.getRequestContextPath()
+ "/j_spring_security_logout");
FacesContext.getCurrentInstance().responseComplete();
return null;
}
}
this is WebXml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" 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">
<display-name>PFE</display-name>
<context-param>
<param-name>primefaces.THEME</param-name>
<param-value>trontastic</param-value>
</context-param>
<context-param>
<description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>client</param-value>
</context-param>
<context-param>
<param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
<param-value>resources.application</param-value>
</context-param>
<listener>
<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
</listener>
<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>*.jsf</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/Test.jsp</welcome-file>
</welcome-file-list>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/application.xml
/WEB-INF/spring_sec.xml
</param-value>
</context-param>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</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>
<dispatcher>FORWARD</dispatcher>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
</web-app>
I fixed My Problem ..there is one Listner misssing
<listener>
<listener-class>
org.springframework.security.web.session.HttpSessionEventPublisher
</listener-class>
</listener
I have written custom UserDetailsService to validate user from database.First time it is working fine but when same user try to login after logout second time it is giving error.my application is based on
Spring 3.1 , Spring security with Pretty faces on tomcat 7
org.springframework.security.authentication.BadCredentialsException: Bad credentials
here is my configuration details 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_2_5.xsd"
version="2.5" metadata-complete="true">
<!-- The definition of the Root Spring Container shared by all Servlets
and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/application-context.xml,
/WEB-INF/spring/application-context-security.xml
</param-value>
</context-param>
<context-param>
<param-name>primefaces.THEME</param-name>
<param-value>redmond</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
<listener>
<listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
</listener>
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>
org.springframework.web.filter.CharacterEncodingFilter
</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/classes/log4j.properties</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>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>FORWARD</dispatcher>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/application-context.xml,
/WEB-INF/spring/application-context-security.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/jcsb</url-pattern>
</servlet-mapping>
<!-- Pretty Face -->
<filter>
<filter-name>Pretty Filter</filter-name>
<filter-class>com.ocpsoft.pretty.PrettyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Pretty Filter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>FORWARD</dispatcher>
<dispatcher>REQUEST</dispatcher>
<dispatcher>ERROR</dispatcher>
</filter-mapping>
<context-param>
<param-name>facelets.DEVELOPMENT</param-name>
<param-value>true</param-value>
</context-param>
<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>*.jsf</url-pattern>
</servlet-mapping>
<error-page>
<exception-type>org.springframework.security.access.AccessDeniedException</exception-type>
<location>/login.xhtml</location>
</error-page>
<session-config>
<session-timeout>10</session-timeout>
</session-config>
<error-page>
<exception-type>javax.faces.application.ViewExpiredException</exception-type>
<location>/index.html</location>
</error-page>
application-context.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:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
<context:component-scan base-package="com.swift.jcbs.web" />
<tx:annotation-driven />
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
<property name="scopes">
<map>
<entry key="view">
<bean class="com.suraj.jcbs.web.spring.ViewScope"/>
</entry>
</map>
</property>
</bean>
application-context-security.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:faces="http://www.springframework.org/schema/faces"
xmlns:int-security="http://www.springframework.org/schema/integration/security"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:sec="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/integration/security http://www.springframework.org/schema/integration/security/spring-integration-security-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/faces http://www.springframework.org/schema/faces/spring-faces-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<sec:global-method-security
secured-annotations="enabled" jsr250-annotations="enabled" pre-post-annotations="enabled">
</sec:global-method-security>
<!--
resource security
Note:
Access-denied-page is invoked when user is AUTHENTICATED but is not AUTHORIZED to access protected resources.
When user is NOT AUTHENTICATED, he is moved into form-login instead of access-denied-page.
-->
<sec:http access-denied-page="/access_denied.xhtml" use-expressions="true" auto-config="true" >
<sec:intercept-url pattern="/login" access="IS_AUTHENTICATED_ANONYMOUSLY" />
<sec:form-login login-page="/login.jsf"/>
<sec:intercept-url pattern="/secured/**" access="isAuthenticated()"/>
<sec:intercept-url pattern="/WEB-INF/faces/**" access="isAuthenticated()"/>
<sec:logout logout-url="/logout" logout-success-url="/secured/home" delete-cookies="JSESSIONID" />
<sec:session-management invalid-session-url="/secured/home">
<sec:concurrency-control error-if-maximum-exceeded="true" max-sessions="6"/>
</sec:session-management>
</sec:http>
<!--
manager responsible for loading user account with assigned roles
-->
<sec:authentication-manager alias="authenticationManager">
<sec:authentication-provider
user-service-ref="userVerificationService"/>
</sec:authentication-manager>
#Service
public class UserVerificationService implements UserDetailsService {
private HashMap<String, org.springframework.security.core.userdetails.User> users = new HashMap<String, org.springframework.security.core.userdetails.User>();
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
org.springframework.security.core.userdetails.User user = users.get(username);
if (user == null) {
throw new UsernameNotFoundException("UserAccount for name \""
+ username + "\" not found.");
}
return user;
}
#PostConstruct
public void init() {
// sample roles
Collection<GrantedAuthority> adminAuthorities = new ArrayList<GrantedAuthority>();
adminAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
Collection<GrantedAuthority> userAuthorities = new ArrayList<GrantedAuthority>();
adminAuthorities.add(new SimpleGrantedAuthority("ROLE_REGISTERED"));
boolean enabled = true;
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
// sample users with roles set
users.put("admin", new org.springframework.security.core.userdetails.User("admin", "admin", enabled, accountNonExpired,
credentialsNonExpired, accountNonLocked, adminAuthorities));
users.put("user", new org.springframework.security.core.userdetails.User("user", "user", enabled, accountNonExpired,
credentialsNonExpired, accountNonLocked, userAuthorities));
}
#Service
public class AuthenticationServiceImpl implements AuthenticateService {
#Resource(name = "authenticationManager")
private AuthenticationManager authenticationManager;
public boolean login(String username, String password) {
try {
System.out.println("inside login");
System.out.println("AuthenticationServiceImpl user name " +username +" Pass = "+password);
Authentication authenticate = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(
username, password));
SecurityContextHolder.getContext().setAuthentication(authenticate);
HttpUtils.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext());
return true;
} catch (AuthenticationException e) {
e.printStackTrace();
}
return false;
}
Here is my loginBean
public String process() {
System.out.println("user name " + username + " Pass = " + password);
if (authenticateService.login(username, password)) {
return "pretty:home";
} else {
FacesUtils.addErrorMessage("Invalid UserName or Password");
return null;
}
}
From Spring 3.1 onwards, the User Credentials are being erased which usually causes some problems. I worked around this problem by turning off the said feature.
<bean id="authenticationManager" class="org.springframework.security.authentication.ProviderManager">
<property name="eraseCredentialsAfterAuthentication" value="false"/>
</bean>
If you are using namespaces, you may use
<authentication-manager erase-credentials="false">
Hi the problem I encountered is related to URL mapping which is quite confusing for me.
The project is "Jboss-Spring integration".
Project is started without error, but I keep getting these msg:
8:53:58,959 WARN [PageNotFound] No mapping found for HTTP request with URI [/frontend/portal/afasfas/asdsad] in DispatcherServlet with name 'NUSLibraries'
18:54:08,992 WARN [PageNotFound] No mapping found for HTTP request with URI [/frontend/portal/afasfas] in DispatcherServlet with name 'NUSLibraries'
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_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>frontend</display-name>
<welcome-file-list>
<welcome-file>index.xhtml</welcome-file>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</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-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.seam</url-pattern>
</servlet-mapping>
<context-param>
<param-name>org.richfaces.SKIN</param-name>
<param-value>blueSky</param-value>
</context-param>
<listener>
<listener-class>org.jboss.seam.servlet.SeamListener</listener-class>
</listener>
<filter>
<filter-name>Seam Filter</filter-name>
<filter-class>org.jboss.seam.servlet.SeamFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Seam Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>Seam Resource Servlet</servlet-name>
<servlet-class>org.jboss.seam.servlet.SeamResourceServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Seam Resource Servlet</servlet-name>
<url-pattern>/seam/resource/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>facelets.DEVELOPMENT</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>javax.faces.DEFAULT_SUFFIX</param-name>
<param-value>.xhtml</param-value>
</context-param>
<security-constraint>
<display-name>Restrict raw XHTML Documents</display-name>
<web-resource-collection>
<web-resource-name>XHTML</web-resource-name>
<url-pattern>*.xhtml</url-pattern>
</web-resource-collection>
<auth-constraint/>
</security-constraint>
<servlet>
<servlet-name>NUSLibraries</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>NUSLibraries</servlet-name>
<url-pattern>/portal/*</url-pattern>
</servlet-mapping>
</web-app>
servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:seam="http://jboss.com/products/seam/spring-seam"
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://jboss.com/products/seam/spring-seam
http://jboss.com/products/seam/spring-seam-2.2.xsd">
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="suffix">
<value>.xhtml</value>
</property>
</bean>
<!-- Controller -->
<bean id="SpringController" class="org.domain.frontend.controller.SpringController" scope="prototype">
<property name="portalStaticPage" ref="ActionPortalStaticPage">
</property>
</bean>
<seam:instance name="ActionPortalStaticPage" id="ActionPortalStaticPage" create="false"/>
<bean id="handlerMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<value>
/*/*/*=SpringController
</value>
</property>
</bean>
</beans>
SpringController
package org.domain.frontend.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.StringTokenizer;
import javax.persistence.NoResultException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.domain.frontend.session.ActionPortalStaticPage;
import org.jboss.seam.annotations.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.support.RequestContextUtils;
#Controller
#Transactional
public class SpringController{
static Logger log = Logger.getLogger("SpringController");
public ActionPortalStaticPage portalStaticPage;
public void setPortalStaticPage(ActionPortalStaticPage portalStaticPage) {
this.portalStaticPage = portalStaticPage;
}
#RequestMapping("/*/*/{param}")
public ModelAndView langzh(HttpServletRequest request, HttpServletResponse response, #PathVariable("param") String param) throws Exception {
List<String> params = new ArrayList<String>();
try{
log.info("param("+param+")");
StringTokenizer st = new StringTokenizer(param,"-");
while (st.hasMoreTokens()) {
params.add(st.nextToken());
}
portalStaticPage.setTitle(params.toString());
log.info("portalStaticPage("+portalStaticPage.getTitle()+")");
return new ModelAndView("index");
}
catch(Exception ex){
ex.printStackTrace();
return new ModelAndView(params.get(0));
}
}
}
Your handlerMapping seems unnecessarily complex. If you want to map all requests to a single controller, then just mark that as the default mapping:
<bean id="handlerMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="defaultHandler" value="SpringController"/>
</bean>