0% found this document useful (0 votes)
205 views

462 Solution Code Spring Security Demo 08 JDBC Plaintext

This document contains code for a Spring Security demo application that uses JDBC authentication with plaintext passwords stored in a database. It includes configuration classes for Spring MVC, Spring Security, controllers, and the pom.xml file.

Uploaded by

ion2010
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
205 views

462 Solution Code Spring Security Demo 08 JDBC Plaintext

This document contains code for a Spring Security demo application that uses JDBC authentication with plaintext passwords stored in a database. It includes configuration classes for Spring MVC, Spring Security, controllers, and the pom.xml file.

Uploaded by

ion2010
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

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 {

// set up variable to hold the properties

@Autowired
private Environment env;

// set up a logger for diagnostics

private Logger logger = Logger.getLogger(getClass().getName());

// define a bean for ViewResolver

@Bean
public ViewResolver viewResolver() {

InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();

viewResolver.setPrefix("/WEB-INF/view/");
viewResolver.setSuffix(".jsp");

return viewResolver;
}

1
// define a bean for our security datasource

@Bean
public DataSource securityDataSource() {

// create connection pool


ComboPooledDataSource securityDataSource
= new ComboPooledDataSource();

// set the jdbc driver class

try {
securityDataSource.setDriverClass(env.getProperty("jdbc.driver"));
} catch (PropertyVetoException exc) {
throw new RuntimeException(exc);
}

// log the connection props


// for sanity's sake, log this info
// just to make sure we are REALLY reading data from properties file

logger.info(">>> jdbc.url=" + env.getProperty("jdbc.url"));


logger.info(">>> jdbc.user=" + env.getProperty("jdbc.user"));

// set database connection props

securityDataSource.setJdbcUrl(env.getProperty("jdbc.url"));
securityDataSource.setUser(env.getProperty("jdbc.user"));
securityDataSource.setPassword(env.getProperty("jdbc.password"));

// set connection pool props

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;
}

// need a helper method


// read environment property and convert to int

private int getIntProperty(String propName) {

String propVal = env.getProperty(propName);

// now convert to int


int intPropVal = Integer.parseInt(propVal);

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 {

// add a reference to our security data source

@Autowired
private DataSource securityDataSource;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {

// use jdbc authentication ... oh yeah!!!

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
;

public class MySpringMvcDispatcherServletInitializer extends


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;

public class SecurityWebApplicationInitializer


extends 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";
}

// add request mapping for /leaders

@GetMapping("/leaders")
public String showLeaders() {

return "leaders";
}

// add request mapping for /systems

@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";

// add request mapping for /access-denied

@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>

<!-- Spring MVC support -->


<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>

<!-- Spring Security -->


<!-- spring-security-web and spring-security-config -->

<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>

<!-- Add Spring Security Taglibs support -->


<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>${springsecurity.version}</version>
</dependency>

<!-- Add MySQL and C3P0 support -->

<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>

<!-- Servlet, JSP and JSTL support -->


<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</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>

<!-- TO DO: Add support for Maven WAR Plugin -->

<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

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>


<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>

<html>

<head> <title>luv2code Company Home Page</title> </head>

<body>
<h2>luv2code Company Home Page</h2>
<hr>

<p>
Welcome to the luv2code company home page!
</p>

<hr>

<!-- display user name and role -->

<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>

<!-- Add a logout button -->


<form:form action="${pageContext.request.contextPath}/logout"
method="POST">

<input type="submit" value="Logout" />

</form:form>

</body>

</html>

8
plain-login.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>

<head>
<title>Custom Login Page</title>

<style>
.failed {
color: red;
}
</style>

</head>

<body>

<h3>My Custom Login Page</h3>

<form:form action="${pageContext.request.contextPath}/authenticateTheUser"
method="POST">

<!-- Check for login error -->

<c:if test="${param.error != null}">

<i class="failed">Sorry! You entered invalid username/password.</i>

</c:if>

<p>
User name: <input type="text" name="username" />
</p>

<p>
Password: <input type="password" name="password" />
</p>

<input type="submit" value="Login" />

</form:form>

</body>

</html>

9
leaders.jsp

<html>

<head>
<title>luv2code LEADERS Home Page</title>
</head>

<body>

<h2>luv2code LEADERS Home Page</h2>

<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>

<a href="${pageContext.request.contextPath}/">Back to Home Page</a>

</body>

</html>

systems.jsp

<html>

<head>
<title>luv2code SYSTEMS Home Page</title>
</head>

<body>

<h2>luv2code SYSTEMS Home Page</h2>

<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>

<a href="${pageContext.request.contextPath}/">Back to Home Page</a>

</body>

</html>

10
access-denied.jsp

<html>

<head>
<title>luv2code - Access Denied</title>
</head>

<body>

<h2>Access Denied - You are not authorized to access this resource.</h2>

<hr>

<a href="${pageContext.request.contextPath}/">Back to Home Page</a>

</body>

</html>

11
fancy-login.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!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">

<!-- Reference Bootstrap files -->


<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</head>

<body>

<div>

<div id="loginbox" style="margin-top: 50px;"


class="mainbox col-md-3 col-md-offset-2 col-sm-6 col-sm-offset-2">

<div class="panel panel-info">

<div class="panel-heading">
<div class="panel-title">Sign In</div>
</div>

<div style="padding-top: 30px" class="panel-body">

12
<!-- Login Form -->
<form action="${pageContext.request.contextPath}/authenticateTheUser"
method="POST" class="form-horizontal">

<!-- Place for messages: error, alert etc ... -->


<div class="form-group">
<div class="col-xs-15">
<div>

<!-- Check for login error -->

<c:if test="${param.error != null}">

<div class="alert alert-danger col-xs-offset-1 col-xs-10">


Invalid username and password.
</div>

</c:if>

<!-- Check for logout -->

<c:if test="${param.logout != null}">

<div class="alert alert-success col-xs-offset-1 col-xs-10">


You have been logged out.
</div>

</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="text" name="username" placeholder="username" class="form-control">


</div>

<!-- Password -->


<div style="margin-bottom: 25px" class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>

<input type="password" name="password" placeholder="password" class="form-control" >


</div>

<!-- Login/Submit Button -->


<div style="margin-top: 10px" class="form-group">
<div class="col-sm-6 controls">
<button type="submit" class="btn btn-success">Login</button>
</div>
</div>

<!-- I'm manually adding tokens ... Bro! -->

<input type="hidden"
name="${_csrf.parameterName}"
value="${_csrf.token}" />

</form>

</div>

</div>

</div>

</div>

</body>
</html>

14

You might also like