Merge pull request #19 from corsoft/master
Initial commit of Persisted Remember-Me Example
This commit is contained in:
@@ -0,0 +1,16 @@
|
||||
# Eclipse
|
||||
.classpath
|
||||
.project
|
||||
.settings/
|
||||
|
||||
# Intellij
|
||||
.idea/
|
||||
*.iml
|
||||
*.iws
|
||||
|
||||
# Mac
|
||||
.DS_Store
|
||||
|
||||
# Maven
|
||||
log/
|
||||
target/
|
||||
@@ -0,0 +1,15 @@
|
||||
=========
|
||||
|
||||
## Spring Security Persisted Remember Me Example Project
|
||||
|
||||
|
||||
### Relevant Articles:
|
||||
- [Spring Security Persisted Remember Me]
|
||||
- [Spring Security Remember Me](http://www.baeldung.com/spring-security-remember-me)
|
||||
- [Redirect to different pages after Login with Spring Security](http://www.baeldung.com/spring_redirect_after_login)
|
||||
|
||||
|
||||
### Build the Project
|
||||
```
|
||||
mvn clean install
|
||||
```
|
||||
File diff suppressed because it is too large
Load Diff
+97
@@ -0,0 +1,97 @@
|
||||
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.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
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;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component(value="mySimpleUrlAuthenticationSuccessHandler")
|
||||
public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
|
||||
|
||||
private final Log logger = LogFactory.getLog(this.getClass());
|
||||
|
||||
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
|
||||
|
||||
protected MySimpleUrlAuthenticationSuccessHandler() {
|
||||
super();
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
@Override
|
||||
public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws IOException {
|
||||
handle(request, response, authentication);
|
||||
clearAuthenticationAttributes(request);
|
||||
}
|
||||
|
||||
// IMPL
|
||||
|
||||
protected void handle(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws IOException {
|
||||
final 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(final Authentication authentication) {
|
||||
boolean isUser = false;
|
||||
boolean isAdmin = false;
|
||||
final Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
|
||||
for (final 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();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes temporary authentication-related data which may have been stored in the session
|
||||
* during the authentication process.
|
||||
*/
|
||||
protected final void clearAuthenticationAttributes(final HttpServletRequest request) {
|
||||
final HttpSession session = request.getSession(false);
|
||||
|
||||
if (session == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
|
||||
}
|
||||
|
||||
public void setRedirectStrategy(final RedirectStrategy redirectStrategy) {
|
||||
this.redirectStrategy = redirectStrategy;
|
||||
}
|
||||
|
||||
protected RedirectStrategy getRedirectStrategy() {
|
||||
return redirectStrategy;
|
||||
}
|
||||
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package org.baeldung.security;
|
||||
|
||||
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
|
||||
|
||||
/**
|
||||
* Registers the springSecurityFilterChain Filter for every URL in the application.
|
||||
*
|
||||
*/
|
||||
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer{
|
||||
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package org.baeldung.service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.User;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
/**
|
||||
* User Details Service - hard coded to two users for the example.
|
||||
*/
|
||||
@Service
|
||||
public class MyUserDetailsService implements UserDetailsService {
|
||||
|
||||
private final Log logger = LogFactory.getLog(this.getClass());
|
||||
|
||||
private Map<String, User> availableUsers = new HashMap<String, User>();
|
||||
|
||||
public MyUserDetailsService() {
|
||||
|
||||
availableUsers.put("user",
|
||||
createUser("user", "password", Arrays.asList("ROLE_USER")));
|
||||
availableUsers.put("admin",
|
||||
createUser("admin", "password", Arrays.asList("ROLE_ADMIN")));
|
||||
}
|
||||
|
||||
@Override
|
||||
public UserDetails loadUserByUsername(String username)
|
||||
throws UsernameNotFoundException {
|
||||
|
||||
logger.info("Load user by username " + username);
|
||||
|
||||
UserDetails user = availableUsers.get(username);
|
||||
if (user == null) {
|
||||
throw new UsernameNotFoundException("Username not found");
|
||||
} else {
|
||||
return availableUsers.get(username);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private User createUser(String username, String password, List<String> roles) {
|
||||
|
||||
logger.info("Create user " + username);
|
||||
|
||||
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
|
||||
for (String role : roles) {
|
||||
authorities.add(new SimpleGrantedAuthority(role));
|
||||
}
|
||||
return new User(username, password, true, true, true, true, authorities);
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package org.baeldung.spring;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.jdbc.datasource.DriverManagerDataSource;
|
||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
|
||||
/**
|
||||
* Spring Database Configuration.
|
||||
*/
|
||||
@Configuration
|
||||
@EnableTransactionManagement
|
||||
@PropertySource({ "classpath:persistence-h2.properties" })
|
||||
public class DatabaseConfig {
|
||||
|
||||
@Autowired
|
||||
private Environment env;
|
||||
|
||||
@Bean
|
||||
public DataSource dataSource() {
|
||||
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
|
||||
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
|
||||
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
|
||||
dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
|
||||
dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
|
||||
return dataSource;
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package org.baeldung.spring;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
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;
|
||||
|
||||
/**
|
||||
* Spring Web Configuration.
|
||||
*/
|
||||
@EnableWebMvc
|
||||
@ComponentScan("org.baeldung")
|
||||
@Configuration
|
||||
public class MvcConfig extends WebMvcConfigurerAdapter {
|
||||
|
||||
public MvcConfig() {
|
||||
super();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addViewControllers(final ViewControllerRegistry registry) {
|
||||
super.addViewControllers(registry);
|
||||
registry.addViewController("/anonymous.html");
|
||||
registry.addViewController("/login.html");
|
||||
registry.addViewController("/homepage.html");
|
||||
registry.addViewController("/console.html");
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ViewResolver viewResolver() {
|
||||
final InternalResourceViewResolver bean = new InternalResourceViewResolver();
|
||||
bean.setViewClass(JstlView.class);
|
||||
bean.setPrefix("/WEB-INF/view/");
|
||||
bean.setSuffix(".jsp");
|
||||
return bean;
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package org.baeldung.spring;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.ImportResource;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
|
||||
/**
|
||||
* Spring Security Configuration.
|
||||
*/
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
@ImportResource({ "classpath:webSecurityConfig.xml" })
|
||||
public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
public SecurityConfig() {
|
||||
super();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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>
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
# jdbc.X
|
||||
jdbc.driverClassName=org.h2.Driver
|
||||
jdbc.url=jdbc:h2:tcp://localhost/~/test
|
||||
|
||||
jdbc.user=sa
|
||||
jdbc.pass=
|
||||
|
||||
# hibernate.X
|
||||
hibernate.dialect=org.hibernate.dialect.H2Dialect
|
||||
hibernate.show_sql=false
|
||||
hibernate.hbm2ddl.auto=create-drop
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
# jdbc.X
|
||||
jdbc.driverClassName=org.postgresql.Driver
|
||||
jdbc.url=jdbc:postgresql://localhost:5432
|
||||
|
||||
jdbc.user=postgres
|
||||
jdbc.pass=
|
||||
|
||||
# hibernate.X
|
||||
hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
|
||||
hibernate.show_sql=false
|
||||
hibernate.hbm2ddl.auto=create-drop
|
||||
@@ -0,0 +1,52 @@
|
||||
<?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:tx="http://www.springframework.org/schema/tx"
|
||||
xmlns:p="http://www.springframework.org/schema/p"
|
||||
xmlns:util="http://www.springframework.org/schema/util"
|
||||
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://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
|
||||
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
|
||||
|
||||
|
||||
<http use-expressions="true">
|
||||
|
||||
<intercept-url pattern="/anonymous*" access="isAnonymous()" />
|
||||
<intercept-url pattern="/login*" access="permitAll" />
|
||||
<intercept-url pattern="/**" access="isAuthenticated()" />
|
||||
|
||||
<form-login login-page='/login.html' authentication-success-handler-ref="mySimpleUrlAuthenticationSuccessHandler" authentication-failure-url="/login.html?error=true" />
|
||||
|
||||
<logout delete-cookies="JSESSIONID" />
|
||||
|
||||
<remember-me data-source-ref="dataSource" token-validity-seconds="86400"/>
|
||||
|
||||
</http>
|
||||
|
||||
|
||||
|
||||
|
||||
<beans:bean id="rememberMeAuthenticationProvider" class="org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices">
|
||||
<beans:property name="key" value="myAppKey" />
|
||||
<beans:property name="tokenRepository" ref="jdbcTokenRepository" />
|
||||
<beans:property name="userDetailsService" ref="myUserDetailsService" />
|
||||
</beans:bean>
|
||||
|
||||
<!-- Uses a database table to maintain a set of persistent login data -->
|
||||
<beans:bean id="jdbcTokenRepository" class="org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl">
|
||||
<beans:property name="createTableOnStartup" value="false" />
|
||||
<beans:property name="dataSource" ref="dataSource" />
|
||||
</beans:bean>
|
||||
|
||||
|
||||
<authentication-manager alias="authenticationManager">
|
||||
<authentication-provider user-service-ref="myUserDetailsService">
|
||||
</authentication-provider>
|
||||
</authentication-manager>
|
||||
|
||||
|
||||
|
||||
</beans:beans>
|
||||
@@ -0,0 +1,6 @@
|
||||
<?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>
|
||||
@@ -0,0 +1,10 @@
|
||||
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
|
||||
<html>
|
||||
<head></head>
|
||||
|
||||
<body>
|
||||
<h1>Anonymous page</h1>
|
||||
|
||||
<a href="<c:url value="/login.html" />">To Login</a>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,22 @@
|
||||
<%@ 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>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,22 @@
|
||||
<%@ 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 homepage for the user</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>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,30 @@
|
||||
<html>
|
||||
<head></head>
|
||||
|
||||
<body>
|
||||
<h1>Login</h1>
|
||||
|
||||
<form name='f' action="j_spring_security_check" method='POST'>
|
||||
|
||||
<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>Remember Me:</td>
|
||||
<td><input type="checkbox" name="_spring_security_remember_me" /></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><input name="submit" type="submit" value="submit" /></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
</form>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,55 @@
|
||||
<?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_3_0.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 MVC Custom Application</display-name>
|
||||
|
||||
<session-config>
|
||||
<session-timeout>1</session-timeout>
|
||||
</session-config>
|
||||
|
||||
<!-- Spring root -->
|
||||
<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>
|
||||
|
||||
<!-- Spring child -->
|
||||
<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>
|
||||
|
||||
<!-- 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>
|
||||
-->
|
||||
|
||||
<!-- <welcome-file-list> -->
|
||||
<!-- <welcome-file>index.html</welcome-file> -->
|
||||
<!-- </welcome-file-list> -->
|
||||
|
||||
</web-app>
|
||||
@@ -0,0 +1,13 @@
|
||||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
Reference in New Issue
Block a user