462 Solution Code Spring Security Demo 08 JDBC Plaintext
462 Solution Code Spring Security Demo 08 JDBC Plaintext
DemoAppConfig.java
package com.luv2code.springsecurity.demo.config;
import java.beans.PropertyVetoException;
import java.util.logging.Logger;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import com.mchange.v2.c3p0.ComboPooledDataSource;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages="com.luv2code.springsecurity.demo")
@PropertySource("classpath:persistence-mysql.properties")
public class DemoAppConfig {
@Autowired
private Environment env;
@Bean
public ViewResolver viewResolver() {
viewResolver.setPrefix("/WEB-INF/view/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
1
// define a bean for our security datasource
@Bean
public DataSource securityDataSource() {
try {
securityDataSource.setDriverClass(env.getProperty("jdbc.driver"));
} catch (PropertyVetoException exc) {
throw new RuntimeException(exc);
}
securityDataSource.setJdbcUrl(env.getProperty("jdbc.url"));
securityDataSource.setUser(env.getProperty("jdbc.user"));
securityDataSource.setPassword(env.getProperty("jdbc.password"));
securityDataSource.setInitialPoolSize(
getIntProperty("connection.pool.initialPoolSize"));
securityDataSource.setMinPoolSize(
getIntProperty("connection.pool.minPoolSize"));
securityDataSource.setMaxPoolSize(
getIntProperty("connection.pool.maxPoolSize"));
securityDataSource.setMaxIdleTime(
getIntProperty("connection.pool.maxIdleTime"));
return securityDataSource;
}
return intPropVal;
}
}
2
DemoSecurityConfig.java
package com.luv2code.springsecurity.demo.config;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import
org.springframework.security.config.annotation.authentication.builders.AuthenticationManager
Builder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import
org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapte
r;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.User.UserBuilder;
@Configuration
@EnableWebSecurity
public class DemoSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private DataSource securityDataSource;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(securityDataSource);
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/").hasRole("EMPLOYEE")
.antMatchers("/leaders/**").hasRole("MANAGER")
.antMatchers("/systems/**").hasRole("ADMIN")
.and()
.formLogin()
.loginPage("/showMyLoginPage")
.loginProcessingUrl("/authenticateTheUser")
.permitAll()
.and()
.logout().permitAll()
.and()
.exceptionHandling().accessDeniedPage("/access-denied");
3
MySpringMvcDispatcherServletInitializer.java
package com.luv2code.springsecurity.demo.config;
import
org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer
;
@Override
protected Class<?>[] getRootConfigClasses() {
// TODO Auto-generated method stub
return null;
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { DemoAppConfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
SecurityWebApplicationInitializer.java
package com.luv2code.springsecurity.demo.config;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
4
DemoController.java
package com.luv2code.springsecurity.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class DemoController {
@GetMapping("/")
public String showHome() {
return "home";
}
@GetMapping("/leaders")
public String showLeaders() {
return "leaders";
}
@GetMapping("/systems")
public String showSystems() {
return "systems";
}
LoginController.java
package com.luv2code.springsecurity.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class LoginController {
@GetMapping("/showMyLoginPage")
public String showMyLoginPage() {
// return "plain-login";
return "fancy-login";
@GetMapping("/access-denied")
public String showAccessDenied() {
return "access-denied";
}
5
pom.xml
<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>com.luv2code</groupId>
<artifactId>spring-security-demo</artifactId>
<version>1.0</version>
<packaging>war</packaging>
<name>spring-security-demo</name>
<properties>
<springframework.version>5.0.2.RELEASE</springframework.version>
<springsecurity.version>5.0.0.RELEASE</springsecurity.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${springsecurity.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${springsecurity.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.45</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
6
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>spring-security-demo</finalName>
<pluginManagement>
<plugins>
<plugin>
<!-- Add Maven coordinates (GAV) for: maven-war-plugin -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.0</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
7
home.jsp
<html>
<body>
<h2>luv2code Company Home Page</h2>
<hr>
<p>
Welcome to the luv2code company home page!
</p>
<hr>
<p>
User: <security:authentication property="principal.username" />
<br><br>
Role(s): <security:authentication property="principal.authorities" />
</p>
<security:authorize access="hasRole('MANAGER')">
<!-- Add a link to point to /leaders ... this is for the managers -->
<p>
<a href="${pageContext.request.contextPath}/leaders">Leadership
Meeting</a>
(Only for Manager peeps)
</p>
</security:authorize>
<security:authorize access="hasRole('ADMIN')">
<!-- Add a link to point to /systems ... this is for the admins -->
<p>
<a href="${pageContext.request.contextPath}/systems">IT Systems
Meeting</a>
(Only for Admin peeps)
</p>
</security:authorize>
<hr>
</form:form>
</body>
</html>
8
plain-login.jsp
<html>
<head>
<title>Custom Login Page</title>
<style>
.failed {
color: red;
}
</style>
</head>
<body>
<form:form action="${pageContext.request.contextPath}/authenticateTheUser"
method="POST">
</c:if>
<p>
User name: <input type="text" name="username" />
</p>
<p>
Password: <input type="password" name="password" />
</p>
</form:form>
</body>
</html>
9
leaders.jsp
<html>
<head>
<title>luv2code LEADERS Home Page</title>
</head>
<body>
<hr>
<p>
See you in Brazil ... for our annual Leadership retreat!
<br>
Keep this trip a secret, don't tell the regular employees LOL :-)
</p>
<hr>
</body>
</html>
systems.jsp
<html>
<head>
<title>luv2code SYSTEMS Home Page</title>
</head>
<body>
<hr>
<p>
We have our annual holiday Caribbean cruise coming up. Register now!
<br>
Keep this trip a secret, don't tell the regular employees LOL :-)
</p>
<hr>
</body>
</html>
10
access-denied.jsp
<html>
<head>
<title>luv2code - Access Denied</title>
</head>
<body>
<hr>
</body>
</html>
11
fancy-login.jsp
<!doctype html>
<html lang="en">
<head>
<title>Login Page</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
</head>
<body>
<div>
<div class="panel-heading">
<div class="panel-title">Sign In</div>
</div>
12
<!-- Login Form -->
<form action="${pageContext.request.contextPath}/authenticateTheUser"
method="POST" class="form-horizontal">
</c:if>
</c:if>
</div>
</div>
</div>
13
<!-- User name -->
<div style="margin-bottom: 25px" class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input type="hidden"
name="${_csrf.parameterName}"
value="${_csrf.token}" />
</form>
</div>
</div>
</div>
</div>
</body>
</html>
14