I managed to create a soap server and client that requires a username and password to call functions. The following code shows how i've done this
Client:
package hello;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.ws.client.support.interceptor.ClientInterceptor;
import org.springframework.ws.soap.security.xwss.XwsSecurityInterceptor;
import org.springframework.ws.soap.security.xwss.callback.SpringUsernamePasswordCallbackHandler;
#Configuration
public class SoftlayerConfiguration {
#Bean
public Jaxb2Marshaller marshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setContextPath("be.elision.soap.cloud");
return marshaller;
}
#Bean
public SoftlayerClient softlayerClient(Jaxb2Marshaller marshaller) {
SoftlayerClient client = new SoftlayerClient();
client.setDefaultUri("http://192.168.137.107:8080/ws");
client.setMarshaller(marshaller);
client.setUnmarshaller(marshaller);
client.setInterceptors(new ClientInterceptor[]{securityInterceptor()});
return client;
}
#Bean
XwsSecurityInterceptor securityInterceptor() {
XwsSecurityInterceptor securityInterceptor = new XwsSecurityInterceptor();
securityInterceptor.setSecureRequest(true);
securityInterceptor.setValidateRequest(true);
securityInterceptor.setCallbackHandler(callbackHandler());
securityInterceptor.setPolicyConfiguration(new ClassPathResource("securityPolicy.xml"));
return securityInterceptor;
}
#Bean
SpringUsernamePasswordCallbackHandler callbackHandler() {
SecurityContextHolder.setContext(new SecurityContextImpl());
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken("user", "password"));
return new SpringUsernamePasswordCallbackHandler();
}
}
Server:
package be.elision.main;
import java.util.Collections;
import java.util.List;
import org.springframework.boot.context.embedded.ServletRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.ws.config.annotation.EnableWs;
import org.springframework.ws.config.annotation.WsConfigurerAdapter;
import org.springframework.ws.server.EndpointInterceptor;
import org.springframework.ws.server.endpoint.interceptor.PayloadLoggingInterceptor;
import org.springframework.ws.soap.security.xwss.XwsSecurityInterceptor;
import org.springframework.ws.soap.security.xwss.callback.SimplePasswordValidationCallbackHandler;
import org.springframework.ws.soap.server.endpoint.interceptor.PayloadValidatingInterceptor;
import org.springframework.ws.transport.http.MessageDispatcherServlet;
import org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition;
import org.springframework.xml.xsd.SimpleXsdSchema;
import org.springframework.xml.xsd.XsdSchema;
#EnableWs
#Configuration
public class WebServiceConfig extends WsConfigurerAdapter {
#Bean
public ServletRegistrationBean messageDispatcherServlet(
ApplicationContext applicationContext) {
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(applicationContext);
servlet.setTransformWsdlLocations(true);
return new ServletRegistrationBean(servlet, "/ws/*");
}
#Bean(name = "devices")
public DefaultWsdl11Definition defaultWsdl11Definition(
XsdSchema devicesSchema) {
DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
wsdl11Definition.setPortTypeName("DevicesPort");
wsdl11Definition.setLocationUri("/ws");
wsdl11Definition.setTargetNamespace("http://elision.be/soap/cloud");
wsdl11Definition.setSchema(devicesSchema);
return wsdl11Definition;
}
// toevoegen van xsd aan bean
#Bean
public XsdSchema devicesSchema() {
return new SimpleXsdSchema(new ClassPathResource("devices.xsd"));
}
#Bean
XwsSecurityInterceptor securityInterceptor() {
XwsSecurityInterceptor securityInterceptor = new XwsSecurityInterceptor();
securityInterceptor.setCallbackHandler(callbackHandler());
securityInterceptor.setPolicyConfiguration(new ClassPathResource(
"securityPolicy.xml"));
return securityInterceptor;
}
#Bean
SimplePasswordValidationCallbackHandler callbackHandler() {
SimplePasswordValidationCallbackHandler callbackHandler = new SimplePasswordValidationCallbackHandler();
callbackHandler.setUsersMap(Collections
.singletonMap("user", "password"));
return callbackHandler;
}
#Bean
PayloadLoggingInterceptor payloadLoggingInterceptor() {
return new PayloadLoggingInterceptor();
}
#Bean
PayloadValidatingInterceptor payloadValidatingInterceptor() {
final PayloadValidatingInterceptor payloadValidatingInterceptor = new PayloadValidatingInterceptor();
payloadValidatingInterceptor.setSchema(new ClassPathResource(
"devices.xsd"));
return payloadValidatingInterceptor;
}
#Override
public void addInterceptors(List<EndpointInterceptor> interceptors) {
interceptors.add(payloadLoggingInterceptor());
interceptors.add(payloadValidatingInterceptor());
interceptors.add(securityInterceptor());
}
}
Security policy:
<xwss:SecurityConfiguration xmlns:xwss="http://java.sun.com/xml/ns/xwss/config">
<xwss:UsernameToken digestPassword="false" useNonce="false" />
</xwss:SecurityConfiguration>
But now i want to replace this username and password authentication with a certificate. I prefere not to do this in xml, but rather implement this in my existing code as shown above.
We finaly figured this out some months ago, from what I remember our configuration looked like this.
add this to your web.xml
<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>
this needs to be present in your 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" 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
http://www.springframework.org/schema/web-services
http://www.springframework.org/schema/web-services/web-services-2.0.xsd">
<context:component-scan base-package="com.yourpackage" />
<bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory" />
<bean id="webServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
<constructor-arg ref="messageFactory" />
<property name="defaultUri"
value="${backend.ip}devices" />
<property name="interceptors">
<list>
<ref local="xwsSecurityInterceptor" />
</list>
</property>
</bean>
<bean id="xwsSecurityInterceptor"
class="org.springframework.ws.soap.security.xwss.XwsSecurityInterceptor">
<property name="policyConfiguration" value="/WEB-INF/securityPolicy.xml" />
<property name="callbackHandlers">
<list>
<ref bean="keyStoreHandler" />
</list>
</property>
</bean>
<bean id="keyStore"
class="org.springframework.ws.soap.security.support.KeyStoreFactoryBean">
<property name="password" value="yourpassword" />
<property name="location" value="/WEB-INF/yourkeystore.jks" />
</bean>
<bean id="keyStoreHandler"
class="org.springframework.ws.soap.security.xwss.callback.KeyStoreCallbackHandler">
<property name="keyStore" ref="keyStore" />
<property name="privateKeyPassword" value="yourpassword" />
<property name="defaultAlias" value="client" />
</bean>
<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>
<!-- LOAD PROPERTIES -->
<context:property-placeholder
location="WEB-INF/config.properties"
ignore-unresolvable="true" />
<mvc:resources mapping="/resources/**" location="/resources/" />
<mvc:annotation-driven />
</beans>
The jks file is a java keystore file wich holds your certificate.
SecurityPolicy.xml
<xwss:SecurityConfiguration dumpMessages="true" xmlns:xwss="http://java.sun.com/xml/ns/xwss/config">
<xwss:Sign includeTimestamp="true">
<xwss:X509Token certificateAlias="yourcertificatealias" />
</xwss:Sign>
</xwss:SecurityConfiguration>
This is all done using the xws-security library from oracle, you need the following dependency for this.
<dependency>
<groupId>com.sun.xml.wss</groupId>
<artifactId>xws-security</artifactId>
<version>3.0</version>
<exclusions>
<exclusion>
<groupId>javax.xml.crypto</groupId>
<artifactId>xmldsig</artifactId>
</exclusion>
</exclusions>
</dependency>
We finnaly got this working after we found some good explanation about certificate authentication in this awesome book!
'Spring Web Services 2 Cookbook by Hamidreza Sattari'
If you have any further questions regarding this implementation then just ask away! :d
Related
i want to have something like a plugin system for Spring which are accessible through an REST endpoint.
So I was thinking I could simply implement a controller module as #RestController bean and add it to my beans definition.
Unfortunately I cannot figure out how to configure a #RestController and #RequestMapping using XML.
So far I think I have configured the a
This is my main class:
package me.example.app;
import org.springframework.context.ApplicationContext;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.context.annotation.*;
import java.lang.System;
import java.util.Properties;
#SpringBootApplication
#RestController
#ImportResource({"classpath:applicationContext.xml"})
public class GettingstartedApplication {
public GettingstartedApplication() {
System.out.println("INIT Application");
}
#RequestMapping("/")
String home() {
return "Hello World!";
}
public static void main(String[] args) {
ApplicationContext applicationContext = SpringApplication.run(GettingstartedApplication.class, args);
}
}
This is my resources/applicationContext.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:util="http://www.springframework.org/schema/util" xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<bean id="xmlStringBean1" class="java.lang.String">
<constructor-arg value="stringBean1" />
</bean>
<bean id="xmlController" class="me.tom.app.XMLController">
<constructor-arg value="xmlControllerArg" />
</bean>
<bean id="testSimpleUrlHandlerMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<util:map id="emails" map-class="java.util.HashMap">
<entry key="/xml" value="xmlController"/>
</util:map>
</property>
</bean>
</beans>
This is my XMLController.java
package me.example.app;
public class XMLController{
public XMLController(String arg) {
System.out.println("INIT XMLController");
}
String home() {
return "XMLController";
}
}
I'm struggling to implement a WatchServiceDirectoryScanner. I want to use the scanner to monitor new file uploads to a directory + sub directories. This will exist as part of a Spring boot MVC microservice. I can do this using Java 7's WatchService but would prefer a spring file integration style, AOP style
I have it registered as a #Bean in my app config but I'm struggling to figure out how to have it poll and scan a directory and then call... something (a message endpoint?) when a file is detected. Is anyone able to point me in the right direction for even conceptually how this is done. I cannot find an example implementation of this anywhere.
http://docs.spring.io/spring-integration/reference/html/files.html#_watchservicedirectoryscanner
http://docs.spring.io/spring-integration/api/org/springframework/integration/file/DefaultDirectoryScanner.html#listFiles-java.io.File-
here is my Spring appConfig:
public class appConfig {
#Bean
public DirectoryScanner scanner() {
return new WatchServiceDirectoryScanner("/uploads/test");
}
}
# create one configuration file and bind an input file channel here
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:int-file="http://www.springframework.org/schema/integration/file"
xmlns:int-mail="http://www.springframework.org/schema/integration/mail"
xmlns:int-stream="http://www.springframework.org/schema/integration/stream"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/integration/mail http://www.springframework.org/schema/integration/mail/spring-integration-mail.xsd
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/integration/file http://www.springframework.org/schema/integration/file/spring-integration-file.xsd
http://www.springframework.org/schema/integration/stream http://www.springframework.org/schema/integration/stream/spring-integration-stream.xsd
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">
<int:annotation-config />
<int:channel id="cfpFileIn"></int:channel>
<int-file:inbound-channel-adapter id="cfpFileIn"
directory="${cfp.flight.data.dir}" auto-startup="true" scanner="csvDirScanner">
<int:poller fixed-delay="${cfp.flight.data.dir.polling.delay}"></int:poller>
</int-file:inbound-channel-adapter>
<bean id="csvDirScanner"
class="org.springframework.integration.file.WatchServiceDirectoryScanner">
<constructor-arg index="0" value="${cfp.flight.data.dir}" />
<property name="filter" ref="csvCompositeFilter" />
<property name="autoStartup" value="true" />
</bean>
<bean id="csvCompositeFilter"
class="org.springframework.integration.file.filters.CompositeFileListFilter">
<constructor-arg>
<list>
<bean
class="org.springframework.integration.file.filters.SimplePatternFileListFilter">
<constructor-arg value="*.csv" />
</bean>
<ref bean="persistentFilter" />
</list>
</constructor-arg>
</bean>
<bean id="persistentFilter"
class="org.springframework.integration.file.filters.FileSystemPersistentAcceptOnceFileListFilter">
<constructor-arg index="0" ref="metadataStore" />
<constructor-arg index="1" name="prefix" value="" />
<property name="flushOnUpdate" value="true" />
</bean>
<bean name="metadataStore"
class="org.springframework.integration.metadata.PropertiesPersistingMetadataStore">
<property name="baseDirectory" value="${metadata.dir}"></property>
</bean>
</beans>
import java.io.File;
import java.util.concurrent.locks.ReentrantLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.JobParametersInvalidException;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.stereotype.Component;
#Component
public class BatchJobScheduler {
private static final Logger logger = LoggerFactory.getLogger(BatchJobScheduler.class);
#Autowired
protected JobLauncher jobLauncher;
#Autowired
#Qualifier(value = "job")
private Job job;
#ServiceActivator(inputChannel = "cfpFileIn")
public void run(File file) {
String fileName = file.getAbsolutePath();
logger.info("BatchJobScheduler Running #################"+fileName);
JobParameters jobParameters = new JobParametersBuilder().addString(
"input.file", fileName).toJobParameters();
try {
JobExecution execution = jobLauncher.run(job,
jobParameters);
logger.info(" BatchJobScheduler Exit Status : " + execution.getStatus() +"::"+execution.getAllFailureExceptions());
} catch (JobExecutionAlreadyRunningException | JobRestartException
| JobInstanceAlreadyCompleteException
| JobParametersInvalidException e) {
logger.error(" BatchJobScheduler Exit Status : Exception ::",e);
}
}
}
I am trying to implement a spring security in my project my requirements are
First user will login with url that will generate a secuirty code -
http://localhost:8181/SpringSecurity/login
After successfully loggedIn I hit secuired API call like -
http://localhost:8181/SpringSecurity/admin with secured key generated by login method
I am using crome postman to hit APIs
Although I am loggedIn with a user having ROLE_ADMIN but still it is not allow me to access secured APIs
my web.xml is
<?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">
<!-- 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/root-context.xml</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>
<!-- 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/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/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>
</web-app>
servlet-context.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:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<mvc:annotation-driven/>
<mvc:resources mapping="/resources/**" location="/resources/" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<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="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.ha.**"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">false</prop>
</props>
</property>
</bean>
<bean id="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<bean id="savedRequestAwareAuthenticationSuccessHandler"
class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
<property name="targetUrlParameter" value="targetUrl" />
</bean>
<context:component-scan base-package="com.ha.**" />
<bean id="jsonConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="prefixJson" value="false" />
<property name="supportedMediaTypes" value="application/json" />
</bean>
<import resource="../spring-security.xml"/>
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"
xmlns:context="http://www.springframework.org/schema/context"
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.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<security:global-method-security secured-annotations="enabled"/>
<http auto-config="true">
<intercept-url pattern="/admin**" access="ROLE_ADMIN" />
<custom-filter ref="tokenProcessingFilter" after="FORM_LOGIN_FILTER" />
</http>
<beans:bean
class="com.ha.security.AuthenticationTokenAndSessionProcessingFilter"
id="tokenProcessingFilter">
<beans:constructor-arg name="principal" value="ANONYMOUS" />
<beans:constructor-arg name="authority" value="anonymousUser" />
<beans:constructor-arg name="tokenStore" ref="inMemoryTokenStore" />
</beans:bean>
<beans:bean class="com.ha.security.InMemoryTokenStore" id="inMemoryTokenStore" />
<authentication-manager>
<authentication-provider>
<user-service>
<user name="hr" password="123456" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
Controller file is
package com.ha.security;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ha.model.UserEntity;
import com.ha.services.IUserService;
/**
* Handles requests for the application home page.
*/
#Controller
public class HomeController {
#Autowired
private InMemoryTokenStore tokenStore;
#Autowired
IUserService userServices;
/* #RequestMapping(value = { "/" }, method = RequestMethod.GET)
public String welcomePage() {
return "index";
} */
#RequestMapping(value = { "/", "/welcome**" }, method = RequestMethod.GET)
#Secured("ROLE_ADMIN")
public #ResponseBody String defaultPage() {
List<UserEntity> userEntity = userServices.getUsersList();
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
return gson.toJson(userEntity);
}
#RequestMapping(value = "/admin", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE })
#ResponseStatus(value = HttpStatus.OK)
#ResponseBody
public ResponseDto adminPage() {
return new ResponseDto("Can Access Admin");
}
#RequestMapping(value = "/login", method = RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_VALUE })
#ResponseStatus(value = HttpStatus.OK)
#ResponseBody
public ResponseDto login(#RequestBody UserLoginDto loginDto) {
String userName = loginDto.getUserName();
String password = loginDto.getPassword();
if (StringUtils.hasText(userName) && StringUtils.hasText(password)
&& userServices.validateAdminUser(loginDto)) {
ArrayList<GrantedAuthority> objAuthorities = new ArrayList<GrantedAuthority>();
SimpleGrantedAuthority objAuthority = new SimpleGrantedAuthority(
"ROLE_ADMIN");
objAuthorities.add(objAuthority);
User user = new User(userName, password, objAuthorities);
return new ResponseDto(this.tokenStore.generateAccessToken(user));
} else {
return new ResponseDto("Not Valid User");
}
}
}
AuthenticationTokenAndSessionProcessingFilter
package com.ha.security;
import java.io.IOException;
import java.util.List;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;
public class AuthenticationTokenAndSessionProcessingFilter extends
GenericFilterBean {
private final InMemoryTokenStore tokenStore;
private final Object principal;
private final List<GrantedAuthority> authorities;
public AuthenticationTokenAndSessionProcessingFilter(
InMemoryTokenStore tokenStore, String authority, String principal) {
this.tokenStore = tokenStore;
this.principal = principal;
this.authorities = AuthorityUtils.createAuthorityList(authority);
}
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (!(request instanceof HttpServletRequest)) {
throw new RuntimeException("Expecting a HTTP request");
}
HttpServletRequest httpRequest = (HttpServletRequest) request;
String authToken = null;
UserDetails objUserDetails = null;
if (StringUtils.hasText(httpRequest.getHeader("Authorization"))) {
authToken = httpRequest.getHeader("Authorization");
objUserDetails = this.tokenStore
.readAccessToken(authToken);
}
setAuthentication(objUserDetails, httpRequest);
chain.doFilter(request, response);
}
private void setAuthentication(UserDetails objUserDetails,
HttpServletRequest request) {
UsernamePasswordAuthenticationToken authentication = null;
if (null != objUserDetails) {
authentication = new UsernamePasswordAuthenticationToken(
objUserDetails, null, objUserDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource()
.buildDetails(request));
SecurityContextHolder.getContext()
.setAuthentication(authentication);
} else {
authentication = new UsernamePasswordAuthenticationToken(
this.principal, null, this.authorities);
SecurityContextHolder.getContext()
.setAuthentication(authentication);
}
}
}
I believe you need to use hasRole method
<intercept-url pattern="/admin**" access="hasRole('ROLE_ADMIN')" />
And also I noticed that you have only one user in your users list with role "ROLE_USER" hope you have added the admin user as well.
Thanks for your support, Problem get solved now and It was with importing style of security action. I was importing securty xml file multiple times
I had import securty in
web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/spring-security.xml
</param-value>
</context-param>
as well as in spring-context.xml file
<import resource="../spring-security.xml"/>
due to that multiple instances creted of inMemoryTokenStore and while validating it checking user token with different one.
After removed entry from spring-context.xml and adding following qualifer in HomeController my code is working fine
#Qualifier("inMemoryTokenStore")
private InMemoryTokenStore tokenStore;
Thanks evertybuddy....:)
I am using spring framework and for database I am using hibernate.cfg.xml in the following way
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">false</property>
<property name="hbm2ddl.auto">update</property>
<mapping class="com.lynas.test.Student" />
</session-factory>
</hibernate-configuration>
Now is there any way to write this code in the java file. Like a bean or something??
The Answer is YES. from http://java.dzone.com/articles/springhibernate-application
package com.sivalabs.springmvc.config;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.HibernateTransactionManager;
import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean;
import org.springframework.orm.hibernate3.support.IdTransferringMergeEventListener;
import org.springframework.transaction.annotation.AnnotationTransactionAttributeSource;
import org.springframework.transaction.interceptor.TransactionAttributeSource;
import org.springframework.transaction.interceptor.TransactionInterceptor;
/**
* #author SivaLabs
*
*/
#Configuration
public class RepositoryConfig
{
//${jdbc.driverClassName}
#Value("${jdbc.driverClassName}") private String driverClassName;
#Value("${jdbc.url}") private String url;
#Value("${jdbc.username}") private String username;
#Value("${jdbc.password}") private String password;
#Value("${hibernate.dialect}") private String hibernateDialect;
#Value("${hibernate.show_sql}") private String hibernateShowSql;
#Value("${hibernate.hbm2ddl.auto}") private String hibernateHbm2ddlAuto;
#Bean()
public DataSource getDataSource()
{
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName(driverClassName);
ds.setUrl(url);
ds.setUsername(username);
ds.setPassword(password);
return ds;
}
#Bean
#Autowired
public HibernateTransactionManager transactionManager(SessionFactory sessionFactory)
{
HibernateTransactionManager htm = new HibernateTransactionManager();
htm.setSessionFactory(sessionFactory);
return htm;
}
#Bean
#Autowired
public HibernateTemplate getHibernateTemplate(SessionFactory sessionFactory)
{
HibernateTemplate hibernateTemplate = new HibernateTemplate(sessionFactory);
return hibernateTemplate;
}
#Bean
public AnnotationSessionFactoryBean getSessionFactory()
{
AnnotationSessionFactoryBean asfb = new AnnotationSessionFactoryBean();
asfb.setDataSource(getDataSource());
asfb.setHibernateProperties(getHibernateProperties());
asfb.setPackagesToScan(new String[]{"com.sivalabs"});
return asfb;
}
#Bean
public Properties getHibernateProperties()
{
Properties properties = new Properties();
properties.put("hibernate.dialect", hibernateDialect);
properties.put("hibernate.show_sql", hibernateShowSql);
properties.put("hibernate.hbm2ddl.auto", hibernateHbm2ddlAuto);
return properties;
}
}
A more modern, working solution:
#Configuration
#ComponentScan(basePackageClasses = {массив пакетов с классами #Component, #Service, #Repository, #Controller})
#EnableTransactionManagement
#EnableJpaRepositories(basePackages = "com.jdev.blog.admin.crud.repositories", entityManagerFactoryRef = "entityManagerFactory")
public class ApplicationConfiguration {
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
dataSource.setUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
return dataSource;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource());
entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
entityManagerFactoryBean.setJpaProperties(hibProperties());
return entityManagerFactoryBean;
}
private Properties hibProperties() {
Properties properties = new Properties();
properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
return properties;
}
#Bean
public JpaTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
}
NO the above database configration cannot be moved to a java file BUT can be moved to dispactcher servelet.Actually that whole hibernate.cfg.xml is not required from spring 2.5 version upwards.
You can do the set up of the hibernate properties inside the dispatcher servlet like this. The below code uses mysql dialect so replace it with your requirement also replace name of the database,username and password of the database.
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jee="http://www.springframework.org/schema/jee" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-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.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd">
<context:component-scan base-package="com.c.controllers" />
<context:component-scan base-package="com.c.service" />
<context:component-scan base-package="com.c.dao" />
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="myDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="url">
<value>jdbc:mysql://localhost:3306/"your database name"</value>
</property>
<property name="username">
<value>"insert username here"</value>
</property>
<property name="password">
<value>"insert password here"</value>
</property>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="myDataSource" />
</property>
<property name="annotatedClasses">
<list>
<value>com.c.beans.Employee</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
I've inherited a Spring 3 app that uses XML files to define and wire together the beans. I know that since Spring 2 these can mostly be replaced with annotations. I would like Spring to:
detect beans by scanning certain packages for classes with whatever annotation is used to indicate a Spring bean
attempt to autowire-by-name and field in a bean that I have marked with the relevant annotation
What are steps I need to take to make this happen?
The manual has all the info you need: http://static.springsource.org/spring/docs/3.1.0.M1/spring-framework-reference/html/beans.html#beans-annotation-config
The TL;DR version is that you need to add <context:annotation-config/> to your spring config and then annotate your beans with #Component and in your setter of properties annotate with #Autowired
I shall give you a xml configuration with it anotation based config equivalent respectively, so that you will easily see how to change your bean from xml to java and vice-versa
`<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<context:component-scan base-package="com.mycompany.backendhibernatejpa.controller" />
<mvc:annotation-driven />
<bean id="iAbonneDao" class="com.mycompany.backendhibernatejpa.daoImpl.AbonneDaoImpl"/>
<bean id="iAbonneService" class="com.mycompany.backendhibernatejpa.serviceImpl.AbonneServiceImpl"/>
<!-- couche de persistance JPA -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="databasePlatform" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
<property name="generateDdl" value="true" />
<property name="showSql" value="true" />
</bean>
</property>
<property name="loadTimeWeaver">
<bean
class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
</bean>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="classpath:bd.properties"/>
</bean>
<!-- la source de donnéees DBCP -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" >
<property name="driverClassName" value="${bd.driver}" />
<property name="url" value="${bd.url}" />
<property name="username" value="${bd.username}" />
<property name="password" value="${bd.password}" />
</bean>
<!-- le gestionnaire de transactions -->
<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- traduction des exceptions -->
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<!-- annotations de persistance -->
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
</beans>`
this file is named springrest-sevlet. actually you can give the name
you want followed by "-servlet" and mention that name in the file
web.xml
` <web-app>
<display-name>Gescable</display-name>
<servlet>
<servlet-name>springrest</servlet-name>
<servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springrest</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>`
the two files should be place in the folder "WEB-INF".
Now the equivalent with anotation based config
`/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.backendhibernatejpaannotation.configuration;
import com.mycompany.backendhibernatejpaannotation.daoImpl.AbonneDaoImpl;
import com.mycompany.backendhibernatejpaannotation.daoInterface.IAbonneDao;
import com.mycompany.backendhibernatejpaannotation.serviceImpl.AbonneServiceImpl;
import com.mycompany.backendhibernatejpaannotation.serviceInterface.IAbonneService;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
/**
*
* #author vivien saa
*/
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.mycompany.backendhibernatejpaannotation")
public class RestConfiguration {
#Bean
public IAbonneDao iAbonneDao() {
return new AbonneDaoImpl();
}
#Bean
public IAbonneService iAbonneService() {
return new AbonneServiceImpl();
}
// #Bean
// public PropertyPlaceholderConfigurer placeholderConfigurer() {
// PropertyPlaceholderConfigurer placeholderConfigurer = new PropertyPlaceholderConfigurer();
// placeholderConfigurer.setLocations("classpath:bd.properties");
// return placeholderConfigurer;
// }
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/gescable");
dataSource.setUsername("root");
dataSource.setPassword("root");
return dataSource;
}
#Bean
public HibernateJpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
jpaVendorAdapter.setDatabasePlatform("org.hibernate.dialect.MySQL5InnoDBDialect");
jpaVendorAdapter.setGenerateDdl(true);
jpaVendorAdapter.setShowSql(true);
return jpaVendorAdapter;
}
#Bean
public InstrumentationLoadTimeWeaver loadTimeWeaver() {
InstrumentationLoadTimeWeaver loadTimeWeaver = new InstrumentationLoadTimeWeaver();
return loadTimeWeaver;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
entityManagerFactory.setDataSource(dataSource());
entityManagerFactory.setJpaVendorAdapter(jpaVendorAdapter());
entityManagerFactory.setLoadTimeWeaver(loadTimeWeaver());
return entityManagerFactory;
}
#Bean
public JpaTransactionManager jpaTransactionManager() {
JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
jpaTransactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return jpaTransactionManager;
}
#Bean
public PersistenceExceptionTranslationPostPro`enter code here`cessor persistenceExceptionTranslationPostProcessor() {
return new PersistenceExceptionTranslationPostProcessor();
}
#Bean
public PersistenceAnnotationBeanPostProcessor persistenceAnnotationBeanPostProcessor() {
return new PersistenceAnnotationBeanPostProcessor();
}
}`
this file must be accompanied by this one
`
package com.mycompany.backendhibernatejpaannotation.configuration;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
/**
*
* #author vivien saa
*/
public class Initializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{RestConfiguration.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
`
I think the first thing to do is to go slow. Just pick one service at a time and migrate it as you have cause to touch it. Mucking with a ton of spring config is a sure way screw yourself in production with a dependency you only need once in a while.