initial commit

This commit is contained in:
Adrian Milne 2014-06-04 16:33:02 +01:00
parent dd020af30a
commit 51b61e552e
22 changed files with 804 additions and 0 deletions

View File

@ -0,0 +1,12 @@
=========
## Spring Security with Basic Authentication Example Project
### Relevant Article:
- [Spring Security - security none, filters none, access permitAll](http://www.baeldung.com/security-none-filters-none-access-permitAll)
- [Spring Security Basic Authentication](http://www.baeldung.com/spring-security-basic-authentication)
### Notes
- the project includes both views as well as a REST layer

View File

@ -0,0 +1,266 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.baeldung</groupId>
<artifactId>spring-security-ldap</artifactId>
<version>0.1-SNAPSHOT</version>
<name>spring-security-ldap</name>
<packaging>war</packaging>
<dependencies>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${org.springframework.security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${org.springframework.security.version}</version>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org.springframework.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- web -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
<scope>runtime</scope>
</dependency>
<!-- util -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>14.0.1</version>
</dependency>
<!-- logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<!-- <scope>runtime</scope> -->
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
</dependency>
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit-dep</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>spring-security-mvc-basic-auth</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<!-- <exclude>**/*ProductionTest.java</exclude> -->
</excludes>
<systemPropertyVariables>
<!-- <provPersistenceTarget>h2</provPersistenceTarget> -->
</systemPropertyVariables>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<version>${cargo-maven2-plugin.version}</version>
<configuration>
<wait>true</wait>
<container>
<containerId>jetty8x</containerId>
<type>embedded</type>
<systemProperties>
<!-- <provPersistenceTarget>cargo</provPersistenceTarget> -->
</systemProperties>
</container>
<configuration>
<properties>
<cargo.servlet.port>8082</cargo.servlet.port>
</properties>
</configuration>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<!-- Spring -->
<org.springframework.version>4.0.5.RELEASE</org.springframework.version>
<org.springframework.security.version>3.2.4.RELEASE</org.springframework.security.version>
<!-- persistence -->
<hibernate.version>4.3.5.Final</hibernate.version>
<mysql-connector-java.version>5.1.30</mysql-connector-java.version>
<!-- logging -->
<org.slf4j.version>1.7.6</org.slf4j.version>
<logback.version>1.1.1</logback.version>
<!-- various -->
<hibernate-validator.version>5.1.1.Final</hibernate-validator.version>
<!-- util -->
<guava.version>17.0</guava.version>
<commons-lang3.version>3.3.2</commons-lang3.version>
<!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.11</junit.version>
<mockito.version>1.9.5</mockito.version>
<httpcore.version>4.3.2</httpcore.version>
<httpclient.version>4.3.3</httpclient.version>
<rest-assured.version>2.3.1</rest-assured.version>
<!-- Maven plugins -->
<maven-compiler-plugin.version>3.1</maven-compiler-plugin.version>
<maven-war-plugin.version>2.4</maven-war-plugin.version>
<maven-surefire-plugin.version>2.17</maven-surefire-plugin.version>
<maven-resources-plugin.version>2.6</maven-resources-plugin.version>
<cargo-maven2-plugin.version>1.4.8</cargo-maven2-plugin.version>
</properties>
</project>

View File

@ -0,0 +1,23 @@
package org.baeldung.persistence.service;
import org.baeldung.web.dto.Foo;
import org.springframework.stereotype.Service;
@Service
public class FooService {
public FooService() {
super();
}
// API
public Foo getById(final Long id) {
return null;
}
public Long create(final Foo resource) {
return null;
}
}

View File

@ -0,0 +1,31 @@
package org.baeldung.security.basic;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;
import org.springframework.stereotype.Component;
@Component
public class MyBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {
@Override
public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException) throws IOException, ServletException {
response.addHeader("WWW-Authenticate", "Basic realm=\"" + getRealmName() + "\"");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
final PrintWriter writer = response.getWriter();
writer.println("HTTP Status " + HttpServletResponse.SC_UNAUTHORIZED + " - " + authException.getMessage());
}
@Override
public void afterPropertiesSet() throws Exception {
setRealmName("Baeldung");
super.afterPropertiesSet();
}
}

View File

@ -0,0 +1,39 @@
package org.baeldung.spring;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
@Configuration
@EnableWebMvc
public class MvcConfig extends WebMvcConfigurerAdapter {
public MvcConfig() {
super();
}
// API
@Override
public void addViewControllers(final ViewControllerRegistry registry) {
super.addViewControllers(registry);
registry.addViewController("/homepage.html");
}
@Bean
public ViewResolver viewResolver() {
final InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/view/");
bean.setSuffix(".jsp");
return bean;
}
}

View File

@ -0,0 +1,14 @@
package org.baeldung.spring;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("org.baeldung.persistence")
public class PersistenceConfig {
public PersistenceConfig() {
super();
}
}

View File

@ -0,0 +1,16 @@
package org.baeldung.spring;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
@Configuration
@ImportResource({ "classpath:webSecurityConfig.xml" })
@ComponentScan("org.baeldung.security")
public class SecSecurityConfig {
public SecSecurityConfig() {
super();
}
}

View File

@ -0,0 +1,17 @@
package org.baeldung.spring;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
@ComponentScan("org.baeldung.web")
public class WebConfig extends WebMvcConfigurerAdapter {
public WebConfig() {
super();
}
// API
}

View File

@ -0,0 +1,74 @@
package org.baeldung.web.controller;
import java.net.URI;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.baeldung.persistence.service.FooService;
import org.baeldung.web.dto.Foo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
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 org.springframework.web.util.UriComponentsBuilder;
import org.springframework.web.util.UriTemplate;
import com.google.common.base.Preconditions;
@Controller
@RequestMapping(value = "/foo")
public class FooController {
@Autowired
private ApplicationEventPublisher eventPublisher;
@Autowired
private FooService service;
public FooController() {
super();
}
// API
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
public Foo findOne(@PathVariable("id") final Long id, final UriComponentsBuilder uriBuilder, final HttpServletResponse response) {
return new Foo();
}
@RequestMapping(value = "admin/foo/{id}", method = RequestMethod.GET)
@ResponseBody
public Foo get(@PathVariable("id") final Long id, final HttpServletRequest request, final HttpServletResponse response) {
final Foo resourceById = Preconditions.checkNotNull(service.getById(id));
eventPublisher.publishEvent(new SingleResourceRetrieved(this, request, response));
return resourceById;
}
@RequestMapping(value = "admin/foo", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public void create(@RequestBody final Foo resource, final HttpServletRequest request, final HttpServletResponse response) {
Preconditions.checkNotNull(resource);
final Long idOfCreatedResource = service.create(resource);
eventPublisher.publishEvent(new ResourceCreated(this, request, response, idOfCreatedResource));
}
@RequestMapping(value = "admin", method = RequestMethod.GET)
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public void adminRoot(final HttpServletRequest request, final HttpServletResponse response) {
final String rootUri = request.getRequestURL().toString();
final URI fooUri = new UriTemplate("{rootUri}/{resource}").expand(rootUri, "foo");
final String linkToFoo = LinkUtil.createLinkHeader(fooUri.toASCIIString(), "collection");
response.addHeader("Link", linkToFoo);
}
}

View File

@ -0,0 +1,30 @@
package org.baeldung.web.controller;
import javax.servlet.http.HttpServletResponse;
/**
* Provides some constants and utility methods to build a Link Header to be stored in the {@link HttpServletResponse} object
*/
public final class LinkUtil {
private LinkUtil() {
throw new AssertionError();
}
//
/**
* Creates a Link Header to be stored in the {@link HttpServletResponse} to provide Discoverability features to the user
*
* @param uri
* the base uri
* @param rel
* the relative path
*
* @return the complete url
*/
public static String createLinkHeader(final String uri, final String rel) {
return "<" + uri + ">; rel=\"" + rel + "\"";
}
}

View File

@ -0,0 +1,35 @@
package org.baeldung.web.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationEvent;
public class ResourceCreated extends ApplicationEvent {
private final HttpServletResponse response;
private final HttpServletRequest request;
private final long idOfNewResource;
public ResourceCreated(final Object source, final HttpServletRequest request, final HttpServletResponse response, final long idOfNewResource) {
super(source);
this.request = request;
this.response = response;
this.idOfNewResource = idOfNewResource;
}
// API
public HttpServletResponse getResponse() {
return response;
}
public HttpServletRequest getRequest() {
return request;
}
public long getIdOfNewResource() {
return idOfNewResource;
}
}

View File

@ -0,0 +1,35 @@
package org.baeldung.web.controller;
import java.net.URI;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.springframework.web.util.UriTemplate;
import com.google.common.base.Preconditions;
import com.google.common.net.HttpHeaders;
@Component
class ResourceCreatedDiscoverabilityListener implements ApplicationListener<ResourceCreated> {
@Override
public void onApplicationEvent(final ResourceCreated resourceCreatedEvent) {
Preconditions.checkNotNull(resourceCreatedEvent);
final HttpServletRequest request = resourceCreatedEvent.getRequest();
final HttpServletResponse response = resourceCreatedEvent.getResponse();
final long idOfNewResource = resourceCreatedEvent.getIdOfNewResource();
addLinkHeaderOnResourceCreation(request, response, idOfNewResource);
}
void addLinkHeaderOnResourceCreation(final HttpServletRequest request, final HttpServletResponse response, final long idOfNewResource) {
final String requestUrl = request.getRequestURL().toString();
final URI uri = new UriTemplate("{requestUrl}/{idOfNewResource}").expand(requestUrl, idOfNewResource);
response.setHeader(HttpHeaders.LOCATION, uri.toASCIIString());
}
}

View File

@ -0,0 +1,29 @@
package org.baeldung.web.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationEvent;
public class SingleResourceRetrieved extends ApplicationEvent {
private final HttpServletResponse response;
private final HttpServletRequest request;
public SingleResourceRetrieved(final Object source, final HttpServletRequest request, final HttpServletResponse response) {
super(source);
this.request = request;
this.response = response;
}
// API
public HttpServletResponse getResponse() {
return response;
}
public HttpServletRequest getRequest() {
return request;
}
}

View File

@ -0,0 +1,32 @@
package org.baeldung.web.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import com.google.common.base.Preconditions;
@Component
class SingleResourceRetrievedDiscoverabilityListener implements ApplicationListener<SingleResourceRetrieved> {
@Override
public void onApplicationEvent(final SingleResourceRetrieved resourceRetrievedEvent) {
Preconditions.checkNotNull(resourceRetrievedEvent);
final HttpServletRequest request = resourceRetrievedEvent.getRequest();
final HttpServletResponse response = resourceRetrievedEvent.getResponse();
addLinkHeaderOnSingleResourceRetrieval(request, response);
}
void addLinkHeaderOnSingleResourceRetrieval(final HttpServletRequest request, final HttpServletResponse response) {
final StringBuffer requestURL = request.getRequestURL();
final int positionOfLastSlash = requestURL.lastIndexOf("/");
final String uriForResourceCreation = requestURL.substring(0, positionOfLastSlash);
final String linkHeaderValue = LinkUtil.createLinkHeader(uriForResourceCreation, "collection");
response.addHeader("Link", linkHeaderValue);
}
}

View File

@ -0,0 +1,28 @@
package org.baeldung.web.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class TestController {
public TestController() {
super();
}
// API
@RequestMapping("/permitAll")
@ResponseBody
public String permitAll() {
return "Permit All";
}
@RequestMapping("/securityNone")
@ResponseBody
public String securityNone() {
return "Security None";
}
}

View File

@ -0,0 +1,11 @@
package org.baeldung.web.dto;
import java.io.Serializable;
public class Foo implements Serializable {
public Foo() {
super();
}
}

View File

@ -0,0 +1,20 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>web - %date [%thread] %-5level %logger{36} - %message%n
</pattern>
</encoder>
</appender>
<logger name="org.springframework" level="WARN" />
<logger name="org.springframework.transaction" level="WARN" />
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<http pattern="/securityNone" security="none" />
<http use-expressions="true">
<intercept-url pattern="/**" access="isAuthenticated()" />
<http-basic entry-point-ref="myBasicAuthenticationEntryPoint" />
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="user1" password="user1Pass" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
</beans>

View File

@ -0,0 +1,7 @@
<html>
<head></head>
<body>
<h1>This is the body of the sample view</h1>
</body>
</html>

View File

@ -0,0 +1,42 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Spring Security Basic Auth Application</display-name>
<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.baeldung.spring</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc</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>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

View File

@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear