Spring Login Error Handling Additional changes -

Properties files and jsps
This commit is contained in:
egmp777 2014-07-22 18:02:11 -05:00
parent b27187d120
commit 7cda135e70
35 changed files with 1271 additions and 37 deletions

15
bin/.springBeans Normal file
View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<beansProjectDescription>
<version>1</version>
<pluginVersion><![CDATA[3.5.1.201404300732-RELEASE]]></pluginVersion>
<configSuffixes>
<configSuffix><![CDATA[xml]]></configSuffix>
</configSuffixes>
<enableImports><![CDATA[true]]></enableImports>
<configs>
</configs>
<autoconfigs>
</autoconfigs>
<configSets>
</configSets>
</beansProjectDescription>

179
bin/pom.xml Normal file
View File

@ -0,0 +1,179 @@
<?xml version="1.0" encoding="UTF-8"?>
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.baeldung</groupId>
<artifactId>spring-security-login-error-handling</artifactId>
<name>spring-security-login-error-handling</name>
<packaging>war</packaging>
<version>1.0.0-BUILD-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.1.4.RELEASE</version>
</parent>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<exclusions>
<!-- Exclude Commons Logging in favor of SLF4j -->
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<scope>runtime</scope>
</dependency>
<!-- AspectJ -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
</dependency>
<!-- Validation -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
<!-- logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<!-- <scope>runtime</scope> -->
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<!-- <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>
</dependency>
<!-- @Inject -->
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!-- Taglibs -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
</dependency>
<!-- Test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>spring-security-login-and-registration</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>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
</plugin>
</plugins>
</build>
<properties>
<java-version>1.7</java-version>
<org.springframework-version>3.1.1.RELEASE</org.springframework-version>
<org.springframework.security.version>3.2.4.RELEASE</org.springframework.security.version>
<org.aspectj-version>1.6.10</org.aspectj-version>
<!-- logging -->
<org.slf4j.version>1.7.6</org.slf4j.version>
<logback.version>1.1.1</logback.version>
</properties>
</project>

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,9 @@
message.username=Username required
message.password=Password required
message.unauth=Unauthorized Access !!
message.badCredentials=Invalid Username or Password
message.sessionExpired=Session Timed Out
message.logoutError=Sorry, error logging out
message.logoutSucc=You logged out successfully
message.regSucc=You registrated correctly, please log in
message.regError=There was a registration error please go back to registration

View File

@ -0,0 +1,9 @@
message.username=Por favor ingrese el nombre de usuario
message.password=Por favor ingrese una clave
message.unauth=Acceso denegado !!
message.badCredentials=Usuario o clave invalida
message.sessionExpired=La sesion expiro
message.logoutError=Lo sentimos, hubo problemas en logout
message.logoutSucc=Logout con exito
message.regSucc=Se registro correctamente, por favor ingrese
message.regError=Hubo un error, por favor vuelva a registrarse

View File

@ -0,0 +1,36 @@
<?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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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 use-expressions="true">
<intercept-url pattern="/login*" access="permitAll" />
<intercept-url pattern="/logout*" access="permitAll" />
<intercept-url pattern="/registration*" access="permitAll" />
<intercept-url pattern="/resources/**" access="permitAll" />
<intercept-url pattern="/invalidSession*" access="isAnonymous()" />
<intercept-url pattern="/**" access="isAuthenticated()" />
<form-login login-page='/login.html'
authentication-failure-url="/login.html?error=true"
authentication-success-handler-ref="myAuthenticationSuccessHandler"
default-target-url="/homepage.html" />
<session-management invalid-session-url="/invalidSession.html"
session-fixation-protection="none" />
<logout invalidate-session="false" logout-success-url="/logout.html?logSucc=1"
logout-url="/j_spring_security_logout" delete-cookies="JSESSIONID" />
</http>
<beans:bean id="myAuthenticationSuccessHandler"
class="org.baeldung.security.MySimpleUrlAuthenticationSuccessHandler" />
<authentication-manager>
<authentication-provider>
<user-service>
<user name="user1" password="user1Pass" authorities="ROLE_USER" />
<user name="admin1" password="admin1Pass" authorities="ROLE_ADMIN" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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,23 @@
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<html>
<sec:authorize ifAnyGranted="ROLE_USER">
<spring:message code="message.unauth" ></spring:message>
</sec:authorize>
<head></head>
<body>
<head></head>
<sec:authorize ifAnyGranted="ROLE_ADMIN">
<H1> Hello Admin</H1>
</sec:authorize>
<a href="<c:url value="/j_spring_security_logout" />">Logout</a>
<a href="<c:url value="/home.html" />">Home</a>
</body>
</html>

View File

@ -0,0 +1,23 @@
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
<html>
<head></head>
<body>
<h1>This is the landing page for the admin</h1>
<security:authorize access="hasRole('ROLE_USER')">
This text is only visible to a user
<br/>
</security:authorize>
<security:authorize access="hasRole('ROLE_ADMIN')">
This text is only visible to an admin
<br/>
</security:authorize>
<a href="<c:url value="/j_spring_security_logout" />">Logout</a>
<a href="<c:url value="/admin.html" />">Administrator Page</a>
</body>
</html>

View File

@ -0,0 +1,13 @@
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="true" %>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>
Welcome back home!
</h1>
</body>
</html>

View File

@ -0,0 +1,28 @@
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<%@ page session="true" %>
<html>
<head></head>
<body>
<body>
<h1>This is the homepage for the user</h1>
<sec:authorize access="hasRole('ROLE_USER')">
This text is only visible to a user
<br />
</sec:authorize>
<sec:authorize access="hasRole('ROLE_ADMIN')">
This text is only visible to an admin
<br />
</sec:authorize>
<a href="<c:url value="/j_spring_security_logout" />">Logout</a>
<a href="<c:url value="/home.html" />">Home</a>
<a href="<c:url value="/admin.html" />">Administrator Page</a>
</body>
</body>
</html>

View File

@ -0,0 +1,12 @@
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>
<spring:message code="message.sessionExpired" ></spring:message>
</h1>
</body>
</html>

View File

@ -0,0 +1,77 @@
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="sec"
uri="http://www.springframework.org/security/tags"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<fmt:setBundle basename="messages" />
<%@ page session="false"%>
<c:if test="${param.error != null}">
<div id="error">
<spring:message code="message.badCredentials"></spring:message>
</div>
</c:if>
<c:if test="${param.regSucc == 1}">
<div id="error">
<spring:message code="message.regSucc"></spring:message>
</div>
</c:if>
<c:if test="${param.regError == 1}">
<div id="error">
<spring:message code="message.regError"></spring:message>
</div>
<a href="registration.html">Register</a>
</c:if>
<fmt:message key="message.password" var="noPass" />
<fmt:message key="message.username" var="noUser" />
<html>
<head>
<script type="text/javascript">
function validate() {
if (document.f.j_username.value == ""
&& document.f.j_password.value == "") {
alert("${noUser} & ${noPass}");
document.f.j_username.focus();
return false;
}
if (document.f.j_username.value == "") {
alert("${noUser}");
document.f.j_username.focus();
return false;
}
if (document.f.j_password.value == "") {
alert("${noPass}");
document.f.j_password.focus();
return false;
}
}
</script>
</head>
<body>
<h1>Login</h1>
<a href="?lang=en">English</a> |
<a href="?lang=es_ES">Spanish</a>
<form name='f' action="j_spring_security_check" method='POST'
onsubmit="return validate();">
<table>
<tr>
<td>User:</td>
<td><input type='text' name='j_username' value=''></td>
</tr>
<tr>
<td>Password:</td>
<td><input type='password' name='j_password' /></td>
</tr>
<tr>
<td><input name="submit" type="submit" value="submit" /></td>
</tr>
</table>
</form>
<br> Current Locale : ${pageContext.response.locale}
</body>
</html>

View File

@ -0,0 +1,24 @@
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="sec"
uri="http://www.springframework.org/security/tags"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<c:if test="${not empty SPRING_SECURITY_LAST_EXCEPTION}">
<div id="error">
<spring:message code="message.logoutError"></spring:message>
</div>
</c:if>
<c:if test="${param.logSucc == 1}">
<div id="success">
<spring:message code="message.logoutSucc"></spring:message>
</div>
</c:if>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Logged Out</title>
</head>
<body>
<a href="login.html">Login</a>
</body>
</html>

View File

@ -0,0 +1,12 @@
<%@ page language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Registration</title>
</head>
<body>
<H1> This is the registration page</H1>
</body>
</html>

View File

@ -0,0 +1,41 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<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>
<filter>
<filter-name>localizationFilter</filter-name>
<filter-class>org.springframework.web.filter.RequestContextFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>localizationFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

151
pom.xml
View File

@ -1,39 +1,116 @@
<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>parent</artifactId>
<version>0.1-SNAPSHOT</version>
<name>parent</name>
<packaging>pom</packaging>
<?xml version="1.0" encoding="UTF-8"?>
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.baeldung</groupId>
<artifactId>spring-security-login-and-registration</artifactId>
<name>spring-security-login-and-registration</name>
<packaging>war</packaging>
<version>1.0.0-BUILD-SNAPSHOT</version>
<modules>
<module>core-java</module>
<module>experiments</module>
<module>guava</module>
<module>httpclient</module>
<module>jackson</module>
<module>mockito</module>
<module>rest-testing</module>
<module>sandbox</module>
<module>spring-all</module>
<module>spring-exceptions</module>
<module>spring-hibernate3</module>
<module>spring-hibernate4</module>
<module>spring-jpa</module>
<module>spring-mvc-java</module>
<module>spring-mvc-no-xml</module>
<module>spring-mvc-xml</module>
<module>spring-rest</module>
<module>spring-security-basic-auth</module>
<module>spring-security-mvc-custom</module>
<module>spring-security-mvc-digest-auth</module>
<module>spring-security-mvc-login</module>
<module>spring-security-mvc-session</module>
<module>spring-security-rest</module>
<module>spring-security-rest-basic-auth</module>
<module>spring-security-rest-custom</module>
<module>spring-security-rest-digest-auth</module>
<module>spring-security-rest-full</module>
</modules>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.1.4.RELEASE</version>
</parent>
</project>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Validation -->
<!-- logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<!-- <scope>runtime</scope> -->
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<!-- <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>
</dependency>
<!-- @Inject -->
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>${javax.inject.version}</version>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>${javax.servlet.jsp-api.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!-- Taglibs -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
</dependency>
<!-- Test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>spring-security-login-and-registration</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<properties>
<java-version>1.7</java-version>
<org.springframework-version>3.1.1.RELEASE</org.springframework-version>
<org.springframework.security.version>3.2.4.RELEASE</org.springframework.security.version>
<org.aspectj-version>1.6.10</org.aspectj-version>
<!-- logging -->
<org.slf4j.version>1.7.6</org.slf4j.version>
<logback.version>1.1.1</logback.version>
<!-- javax jsp -->
<javax.servlet.jsp-api.version>2.3.2-b01</javax.servlet.jsp-api.version>
<!-- Inject -->
<javax.inject.version>1</javax.inject.version>
</properties>
</project>

View File

@ -0,0 +1,116 @@
<?xml version="1.0" encoding="UTF-8"?>
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.baeldung</groupId>
<artifactId>spring-security-login-and-registration</artifactId>
<name>spring-security-login-and-registration</name>
<packaging>war</packaging>
<version>1.0.0-BUILD-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.1.4.RELEASE</version>
</parent>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Validation -->
<!-- logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<!-- <scope>runtime</scope> -->
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<!-- <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>
</dependency>
<!-- @Inject -->
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>${javax.inject.version}</version>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>${javax.servlet.jsp-api.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!-- Taglibs -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
</dependency>
<!-- Test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>spring-security-login-and-registration</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<properties>
<java-version>1.7</java-version>
<org.springframework-version>3.1.1.RELEASE</org.springframework-version>
<org.springframework.security.version>3.2.4.RELEASE</org.springframework.security.version>
<org.aspectj-version>1.6.10</org.aspectj-version>
<!-- logging -->
<org.slf4j.version>1.7.6</org.slf4j.version>
<logback.version>1.1.1</logback.version>
<!-- javax jsp -->
<javax.servlet.jsp-api.version>2.3.2-b01</javax.servlet.jsp-api.version>
<!-- Inject -->
<javax.inject.version>1</javax.inject.version>
</properties>
</project>

View File

@ -0,0 +1,81 @@
package org.baeldung.security;
import java.io.IOException;
import java.util.Collection;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
private final Logger logger = LoggerFactory.getLogger(getClass());
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
handle(request, response, authentication);
HttpSession session = request.getSession(false);
if (session != null) {
session.setMaxInactiveInterval(30);
}
clearAuthenticationAttributes(request);
}
protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
String targetUrl = determineTargetUrl(authentication);
if (response.isCommitted()) {
logger.debug("Response has already been committed. Unable to redirect to " + targetUrl);
return;
}
redirectStrategy.sendRedirect(request, response, targetUrl);
}
protected String determineTargetUrl(Authentication authentication) {
boolean isUser = false;
boolean isAdmin = false;
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
for (GrantedAuthority grantedAuthority : authorities) {
if (grantedAuthority.getAuthority().equals("ROLE_USER")) {
isUser = true;
break;
} else if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) {
isAdmin = true;
break;
}
}
if (isUser) {
return "/homepage.html";
} else if (isAdmin) {
return "/console.html";
} else {
throw new IllegalStateException();
}
}
protected void clearAuthenticationAttributes(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session == null) {
return;
}
session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
}
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy;
}
protected RedirectStrategy getRedirectStrategy() {
return redirectStrategy;
}
}

View File

@ -0,0 +1,78 @@
package org.baeldung.spring;
import java.util.Locale;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
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("/login.html");
registry.addViewController("/logout.html");
registry.addViewController("/homepage.html");
registry.addViewController("/home.html");
registry.addViewController("/invalidSession.html");
registry.addViewController("/console.html");
registry.addViewController("/admin.html");
registry.addViewController("/registration.html");
}
@Bean
public ViewResolver viewResolver() {
final InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/view/");
bean.setSuffix(".jsp");
return bean;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("lang");
registry.addInterceptor(localeChangeInterceptor);
}
@Bean
public LocaleResolver localeResolver() {
CookieLocaleResolver cookieLocaleResolver = new CookieLocaleResolver();
cookieLocaleResolver.setDefaultLocale(Locale.ENGLISH);
return cookieLocaleResolver;
}
@Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("classpath:messages");
messageSource.setUseCodeAsDefaultMessage(true);
messageSource.setDefaultEncoding("UTF-8");
messageSource.setCacheSeconds(0);
return messageSource;
}
}

View File

@ -0,0 +1,14 @@
package org.baeldung.spring;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
@Configuration
@ImportResource({ "classpath:webSecurityConfig.xml" })
public class SecSecurityConfig {
public SecSecurityConfig() {
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,9 @@
message.username=Username required
message.password=Password required
message.unauth=Unauthorized Access !!
message.badCredentials=Invalid Username or Password
message.sessionExpired=Session Timed Out
message.logoutError=Sorry, error logging out
message.logoutSucc=You logged out successfully
message.regSucc=You registrated correctly, please log in
message.regError=There was a registration error please go back to registration

View File

@ -0,0 +1,9 @@
message.username=Por favor ingrese el nombre de usuario
message.password=Por favor ingrese una clave
message.unauth=Acceso denegado !!
message.badCredentials=Usuario o clave invalida
message.sessionExpired=La sesion expiro
message.logoutError=Lo sentimos, hubo problemas en logout
message.logoutSucc=Logout con exito
message.regSucc=Se registro correctamente, por favor ingrese
message.regError=Hubo un error, por favor vuelva a registrarse

View File

@ -0,0 +1,36 @@
<?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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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 use-expressions="true">
<intercept-url pattern="/login*" access="permitAll" />
<intercept-url pattern="/logout*" access="permitAll" />
<intercept-url pattern="/registration*" access="permitAll" />
<intercept-url pattern="/resources/**" access="permitAll" />
<intercept-url pattern="/invalidSession*" access="isAnonymous()" />
<intercept-url pattern="/**" access="isAuthenticated()" />
<form-login login-page='/login.html'
authentication-failure-url="/login.html?error=true"
authentication-success-handler-ref="myAuthenticationSuccessHandler"
default-target-url="/homepage.html" />
<session-management invalid-session-url="/invalidSession.html"
session-fixation-protection="none" />
<logout invalidate-session="false" logout-success-url="/logout.html?logSucc=1"
logout-url="/j_spring_security_logout" delete-cookies="JSESSIONID" />
</http>
<beans:bean id="myAuthenticationSuccessHandler"
class="org.baeldung.security.MySimpleUrlAuthenticationSuccessHandler" />
<authentication-manager>
<authentication-provider>
<user-service>
<user name="user1" password="user1Pass" authorities="ROLE_USER" />
<user name="admin1" password="admin1Pass" authorities="ROLE_ADMIN" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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,23 @@
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<html>
<sec:authorize ifAnyGranted="ROLE_USER">
<spring:message code="message.unauth" ></spring:message>
</sec:authorize>
<head></head>
<body>
<head></head>
<sec:authorize ifAnyGranted="ROLE_ADMIN">
<H1> Hello Admin</H1>
</sec:authorize>
<a href="<c:url value="/j_spring_security_logout" />">Logout</a>
<a href="<c:url value="/home.html" />">Home</a>
</body>
</html>

View File

@ -0,0 +1,23 @@
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
<html>
<head></head>
<body>
<h1>This is the landing page for the admin</h1>
<security:authorize access="hasRole('ROLE_USER')">
This text is only visible to a user
<br/>
</security:authorize>
<security:authorize access="hasRole('ROLE_ADMIN')">
This text is only visible to an admin
<br/>
</security:authorize>
<a href="<c:url value="/j_spring_security_logout" />">Logout</a>
<a href="<c:url value="/admin.html" />">Administrator Page</a>
</body>
</html>

View File

@ -0,0 +1,13 @@
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="true" %>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>
Welcome back home!
</h1>
</body>
</html>

View File

@ -0,0 +1,28 @@
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<%@ page session="true" %>
<html>
<head></head>
<body>
<body>
<h1>This is the homepage for the user</h1>
<sec:authorize access="hasRole('ROLE_USER')">
This text is only visible to a user
<br />
</sec:authorize>
<sec:authorize access="hasRole('ROLE_ADMIN')">
This text is only visible to an admin
<br />
</sec:authorize>
<a href="<c:url value="/j_spring_security_logout" />">Logout</a>
<a href="<c:url value="/home.html" />">Home</a>
<a href="<c:url value="/admin.html" />">Administrator Page</a>
</body>
</body>
</html>

View File

@ -0,0 +1,12 @@
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>
<spring:message code="message.sessionExpired" ></spring:message>
</h1>
</body>
</html>

View File

@ -0,0 +1,77 @@
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="sec"
uri="http://www.springframework.org/security/tags"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<fmt:setBundle basename="messages" />
<%@ page session="false"%>
<c:if test="${param.error != null}">
<div id="error">
<spring:message code="message.badCredentials"></spring:message>
</div>
</c:if>
<c:if test="${param.regSucc == 1}">
<div id="error">
<spring:message code="message.regSucc"></spring:message>
</div>
</c:if>
<c:if test="${param.regError == 1}">
<div id="error">
<spring:message code="message.regError"></spring:message>
</div>
<a href="registration.html">Register</a>
</c:if>
<fmt:message key="message.password" var="noPass" />
<fmt:message key="message.username" var="noUser" />
<html>
<head>
<script type="text/javascript">
function validate() {
if (document.f.j_username.value == ""
&& document.f.j_password.value == "") {
alert("${noUser} & ${noPass}");
document.f.j_username.focus();
return false;
}
if (document.f.j_username.value == "") {
alert("${noUser}");
document.f.j_username.focus();
return false;
}
if (document.f.j_password.value == "") {
alert("${noPass}");
document.f.j_password.focus();
return false;
}
}
</script>
</head>
<body>
<h1>Login</h1>
<a href="?lang=en">English</a> |
<a href="?lang=es_ES">Spanish</a>
<form name='f' action="j_spring_security_check" method='POST'
onsubmit="return validate();">
<table>
<tr>
<td>User:</td>
<td><input type='text' name='j_username' value=''></td>
</tr>
<tr>
<td>Password:</td>
<td><input type='password' name='j_password' /></td>
</tr>
<tr>
<td><input name="submit" type="submit" value="submit" /></td>
</tr>
</table>
</form>
<br> Current Locale : ${pageContext.response.locale}
</body>
</html>

View File

@ -0,0 +1,24 @@
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="sec"
uri="http://www.springframework.org/security/tags"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<c:if test="${not empty SPRING_SECURITY_LAST_EXCEPTION}">
<div id="error">
<spring:message code="message.logoutError"></spring:message>
</div>
</c:if>
<c:if test="${param.logSucc == 1}">
<div id="success">
<spring:message code="message.logoutSucc"></spring:message>
</div>
</c:if>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Logged Out</title>
</head>
<body>
<a href="login.html">Login</a>
</body>
</html>

View File

@ -0,0 +1,12 @@
<%@ page language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Registration</title>
</head>
<body>
<H1> This is the registration page</H1>
</body>
</html>

View File

@ -0,0 +1,41 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<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>
<filter>
<filter-name>localizationFilter</filter-name>
<filter-class>org.springframework.web.filter.RequestContextFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>localizationFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>