Commit 6fd8f7ef authored by Administrator's avatar Administrator

Changes authentication to HTTP Basic

The user authentication was currently done using a cookie and following
the same style of token as the HTTP Basic authentication (i.e. a
concatenation of user and password joined with a ':' encoded with
base64).

This authentication has been replaced by a standard HTTP Basic
authentication.
parent 0ee6f4fa
......@@ -10,6 +10,7 @@ CREATE TABLE `daaexample`.`people` (
CREATE TABLE `daaexample`.`users` (
`login` varchar(100) NOT NULL,
`password` varchar(64) NOT NULL,
`role` varchar(10) NOT NULL,
PRIMARY KEY (`login`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
......@@ -25,5 +26,7 @@ INSERT INTO `daaexample`.`people` (`id`,`name`,`surname`) VALUES (0,'Alba','Fern
INSERT INTO `daaexample`.`people` (`id`,`name`,`surname`) VALUES (0,'Asunción','Jiménez');
-- The password for each user is its login suffixed with "pass". For example, user "admin" has the password "adminpass".
INSERT INTO `daaexample`.`users` (`login`,`password`) VALUES ('admin', '43f413b773f7d0cfad0e8e6529ec1249ce71e8697919eab30d82d800a3986b70');
INSERT INTO `daaexample`.`users` (`login`,`password`) VALUES ('normal', '688f21dd2d65970f174e2c9d35159250a8a23e27585452683db8c5d10b586336');
INSERT INTO `daaexample`.`users` (`login`,`password`,`role`)
VALUES ('admin', '713bfda78870bf9d1b261f565286f85e97ee614efe5f0faf7c34e7ca4f65baca','ADMIN');
INSERT INTO `daaexample`.`users` (`login`,`password`,`role`)
VALUES ('normal', '7bf24d6ca2242430343ab7e3efb89559a47784eea1123be989c1b2fb2ef66e83','USER');
......@@ -10,6 +10,7 @@ CREATE TABLE `daaexample`.`people` (
CREATE TABLE `daaexample`.`users` (
`login` varchar(100) NOT NULL,
`password` varchar(64) NOT NULL,
`role` varchar(10) NOT NULL,
PRIMARY KEY (`login`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
......
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<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>es.uvigo.esei.daa</groupId>
<artifactId>example</artifactId>
<packaging>war</packaging>
<version>0.1.9</version>
<version>0.1.10</version>
<name>DAA Example</name>
<licenses>
......@@ -37,13 +38,13 @@
<junit.version>4.12</junit.version>
<java-hamcrest.version>2.0.0.0</java-hamcrest.version>
<easymock.version>3.5.1</easymock.version>
<selenium-java.version>3.8.1</selenium-java.version>
<selenium-java.version>3.141.59</selenium-java.version>
<spring-test.version>4.3.14.RELEASE</spring-test.version>
<dbunit.version>2.5.1</dbunit.version>
<spring-test-dbunit.version>1.3.0</spring-test-dbunit.version>
<hsqldb.version>2.3.3</hsqldb.version>
<mysql.version>5.1.45</mysql.version>
<geckodriver.version>v0.19.1</geckodriver.version>
<geckodriver.version>v0.24.0</geckodriver.version>
<equalsverifier.version>2.4.2</equalsverifier.version>
<!-- Plugins -->
......@@ -320,7 +321,7 @@
</goals>
</pluginExecutionFilter>
<action>
<ignore></ignore>
<ignore />
</action>
</pluginExecution>
</pluginExecutions>
......@@ -410,7 +411,7 @@
<address>localhost</address>
<name>daatestdb</name>
<username>sa</username>
<password></password>
<password />
</configuration>
<!-- call start and stop -->
......@@ -454,6 +455,12 @@
<configuration>
<home>${project.build.directory}/catalina-base</home>
<files>
<copy>
<file>tomcat/server.hsqldb.xml</file>
<tofile>conf/server.xml</tofile>
</copy>
</files>
<properties>
<cargo.jvmargs>${jacoco.agent.itArgLine},output=tcpserver,port=${jacoco.port}
-Drunmode=TEST</cargo.jvmargs>
......@@ -553,6 +560,12 @@
<configuration>
<home>${project.build.directory}/catalina-base</home>
<files>
<copy>
<file>tomcat/server.mysql.xml</file>
<tofile>conf/server.xml</tofile>
</copy>
</files>
<properties>
<cargo.servlet.port>9080</cargo.servlet.port>
<cargo.datasource.datasource.h2>
......@@ -599,11 +612,12 @@
<configuration>
<target>
<mkdir dir="${geckodriver.basepath}" />
<get src="${geckodriver.url}" dest="${geckodriver.compressed.path}"
skipexisting="true" />
<untar src="${geckodriver.compressed.path}" dest="${geckodriver.basepath}"
compression="gzip" />
<chmod file="${geckodriver.uncompressed.path}" perm="a+x" />
<get src="${geckodriver.url}"
dest="${geckodriver.compressed.path}" skipexisting="true" />
<untar src="${geckodriver.compressed.path}"
dest="${geckodriver.basepath}" compression="gzip" />
<chmod file="${geckodriver.uncompressed.path}"
perm="a+x" />
</target>
</configuration>
<goals>
......@@ -642,10 +656,12 @@
<configuration>
<target>
<mkdir dir="${geckodriver.basepath}" />
<get src="${geckodriver.url}" dest="${geckodriver.compressed.path}"
skipexisting="true" />
<unzip src="${geckodriver.compressed.path}" dest="${file.separator}${geckodriver.basepath}" />
<chmod file="${geckodriver.uncompressed.path}" perm="a+x" />
<get src="${geckodriver.url}"
dest="${geckodriver.compressed.path}" skipexisting="true" />
<unzip src="${geckodriver.compressed.path}"
dest="${file.separator}${geckodriver.basepath}" />
<chmod file="${geckodriver.uncompressed.path}"
perm="a+x" />
</target>
</configuration>
<goals>
......@@ -737,11 +753,12 @@
<configuration>
<target>
<mkdir dir="${geckodriver.basepath}" />
<get src="${geckodriver.url}" dest="${geckodriver.compressed.path}"
skipexisting="true" />
<untar src="${geckodriver.compressed.path}" dest="${geckodriver.basepath}"
compression="gzip" />
<chmod file="${geckodriver.uncompressed.path}" perm="a+x" />
<get src="${geckodriver.url}"
dest="${geckodriver.compressed.path}" skipexisting="true" />
<untar src="${geckodriver.compressed.path}"
dest="${geckodriver.basepath}" compression="gzip" />
<chmod file="${geckodriver.uncompressed.path}"
perm="a+x" />
</target>
</configuration>
<goals>
......
package es.uvigo.esei.daa;
import static java.util.Objects.requireNonNull;
import java.io.IOException;
import java.util.Base64;
import java.util.Optional;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import es.uvigo.esei.daa.dao.DAOException;
import es.uvigo.esei.daa.dao.UsersDAO;
/**
* Security filter that implements a login protocol based on the HTTP Basic
* Authentication protocol. In this case, the login and password can be provided
* as plain request parameters or as a cookie named "token" that should contain
* both values in the same format as HTTP Basic Authentication
* ({@code base64(login + ":" + password)}).
*
* @author Miguel Reboiro Jato
*
*/
@WebFilter(urlPatterns = "/*")
public class LoginFilter implements Filter {
private static final String LOGOUT_PATH = "/logout";
private static final String REST_PATH = "/rest";
private static final String[] PUBLIC_PATHS = new String[] {
"/index.html", "/js", "/css" // Add the paths that can be publicly accessed (e.g. /images...)
};
@Override
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain
) throws IOException, ServletException {
final HttpServletRequest httpRequest = (HttpServletRequest) request;
final HttpServletResponse httpResponse = (HttpServletResponse) response;
try {
if (isLogoutPath(httpRequest)) {
destroySession(httpRequest);
removeTokenCookie(httpRequest, httpResponse);
redirectToIndex(httpRequest, httpResponse);
} else if (isPublicPath(httpRequest) || checkToken(httpRequest)) {
chain.doFilter(request, response);
} else if (checkLogin(httpRequest, httpResponse)) {
continueWithRedirect(httpRequest, httpResponse);
} else if (isRestPath(httpRequest)) {
destroySession(httpRequest);
httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
} else {
destroySession(httpRequest);
redirectToIndex(httpRequest, httpResponse);
}
} catch (IllegalArgumentException iae) {
httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
} catch (DAOException e) {
httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
@Override
public void init(FilterConfig config) throws ServletException {
}
@Override
public void destroy() {
}
private boolean isLogoutPath(HttpServletRequest request) {
return request.getServletPath().equals(LOGOUT_PATH);
}
private boolean isPublicPath(HttpServletRequest request) {
for (String path : PUBLIC_PATHS) {
if (request.getServletPath().startsWith(path))
return true;
}
return false;
}
private boolean isRestPath(HttpServletRequest request) {
return request.getServletPath().startsWith(REST_PATH);
}
private void redirectToIndex(
HttpServletRequest request,
HttpServletResponse response
) throws IOException {
response.sendRedirect(request.getContextPath());
}
private void continueWithRedirect(
HttpServletRequest request,
HttpServletResponse response
) throws IOException {
String redirectPath = request.getRequestURI();
if (request.getQueryString() != null)
redirectPath += "?" + request.getQueryString();
response.sendRedirect(redirectPath);
}
private void removeTokenCookie(
HttpServletRequest request,
HttpServletResponse response
) {
final Cookie cookie = getTokenCookie(request);
if (cookie != null) {
cookie.setMaxAge(0);
response.addCookie(cookie);
}
}
private void destroySession(HttpServletRequest request) {
request.getSession().invalidate();
}
private boolean checkLogin(
HttpServletRequest request,
HttpServletResponse response
) throws DAOException {
final String login = request.getParameter("login");
final String password = request.getParameter("password");
if (login != null && password != null) {
final UsersDAO dao = new UsersDAO();
if (dao.checkLogin(login, password)) {
final Credentials credentials = new Credentials(login, password);
response.addCookie(new Cookie("token", credentials.toToken()));
request.getSession().setAttribute("login", login);
return true;
} else {
return false;
}
} else {
return false;
}
}
private Cookie getTokenCookie(HttpServletRequest request) {
final Cookie[] cookies = Optional.ofNullable(request.getCookies())
.orElse(new Cookie[0]);
for (Cookie cookie : cookies) {
if ("token".equals(cookie.getName())) {
return cookie;
}
}
return null;
}
private boolean checkToken(HttpServletRequest request)
throws DAOException, IllegalArgumentException {
final Cookie cookie = getTokenCookie(request);
if (cookie != null) {
final Credentials credentials = new Credentials(cookie.getValue());
final UsersDAO dao = new UsersDAO();
if (dao.checkLogin(credentials.getLogin(), credentials.getPassword())) {
request.getSession().setAttribute("login", credentials.getLogin());
return true;
} else {
return false;
}
}
return false;
}
private static class Credentials {
private final String login;
private final String password;
public Credentials(String token) {
final String decodedToken = decodeBase64(token);
final int colonIndex = decodedToken.indexOf(':');
if (colonIndex < 0 || colonIndex == decodedToken.length()-1) {
throw new IllegalArgumentException("Invalid token");
}
this.login = decodedToken.substring(0, colonIndex);
this.password = decodedToken.substring(colonIndex + 1);
}
public Credentials(String login, String password) {
this.login = requireNonNull(login, "Login can't be null");
this.password = requireNonNull(password, "Password can't be null");
}
public String getLogin() {
return login;
}
public String getPassword() {
return password;
}
public String toToken() {
return encodeBase64(this.login + ":" + this.password);
}
private final static String decodeBase64(String text) {
return new String(Base64.getDecoder().decode(text.getBytes()));
}
private final static String encodeBase64(String text) {
return Base64.getEncoder().encodeToString(text.getBytes());
}
}
}
......@@ -19,9 +19,6 @@ import es.uvigo.esei.daa.entities.User;
public class UsersDAO extends DAO {
private final static Logger LOG = Logger.getLogger(UsersDAO.class.getName());
// Yes, SALT should come from external configuration (for example, a property in Tomcat's context).
private final static String SALT = "daaexample-";
/**
* Returns a user stored persisted in the system.
*
......@@ -70,7 +67,7 @@ public class UsersDAO extends DAO {
final User user = this.get(login);
final String dbPassword = user.getPassword();
final String shaPassword = encodeSha256(SALT + password);
final String shaPassword = encodeSha256(password);
return shaPassword.equals(dbPassword);
} catch (IllegalArgumentException iae) {
......@@ -103,7 +100,8 @@ public class UsersDAO extends DAO {
private User rowToEntity(ResultSet result) throws SQLException {
return new User(
result.getString("login"),
result.getString("password")
result.getString("password"),
result.getString("role")
);
}
}
......@@ -10,6 +10,7 @@ import static java.util.Objects.requireNonNull;
public class User {
private String login;
private String password;
private String role;
// Constructor needed for the JSON conversion
User() {}
......@@ -21,9 +22,10 @@ public class User {
* @param password password of the user encoded using SHA-256 and with the
* "salt" prefix added.
*/
public User(String login, String password) {
public User(String login, String password, String role) {
this.setLogin(login);
this.setPassword(password);
this.setRole(role);
}
/**
......@@ -65,4 +67,22 @@ public class User {
this.password = password;
}
/**
* Returns the role of the user.
*
* @return the role of the user.
*/
public String getRole() {
return role;
}
/**
* Sets the role of the user.
*
* @param role the role of the user
*/
public void setRole(String role) {
this.role = requireNonNull(role, "Role can't be null");
}
}
......@@ -3,7 +3,6 @@ package es.uvigo.esei.daa.rest;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
......@@ -11,6 +10,7 @@ import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import es.uvigo.esei.daa.dao.DAOException;
import es.uvigo.esei.daa.dao.UsersDAO;
......@@ -26,9 +26,7 @@ public class UsersResource {
private final UsersDAO dao;
// The HttpServletRequest can be also injected as a parameter in the REST
// methods.
private @Context HttpServletRequest request;
private @Context SecurityContext security;
/**
* Constructs a new instance of {@link UsersResource}.
......@@ -43,9 +41,9 @@ public class UsersResource {
}
// Needed for testing purposes
UsersResource(UsersDAO dao, HttpServletRequest request) {
UsersResource(UsersDAO dao, SecurityContext security) {
this.dao = dao;
this.request = request;
this.security = security;
}
/**
......@@ -71,7 +69,7 @@ public class UsersResource {
// Each user can only access his or her own data. Only the admin user
// can access the data of any user.
if (loggedUser.equals(login) || loggedUser.equals("admin")) {
if (loggedUser.equals(login) || this.isAdmin()) {
try {
return Response.ok(dao.get(login)).build();
} catch (IllegalArgumentException iae) {
......@@ -93,6 +91,10 @@ public class UsersResource {
}
private String getLogin() {
return (String) request.getSession().getAttribute("login");
return this.security.getUserPrincipal().getName();
}
private boolean isAdmin() {
return this.security.isUserInRole("ADMIN");
}
}
......@@ -9,4 +9,48 @@
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<security-constraint>
<web-resource-collection>
<web-resource-name>Protected Area</web-resource-name>
<url-pattern>/rest/*</url-pattern>
<http-method>PUT</http-method>
<http-method>DELETE</http-method>
<http-method>GET</http-method>
<http-method>POST</http-method>
<http-method>OPTIONS</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>ADMIN</role-name>
<role-name>USER</role-name>
</auth-constraint>
</security-constraint>
<security-constraint>
<web-resource-collection>
<web-resource-name>Admin Area</web-resource-name>
<url-pattern>/rest/people/*</url-pattern>
<http-method>PUT</http-method>
<http-method>DELETE</http-method>
<http-method>GET</http-method>
<http-method>POST</http-method>
<http-method>OPTIONS</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>ADMIN</role-name>
</auth-constraint>
</security-constraint>
<!-- Security roles referenced by this web application -->
<security-role>
<role-name>ADMIN</role-name>
</security-role>
<security-role>
<role-name>USER</role-name>
</security-role>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>DAAExample</realm-name>
</login-config>
</web-app>
\ No newline at end of file
......@@ -16,14 +16,14 @@ body {
padding-bottom: 40px;
}
.form-signin {
#form-signin {
width: 100%;
max-width: 330px;
padding: 15px;
margin: 0 auto;
}
.form-signin .form-control {
#form-signin .form-control {
position: relative;
box-sizing: border-box;
height: auto;
......@@ -31,7 +31,7 @@ body {
font-size: 16px;
}
.form-signin .form-control:focus {
#form-signin .form-control:focus {
z-index: 2;
}
......
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>DAA Example - Login</title>
<title>DAA Example - Login</title>
<link rel="stylesheet" href="css/login.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body class="text-center">
<form class="form-singin" action="main.html" method="POST">
<link rel="stylesheet" href="css/login.css">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body class="text-center">
<form id="form-singin">
<h1 class="h1 mb-3 font-weight-normal">DAA Example</h1>
<label for="login" class="sr-only">Usuario</label>
<input id="login" name="login" type="text" class="form-control" placeholder="Usuario" required autofocus />
<label for="password" class="sr-only">Contraseña</label>
<input id="password" name="password" type="password" class="form-control" placeholder="Contraseña" required />
<label for="login" class="sr-only">Usuario</label> <input id="login"
name="login" type="text" class="form-control" placeholder="Usuario"
required autofocus /> <label for="password" class="sr-only">Contraseña</label>
<input id="password" name="password" type="password"
class="form-control" placeholder="Contraseña" required />
<button type="submit" class="btn btn-lg btn-primary btn-block mt-3">Entrar</button>
</form>
</body>
<script type="text/javascript"
src="http://code.jquery.com/jquery-2.2.4.min.js"></script>
<script
src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>
<script type="text/javascript" src="js/login.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#form-singin').submit(function(event) {
event.preventDefault();
var login = $('#login').val();
var password = $('#password').val();
doLogin(login, password);
});
});
</script>
</body>
</html>
\ No newline at end of file
......@@ -5,40 +5,44 @@ var PeopleDAO = (function() {
fail = typeof fail !== 'undefined' ? fail : function() {};
always = typeof always !== 'undefined' ? always : function() {};
$.ajax(data)
.done(done)
.fail(fail)
.always(always);
let authToken = localStorage.getItem('authorization-token');
if (authToken !== null) {
data.beforeSend = function(xhr) {
xhr.setRequestHeader('Authorization', 'Basic ' + authToken);
};
}
$.ajax(data).done(done).fail(fail).always(always);
};
function PeopleDAO() {
this.listPeople = function(done, fail, always) {
requestByAjax({
url: resourcePath,
type: 'GET'
url : resourcePath,
type : 'GET'
}, done, fail, always);
};
this.addPerson = function(person, done, fail, always) {
requestByAjax({
url: resourcePath,
type: 'POST',
data: person
url : resourcePath,
type : 'POST',
data : person
}, done, fail, always);
};
this.modifyPerson = function(person, done, fail, always) {
requestByAjax({
url: resourcePath + person.id,
type: 'PUT',
data: person
url : resourcePath + person.id,
type : 'PUT',
data : person
}, done, fail, always);
};
this.deletePerson = function(id, done, fail, always) {
requestByAjax({
url: resourcePath + id,
type: 'DELETE',
url : resourcePath + id,
type : 'DELETE',
}, done, fail, always);
};
}
......
function doLogin(login, password) {
$.ajax({
url: 'rest/users/' + login,
type: 'GET',
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Basic ' + btoa(login + ":" + password));
}
})
.done(function() {
localStorage.setItem('authorization-token', btoa(login + ":" + password));
window.location = 'main.html';
})
.fail(function() {
alert('Invalid login and/or password.');
});
}
function doLogout() {
localStorage.removeItem('authorization-token');
window.location = 'index.html';
}
\ No newline at end of file
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<head>
<meta charset="UTF-8">
<title>DAA Example</title>
<title>DAA Example</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body>
<header>
<div class="navbar navbar-dark bg-dark box-shadow">
<div class="container d-flex justify-content-between">
<a href="#" class="navbar-brand d-flex align-items-center">
<strong>DAA Example</strong>
</a>
<a id="#logout" href="logout" class="btn btn-dark" role="button">Cerrar sesión</a>
<button id="logout" class="btn btn-dark">Cerrar sesión</button>
</div>
</div>
</header>
......@@ -26,15 +26,25 @@
</div>
</div>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.2.4.min.js"></script>
<script type="text/javascript"
src="http://code.jquery.com/jquery-2.2.4.min.js"></script>
<script type="text/javascript" src="js/dao/people.js"></script>
<script type="text/javascript" src="js/view/people.js"></script>
<script type="text/javascript" src="js/login.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var view = new PeopleView(new PeopleDAO(), 'people-container', 'people-container');
$(document).ready(
function() {
$('#logout').click(function(event) {
event.preventDefault();
doLogout();
});
var view = new PeopleView(new PeopleDAO(),
'people-container', 'people-container'
);
view.init();
});
</script>
</body>
</body>
</html>
\ No newline at end of file
package es.uvigo.esei.daa;
import static java.util.Collections.unmodifiableSet;
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.ApplicationPath;
import es.uvigo.esei.daa.filters.AuthorizationFilter;
@ApplicationPath("/rest/*")
public class DAAExampleTestApplication extends DAAExampleApplication {
@Override
public Set<Class<?>> getClasses() {
final Set<Class<?>> classes = new HashSet<>(super.getClasses());
classes.add(AuthorizationFilter.class);
return unmodifiableSet(classes);
}
}
......@@ -10,8 +10,8 @@ public final class UsersDataset {
public static User[] users() {
return new User[] {
new User(adminLogin(), "43f413b773f7d0cfad0e8e6529ec1249ce71e8697919eab30d82d800a3986b70"),
new User(normalLogin(), "688f21dd2d65970f174e2c9d35159250a8a23e27585452683db8c5d10b586336")
new User(adminLogin(), "713bfda78870bf9d1b261f565286f85e97ee614efe5f0faf7c34e7ca4f65baca", "ADMIN"),
new User(normalLogin(), "7bf24d6ca2242430343ab7e3efb89559a47784eea1123be989c1b2fb2ef66e83", "USER")
};
}
......
package es.uvigo.esei.daa.filters;
import java.io.IOException;
import java.security.Principal;
import java.util.Base64;
import javax.annotation.Priority;
import javax.ws.rs.Priorities;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.ext.Provider;
import es.uvigo.esei.daa.dao.DAOException;
import es.uvigo.esei.daa.dao.UsersDAO;
import es.uvigo.esei.daa.entities.User;
@Provider
@Priority(Priorities.AUTHENTICATION)
public class AuthorizationFilter implements ContainerRequestFilter {
private final UsersDAO dao;
public AuthorizationFilter() {
this.dao = new UsersDAO();
}
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
// Get the authentication passed in HTTP headers parameters
final String auth = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
if (auth == null) {
requestContext.abortWith(createResponse());
} else {
final byte[] decodedToken = Base64.getDecoder()
.decode(auth.substring(6));
final String userColonPass = new String(decodedToken);
final String[] userPass = userColonPass.split(":", 2);
if (userPass.length == 2) {
try {
if (this.dao.checkLogin(userPass[0], userPass[1])) {
final User user = this.dao.get(userPass[0]);
requestContext.setSecurityContext(new UserSecurityContext(user));
} else {
requestContext.abortWith(createResponse());
}
} catch (DAOException e) {
requestContext.abortWith(createResponse());
}
} else {
requestContext.abortWith(createResponse());
}
}
}
private static Response createResponse() {
return Response.status(Status.UNAUTHORIZED)
.header(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\"DAAExample\"")
.entity("Page requires login.")
.build();
}
private static final class UserSecurityContext implements SecurityContext {
private final User user;
private UserSecurityContext(User user) {
this.user = user;
}
@Override
public boolean isUserInRole(String role) {
return user.getRole().equals(role);
}
@Override
public boolean isSecure() {
return false;
}
@Override
public Principal getUserPrincipal() {
return new Principal() {
@Override
public String getName() {
return user.getLogin();
}
};
}
@Override
public String getAuthenticationScheme() {
return SecurityContext.BASIC_AUTH;
}
}
}
......@@ -4,7 +4,6 @@ import static es.uvigo.esei.daa.dataset.UsersDataset.adminLogin;
import static es.uvigo.esei.daa.dataset.UsersDataset.normalLogin;
import static es.uvigo.esei.daa.dataset.UsersDataset.user;
import static es.uvigo.esei.daa.dataset.UsersDataset.userToken;
import static es.uvigo.esei.daa.matchers.HasHttpStatus.hasForbidden;
import static es.uvigo.esei.daa.matchers.HasHttpStatus.hasOkStatus;
import static es.uvigo.esei.daa.matchers.HasHttpStatus.hasUnauthorized;
import static es.uvigo.esei.daa.matchers.IsEqualToUser.equalsToUser;
......@@ -36,8 +35,7 @@ import com.github.springtestdbunit.DbUnitTestExecutionListener;
import com.github.springtestdbunit.annotation.DatabaseSetup;
import com.github.springtestdbunit.annotation.ExpectedDatabase;
import es.uvigo.esei.daa.DAAExampleApplication;
import es.uvigo.esei.daa.LoginFilter;
import es.uvigo.esei.daa.DAAExampleTestApplication;
import es.uvigo.esei.daa.entities.User;
import es.uvigo.esei.daa.listeners.ApplicationContextBinding;
import es.uvigo.esei.daa.listeners.ApplicationContextJndiBindingTestExecutionListener;
......@@ -64,7 +62,7 @@ import es.uvigo.esei.daa.listeners.DbManagementTestExecutionListener;
public class UsersResourceTest extends JerseyTest {
@Override
protected Application configure() {
return new DAAExampleApplication();
return new DAAExampleTestApplication();
}
@Override
......@@ -87,7 +85,6 @@ public class UsersResourceTest extends JerseyTest {
new ServletContainer(ResourceConfig.forApplication(configure()))
)
.servletPath("/rest")
.addFilter(LoginFilter.class, "login-filter")
.build();
}
......@@ -96,7 +93,7 @@ public class UsersResourceTest extends JerseyTest {
final String admin = adminLogin();
final Response response = target("users/" + admin).request()
.cookie("token", userToken(admin))
.header("Authorization", "Basic " + userToken(admin))
.get();
assertThat(response, hasOkStatus());
......@@ -111,7 +108,7 @@ public class UsersResourceTest extends JerseyTest {
final String otherUser = normalLogin();
final Response response = target("users/" + otherUser).request()
.cookie("token", userToken(admin))
.header("Authorization", "Basic " + userToken(admin))
.get();
assertThat(response, hasOkStatus());
......@@ -125,7 +122,7 @@ public class UsersResourceTest extends JerseyTest {
final String login = normalLogin();
final Response response = target("users/" + login).request()
.cookie("token", userToken(login))
.header("Authorization", "Basic " + userToken(login))
.get();
assertThat(response, hasOkStatus());
......@@ -138,22 +135,22 @@ public class UsersResourceTest extends JerseyTest {
public void testGetNoCredentials() throws IOException {
final Response response = target("users/" + normalLogin()).request().get();
assertThat(response, hasForbidden());
assertThat(response, hasUnauthorized());
}
@Test
public void testGetBadCredentials() throws IOException {
final Response response = target("users/" + adminLogin()).request()
.cookie("token", "YmFkOmNyZWRlbnRpYWxz")
.header("Authorization", "Basic YmFkOmNyZWRlbnRpYWxz")
.get();
assertThat(response, hasForbidden());
assertThat(response, hasUnauthorized());
}
@Test
public void testGetIllegalAccess() throws IOException {
final Response response = target("users/" + adminLogin()).request()
.cookie("token", userToken(normalLogin()))
.header("Authorization", "Basic " + userToken(normalLogin()))
.get();
assertThat(response, hasUnauthorized());
......
......@@ -20,9 +20,12 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.html5.LocalStorage;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
......@@ -65,14 +68,23 @@ public class PeopleWebTest {
public void setUp() throws Exception {
final String baseUrl = "http://localhost:9080/DAAExample/";
driver = new FirefoxDriver();
final FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("browser.privatebrowsing.autostart", true);
final FirefoxOptions options = new FirefoxOptions(DesiredCapabilities.firefox());
options.setProfile(profile);
final FirefoxDriver firefoxDriver;
driver = firefoxDriver = new FirefoxDriver();
driver.get(baseUrl);
// Driver will wait DEFAULT_WAIT_TIME if it doesn't find and element.
driver.manage().timeouts().implicitlyWait(DEFAULT_WAIT_TIME, TimeUnit.SECONDS);
driver.manage().window().maximize();
// Login as "admin:adminpass"
driver.manage().addCookie(new Cookie("token", "YWRtaW46YWRtaW5wYXNz"));
final LocalStorage localStorage = firefoxDriver.getLocalStorage();
localStorage.setItem("authorization-token", "YWRtaW46YWRtaW5wYXNz");
mainPage = new MainPage(driver, baseUrl);
mainPage.navigateTo();
......
......@@ -14,6 +14,6 @@
<people id="10" name="Juan" surname="Jiménez" />
<people id="11" name="John" surname="Doe" />
<users login="admin" password="43f413b773f7d0cfad0e8e6529ec1249ce71e8697919eab30d82d800a3986b70" />
<users login="normal" password="688f21dd2d65970f174e2c9d35159250a8a23e27585452683db8c5d10b586336" />
<users login="admin" password="713bfda78870bf9d1b261f565286f85e97ee614efe5f0faf7c34e7ca4f65baca" role="ADMIN"/>
<users login="normal" password="7bf24d6ca2242430343ab7e3efb89559a47784eea1123be989c1b2fb2ef66e83" role="USER" />
</dataset>
\ No newline at end of file
......@@ -12,6 +12,6 @@
<people id="9" name="Julia" surname="Justa" />
<people id="10" name="Juan" surname="Jiménez" />
<users login="admin" password="43f413b773f7d0cfad0e8e6529ec1249ce71e8697919eab30d82d800a3986b70" />
<users login="normal" password="688f21dd2d65970f174e2c9d35159250a8a23e27585452683db8c5d10b586336" />
<users login="admin" password="713bfda78870bf9d1b261f565286f85e97ee614efe5f0faf7c34e7ca4f65baca" role="ADMIN"/>
<users login="normal" password="7bf24d6ca2242430343ab7e3efb89559a47784eea1123be989c1b2fb2ef66e83" role="USER" />
</dataset>
\ No newline at end of file
......@@ -13,6 +13,6 @@
<people id="9" name="Julia" surname="Justa" />
<people id="10" name="Juan" surname="Jiménez" />
<users login="admin" password="43f413b773f7d0cfad0e8e6529ec1249ce71e8697919eab30d82d800a3986b70" />
<users login="normal" password="688f21dd2d65970f174e2c9d35159250a8a23e27585452683db8c5d10b586336" />
<users login="admin" password="713bfda78870bf9d1b261f565286f85e97ee614efe5f0faf7c34e7ca4f65baca" role="ADMIN"/>
<users login="normal" password="7bf24d6ca2242430343ab7e3efb89559a47784eea1123be989c1b2fb2ef66e83" role="USER" />
</dataset>
\ No newline at end of file
......@@ -10,4 +10,5 @@
<!ATTLIST users
login CDATA #IMPLIED
password CDATA #IMPLIED
role CDATA #IMPLIED
>
......@@ -13,6 +13,6 @@
<people id="9" name="Julia" surname="Justa" />
<people id="10" name="Juan" surname="Jiménez" />
<users login="admin" password="43f413b773f7d0cfad0e8e6529ec1249ce71e8697919eab30d82d800a3986b70" />
<users login="normal" password="688f21dd2d65970f174e2c9d35159250a8a23e27585452683db8c5d10b586336" />
<users login="admin" password="713bfda78870bf9d1b261f565286f85e97ee614efe5f0faf7c34e7ca4f65baca" role="ADMIN"/>
<users login="normal" password="7bf24d6ca2242430343ab7e3efb89559a47784eea1123be989c1b2fb2ef66e83" role="USER" />
</dataset>
\ No newline at end of file
......@@ -8,5 +8,6 @@ CREATE TABLE people (
CREATE TABLE users (
login VARCHAR(100) NOT NULL,
password VARCHAR(64) NOT NULL,
role VARCHAR(5) NOT NULL,
PRIMARY KEY (login)
);
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" standalone="no"?><!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--><!-- Note: A "Server" is not itself a "Container", so you may not
define subcomponents such as "Valves" at this level.
Documentation at /docs/config/server.html
-->
<Server port="9205" shutdown="SHUTDOWN">
<Listener className="org.apache.catalina.startup.VersionLoggerListener"/>
<!-- Security listener. Documentation at /docs/config/listeners.html
<Listener className="org.apache.catalina.security.SecurityListener" />
-->
<!--APR library loader. Documentation at /docs/apr.html -->
<Listener SSLEngine="on" className="org.apache.catalina.core.AprLifecycleListener"/>
<!-- Prevent memory leaks due to use of particular java/javax APIs-->
<Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener"/>
<Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"/>
<Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener"/>
<!-- Global JNDI resources
Documentation at /docs/jndi-resources-howto.html
-->
<GlobalNamingResources>
<!-- Editable user database that can also be used by
UserDatabaseRealm to authenticate users
-->
<Resource auth="Container" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" name="UserDatabase" pathname="conf/tomcat-users.xml" type="org.apache.catalina.UserDatabase"/>
</GlobalNamingResources>
<!-- A "Service" is a collection of one or more "Connectors" that share
a single "Container" Note: A "Service" is not itself a "Container",
so you may not define subcomponents such as "Valves" at this level.
Documentation at /docs/config/service.html
-->
<Service name="Catalina">
<!--The connectors can use a shared executor, you can define one or more named thread pools-->
<!--
<Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
maxThreads="150" minSpareThreads="4"/>
-->
<!-- A "Connector" represents an endpoint by which requests are received
and responses are returned. Documentation at :
Java HTTP Connector: /docs/config/http.html
Java AJP Connector: /docs/config/ajp.html
APR (HTTP/AJP) Connector: /docs/apr.html
Define a non-SSL/TLS HTTP/1.1 Connector on port 8080
-->
<Connector SSLEnabled="false" URIEncoding="ISO-8859-1" connectionTimeout="20000" port="9080" protocol="HTTP/1.1" redirectPort="9443" scheme="http" secure="false"/>
<!-- A "Connector" using the shared thread pool-->
<!--
<Connector executor="tomcatThreadPool"
port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
-->
<!-- Define a SSL/TLS HTTP/1.1 Connector on port 8443
This connector uses the NIO implementation. The default
SSLImplementation will depend on the presence of the APR/native
library and the useOpenSSL attribute of the
AprLifecycleListener.
Either JSSE or OpenSSL style configuration may be used regardless of
the SSLImplementation selected. JSSE style configuration is used below.
-->
<!--
<Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
maxThreads="150" SSLEnabled="true">
<SSLHostConfig>
<Certificate certificateKeystoreFile="conf/localhost-rsa.jks"
type="RSA" />
</SSLHostConfig>
</Connector>
-->
<!-- Define a SSL/TLS HTTP/1.1 Connector on port 8443 with HTTP/2
This connector uses the APR/native implementation which always uses
OpenSSL for TLS.
Either JSSE or OpenSSL style configuration may be used. OpenSSL style
configuration is used below.
-->
<!--
<Connector port="8443" protocol="org.apache.coyote.http11.Http11AprProtocol"
maxThreads="150" SSLEnabled="true" >
<UpgradeProtocol className="org.apache.coyote.http2.Http2Protocol" />
<SSLHostConfig>
<Certificate certificateKeyFile="conf/localhost-rsa-key.pem"
certificateFile="conf/localhost-rsa-cert.pem"
certificateChainFile="conf/localhost-rsa-chain.pem"
type="RSA" />
</SSLHostConfig>
</Connector>
-->
<!-- Define an AJP 1.3 Connector on port 8009 -->
<Connector port="9009" protocol="AJP/1.3" redirectPort="9443"/>
<!-- An Engine represents the entry point (within Catalina) that processes
every request. The Engine implementation for Tomcat stand alone
analyzes the HTTP headers included with the request, and passes them
on to the appropriate Host (virtual host).
Documentation at /docs/config/engine.html -->
<!-- You should set jvmRoute to support load-balancing via AJP ie :
<Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
-->
<Engine defaultHost="localhost" name="Catalina">
<!--For clustering, please take a look at documentation at:
/docs/cluster-howto.html (simple how to)
/docs/config/cluster.html (reference documentation) -->
<!--
<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
-->
<!-- Use the LockOutRealm to prevent attempts to guess user passwords
via a brute-force attack -->
<Realm className="org.apache.catalina.realm.LockOutRealm">
<!-- This Realm uses the UserDatabase configured in the global JNDI
resources under the key "UserDatabase". Any edits
that are performed against this UserDatabase are immediately
available for use by the Realm. -->
<Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/>
</Realm>
<Realm className="org.apache.catalina.realm.JDBCRealm"
driverName="org.hsqldb.jdbc.JDBCDriver"
connectionURL="jdbc:hsqldb:hsql://localhost/daatestdb?user=sa"
userTable="users" userNameCol="login" userCredCol="password"
userRoleTable="users" roleNameCol="role" />
<Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true">
<!-- SingleSignOn valve, share authentication between web applications
Documentation at: /docs/config/valve.html -->
<!--
<Valve className="org.apache.catalina.authenticator.SingleSignOn" />
-->
<!-- Access log processes all example.
Documentation at: /docs/config/valve.html
Note: The pattern used is equivalent to using pattern="common" -->
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" pattern="%h %l %u %t &quot;%r&quot; %s %b" prefix="localhost_access_log." suffix=".txt"/>
</Host>
</Engine>
</Service>
</Server>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" standalone="no"?><!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--><!-- Note: A "Server" is not itself a "Container", so you may not
define subcomponents such as "Valves" at this level.
Documentation at /docs/config/server.html
-->
<Server port="10205" shutdown="SHUTDOWN">
<Listener className="org.apache.catalina.startup.VersionLoggerListener"/>
<!-- Security listener. Documentation at /docs/config/listeners.html
<Listener className="org.apache.catalina.security.SecurityListener" />
-->
<!--APR library loader. Documentation at /docs/apr.html -->
<Listener SSLEngine="on" className="org.apache.catalina.core.AprLifecycleListener"/>
<!-- Prevent memory leaks due to use of particular java/javax APIs-->
<Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener"/>
<Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"/>
<Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener"/>
<!-- Global JNDI resources
Documentation at /docs/jndi-resources-howto.html
-->
<GlobalNamingResources>
<!-- Editable user database that can also be used by
UserDatabaseRealm to authenticate users
-->
<Resource auth="Container" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" name="UserDatabase" pathname="conf/tomcat-users.xml" type="org.apache.catalina.UserDatabase"/>
</GlobalNamingResources>
<!-- A "Service" is a collection of one or more "Connectors" that share
a single "Container" Note: A "Service" is not itself a "Container",
so you may not define subcomponents such as "Valves" at this level.
Documentation at /docs/config/service.html
-->
<Service name="Catalina">
<!--The connectors can use a shared executor, you can define one or more named thread pools-->
<!--
<Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
maxThreads="150" minSpareThreads="4"/>
-->
<!-- A "Connector" represents an endpoint by which requests are received
and responses are returned. Documentation at :
Java HTTP Connector: /docs/config/http.html
Java AJP Connector: /docs/config/ajp.html
APR (HTTP/AJP) Connector: /docs/apr.html
Define a non-SSL/TLS HTTP/1.1 Connector on port 8080
-->
<Connector SSLEnabled="false" URIEncoding="ISO-8859-1" connectionTimeout="20000" port="9080" protocol="HTTP/1.1" redirectPort="9443" scheme="http" secure="false"/>
<!-- A "Connector" using the shared thread pool-->
<!--
<Connector executor="tomcatThreadPool"
port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
-->
<!-- Define a SSL/TLS HTTP/1.1 Connector on port 8443
This connector uses the NIO implementation. The default
SSLImplementation will depend on the presence of the APR/native
library and the useOpenSSL attribute of the
AprLifecycleListener.
Either JSSE or OpenSSL style configuration may be used regardless of
the SSLImplementation selected. JSSE style configuration is used below.
-->
<!--
<Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
maxThreads="150" SSLEnabled="true">
<SSLHostConfig>
<Certificate certificateKeystoreFile="conf/localhost-rsa.jks"
type="RSA" />
</SSLHostConfig>
</Connector>
-->
<!-- Define a SSL/TLS HTTP/1.1 Connector on port 8443 with HTTP/2
This connector uses the APR/native implementation which always uses
OpenSSL for TLS.
Either JSSE or OpenSSL style configuration may be used. OpenSSL style
configuration is used below.
-->
<!--
<Connector port="8443" protocol="org.apache.coyote.http11.Http11AprProtocol"
maxThreads="150" SSLEnabled="true" >
<UpgradeProtocol className="org.apache.coyote.http2.Http2Protocol" />
<SSLHostConfig>
<Certificate certificateKeyFile="conf/localhost-rsa-key.pem"
certificateFile="conf/localhost-rsa-cert.pem"
certificateChainFile="conf/localhost-rsa-chain.pem"
type="RSA" />
</SSLHostConfig>
</Connector>
-->
<!-- Define an AJP 1.3 Connector on port 8009 -->
<Connector port="9009" protocol="AJP/1.3" redirectPort="9443"/>
<!-- An Engine represents the entry point (within Catalina) that processes
every request. The Engine implementation for Tomcat stand alone
analyzes the HTTP headers included with the request, and passes them
on to the appropriate Host (virtual host).
Documentation at /docs/config/engine.html -->
<!-- You should set jvmRoute to support load-balancing via AJP ie :
<Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
-->
<Engine defaultHost="localhost" name="Catalina">
<!--For clustering, please take a look at documentation at:
/docs/cluster-howto.html (simple how to)
/docs/config/cluster.html (reference documentation) -->
<!--
<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
-->
<!-- Use the LockOutRealm to prevent attempts to guess user passwords
via a brute-force attack -->
<Realm className="org.apache.catalina.realm.LockOutRealm">
<!-- This Realm uses the UserDatabase configured in the global JNDI
resources under the key "UserDatabase". Any edits
that are performed against this UserDatabase are immediately
available for use by the Realm. -->
<Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/>
</Realm>
<Realm className="org.apache.catalina.realm.JDBCRealm"
driverName="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost/daaexample"
connectionName="daa"
connectionPassword="daa"
userTable="users" userNameCol="login" userCredCol="password"
userRoleTable="users" roleNameCol="role" digest="SHA-256">
<CredentialHandler className="org.apache.catalina.realm.MessageDigestCredentialHandler"
algorithm="SHA-256"/>
</Realm>
<Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true">
<!-- SingleSignOn valve, share authentication between web applications
Documentation at: /docs/config/valve.html -->
<!--
<Valve className="org.apache.catalina.authenticator.SingleSignOn" />
-->
<!-- Access log processes all example.
Documentation at: /docs/config/valve.html
Note: The pattern used is equivalent to using pattern="common" -->
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" pattern="%h %l %u %t &quot;%r&quot; %s %b" prefix="localhost_access_log." suffix=".txt"/>
</Host>
</Engine>
</Service>
</Server>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment