February 18, 2019

RPM Installation of WildFly 15 on CentOS 7

Prerequisite

CentOS 7. I use minimal installation. I also need wget to download harbottle rpm repo (https://pkgs.org/download/wildfly), from which I will need to install WilfFly from. The harbottle repo is a Fedora Project repo. And Fedora is supported by Red Hat.


# yum install wget -y

Install HarBottle RPM Repo


# wget https://harbottle.gitlab.io/harbottle-main/7/x86_64/00703701-harbottle-main-release/harbottle-main-release-7-5.el7.noarch.rpm
# rpm -Uvh harbottle-main-release*rpm

Check the HarBottle RPM.


# rpm -ql harbottle-main-release
/etc/yum.repos.d/harbottle-main.repo
/usr/share/doc/harbottle-main-release-7
/usr/share/doc/harbottle-main-release-7/GPL
# rpm -q --scripts harbottle-main-release
# cat /etc/yum.repos.d/harbottle-main.repo
[harbottle-main]
name=Copr repo for main owned by harbottle
baseurl=https://copr-be.cloud.fedoraproject.org/results/harbottle/main/epel-7-$basearch/
type=rpm-md
skip_if_unavailable=True
gpgcheck=1
gpgkey=https://copr-be.cloud.fedoraproject.org/results/harbottle/main/pubkey.gpg
repo_gpgcheck=0
enabled=1
enabled_metadata=1

gpgcheck=value

Use the gpgcheck option to specify if yum should perform a GPG signature check on packages. Replace value with:

0 — Disable GPG signature-checking on packages in all repositories, including local package installation.

1 (default) — Enable checking of GPG signature on all packages in all repositories, including local package installation. With gpgcheck enabled, all packages' signatures are checked."

https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html/system_administrators_guide/sec-configuring_yum_and_yum_repositories

repo_gpgcheck=0

https://github.com/ComplianceAsCode/content/issues/1596

Check rpm repo server certificate.


# openssl s_client -connect copr-be.cloud.fedoraproject.org:443 -showcerts
...
---
Server certificate
subject=/C=US/ST=North Carolina/L=Raleigh/O=Red Hat, Inc./OU=Fedora Infrastructure/CN=copr.fedorainfracloud.org
issuer=/C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert SHA2 High Assurance Server CA
---
...

Install WilfFly RPM

Install WildFly Current (Now 15.0.1). Dubble check it is the current WildFly version at http://wildfly.org/downloads/.


# yum install wildfly
...
 java-1.8.0-openjdk
 java-1.8.0-openjdk-devel
 java-1.8.0-openjdk-headless
...
Retrieving key from https://copr-be.cloud.fedoraproject.org/results/harbottle/main/pubkey.gpg
Importing GPG key 0xE148E740:
 Userid     : "harbottle_main (None) <harbottle#main@copr.fedorahosted.org>"
 Fingerprint: f1df c563 31a9 d77e a8cc ae17 df9b 4194 e148 e740
 From       : https://copr-be.cloud.fedoraproject.org/results/harbottle/main/pubkey.gpg
...

Tour of the WildFly RPM

Start and Auto Start WildFly.


# systemctl start wildfly
# systemctl enable wildfly

Server log.


# less /usr/share/wildfly/standalone/log/server.log

JBoss Home Standalone


# ll /usr/share/wildfly/standalone/
total 0
lrwxrwxrwx. 1 root root 23 Feb 18 13:51 configuration -> /etc/wildfly/standalone
lrwxrwxrwx. 1 root root 32 Feb 18 13:51 data -> /var/lib/wildfly/standalone/data
lrwxrwxrwx. 1 root root 39 Feb 18 13:51 deployments -> /var/lib/wildfly/standalone/deployments
lrwxrwxrwx. 1 root root 31 Feb 18 13:51 lib -> /var/lib/wildfly/standalone/lib
lrwxrwxrwx. 1 root root 27 Feb 18 13:51 log -> /var/log/wildfly/standalone
lrwxrwxrwx. 1 root root 33 Feb 18 13:51 tmp -> /var/cache/wildfly/standalone/tmp

JBoss System Unit Global Configuration.


# ll /etc/wildfly/
total 12
drwxrwxr-x. 2 root wildfly   53 Feb 18 13:51 appclient
drwxrwxr-x. 2 root wildfly  283 Feb 18 13:51 domain
-rw-r--r--. 1 root root    3035 Jan  5 20:10 jboss-cli.xml
drwxrwxr-x. 3 root wildfly 4096 Feb 18 14:03 standalone
-rw-r--r--. 1 root root     170 Jan 14 17:09 wildfly.conf

# cat /etc/wildfly/wildfly.conf 
# The configuration you want to run
#
WILDFLY_CONFIG=standalone.xml

# The mode you want to run
WILDFLY_MODE=standalone

# The address to bind to
#
WILDFLY_BIND=0.0.0.0

Test It


# systemctl stop firewalld
# ip addr show
...
    inet 192.168.122.43/24 brd 192.168.122.255 scope global noprefixroute dynamic eth0
...

Now open a remote browser and enter http://192.168.122.43:8080/.

November 20, 2018

Setting Global HTTP Session Timeout in JBoss EAP 6 and 7

JBoss EAP 6.x

Edit standalone.xml.


<subsystem xmlns="urn:jboss:domain:web:2.2" default-virtual-server="default-host" native="false" default-session-timeout="15">
...
</subsystem>

JBoss EAP 7.x

Edit standalone.xml.


<subsystem xmlns="urn:jboss:domain:undertow:4.0">
...
    <servlet-container name="default" default-session-timeout="15">
...
    </servlet-container>
...
</subsystem>

Note

You can set this in WEB-INF/web.xml also, but this is better to set globally.

Set HttpOnly and secure for Cookies in JBoss EAP 6 and 7

What is Cookie HttpOnly and secure?

Example

Set-Cookie: a=b; HttpOnly; SameSite=strict; secure

HttpOnly = No JavaScript

SameSite = no cross-origin cookie sharing

secure = SSL only

SameSite is not yet supported in all browser, see https://caniuse.com/#feat=same-site-cookie-attribute

JBoss EAP 6.x

Not supported to set globally. Best effort is deploy Servlet 3.0 web-fragment.xml and deploy overlay which is messy.

Next best in local application WEB-INF/web.xml.


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
...
    <session-config>
        <!-- Session timeout after X MINUTES after no user interaction. -->
        <session-timeout>15</session-timeout>
        <cookie-config>
            <http-only>true</http-only>
            <secure>true</secure>
        </cookie-config>
        <tracking-mode>COOKIE</tracking-mode>
    </session-config>
</web-app>

JBoss EAP 7.x

Edit standalone.xml


<subsystem xmlns="urn:jboss:domain:undertow:4.0">
...
    <servlet-container name="default">
...
        <session-cookie http-only="true" secure="true" />
    </servlet-container>
...
</subsystem>

How to Enable RequestDump in JBoss EAP 6 and 7

What is RequestDump?

It is a great debugging tool, that prints HTTP request and response in jboss server.log.

JBoss EAP EAP 6.1.0 or later

Edit standalone.xml.


<subsystem xmlns="urn:jboss:domain:web:2.2" default-virtual-server="default-host" native="false">
    ...
    <virtual-server name="default-host" enable-welcome-root="true">
        ...
    </virtual-server>
    <valve name="RequestDumperValve" module="org.jboss.as.web" class-name="org.apache.catalina.valves.RequestDumperValve"/>
</subsystem>

JBoss EAP EAP 7.x

Edit standalone.xml.


<subsystem xmlns="urn:jboss:domain:undertow:4.0">
    ...
    <server name="default-server">
        ...
    </server>
    ...
    <filters>
        ...
        <expression-filter name="requestDumperExpression" expression="dump-request"/>
    </filters>
</subsystem>

November 17, 2018

Spring Security

What is it?

A security framework, that competes with a framework that are built in Java EE and theirs servers. And is a mandatory requirement when running Spring Boot.

Prerequisite

  • Will use Spring Tools (STS) version 3 and not version 4, since latest version lacks the built in Tomcat (actually it is a modified Spring Tomcat, Pivotal TC Server).
  • Will use my previous blog example of Getting Started with Spring MVC .
  • Will use jetty maven plugin (org.eclipse.jetty:jetty-maven-plugin) to test and run the application via 'mvn jetty:run'.

Setup


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

Add to the src/main/webapp/WEB-INF/web.xml.


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

and /WEB-INF/spring/security-context.xml to your contextConfigLocation. The complete web.xml looks now with Spring MVC:


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    version="3.1">

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

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/spring/application-context.xml
            /WEB-INF/spring/security-context.xml
        </param-value>
    </context-param>

    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value></param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

And now an example /WEB-INF/spring/security-context.xml which protectes all HTTP with the role 'ROLE_USER' and in-memory user 'foo' with password 'changeit' and role 'ROLE_USER'.


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:security="http://www.springframework.org/schema/security"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">

    <security:http auto-config="true" use-expressions="false">
        <security:intercept-url pattern="/**" access="ROLE_USER" />
    </security:http>

    <security:authentication-manager>
        <security:authentication-provider>
            <security:password-encoder ref="passwordEncoder" />
            <security:user-service> 
                <security:user name="foo" password="changeit" authorities="ROLE_USER" /> 
            </security:user-service>
        </security:authentication-provider>
    </security:authentication-manager>

    <!-- java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for 
        the id "null" -->
    <bean id="passwordEncoder"
        class="org.springframework.security.crypto.password.NoOpPasswordEncoder"
        factory-method="getInstance" />
</beans>

Architectual Overview

Authorization

Either via XML (or Java which is the requirement for Spring Boot).


<security:http auto-config="true" use-expressions="false">
    <security:intercept-url pattern="/**" access="ROLE_USER" />
</security:http>

What is important is that the rule with highest clearance must come first and then in decreased clearance. The reason for this is because the first rule that passes, will exit the process. Example of a misconfiguration.


<security:http auto-config="true" use-expressions="false">
    <security:intercept-url pattern="/**" access="ROLE_ANONYMOUS" />
    <security:intercept-url pattern="/topsecret/*" access="ROLE_TOP_SECRET" />
</security:http>

This configuration will lead to that everyone will be granted access to '/topsecret/*', since the first rule will be successfull and will overlay any further more restricted authorization rules.

Another way to enforce authoriation is via class or method annotation @org.springframework.security.access.annotation.Secured. Example:


@Secured({ "ROLE_USER" })
public void create(Contact contact) {...}

Authentication

Basic

/WEB-INF/spring/security-context.xml


    <security:http auto-config="true" use-expressions="false">
        <security:http-basic />
        ...
    </security:http>

Form

/WEB-INF/spring/security-context.xml


    <security:http auto-config="true" use-expressions="false">
        <security:form-login login-page="/login"
            login-processing-url="/login" default-target-url="/"
            always-use-default-target="true"
            authentication-failure-url="/login?error=true" />
        ...
    </security:http>

View in JSP.


<form action=${loginVar} method="POST">
Username: <input type="text" name="username" /></br>
Password: <input type="password" name="password" /></br>
<input type="submit" value="Login" />
</form>

Logout

View in JSP.


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
...
<a href="<c:url value="/logout" />">Logout</a>
...

/WEB-INF/spring/security-context.xml


    <security:http auto-config="true" use-expressions="false">
        ...
        <security:logout logout-success-url="/login?logout=true"/>
        ...
    </security:http>

JDBC Module

Add maven dependency


        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>2.1.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.4.185</version>
        </dependency>

WEB-INF/spring/application-context.xml


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <tx:annotation-driven />

    <jdbc:embedded-database id="datasource" type="H2">
        <jdbc:script location="classpath:initdb.sql" />
    </jdbc:embedded-database>

    ...
</beans>

src/main/resources/initdb.sql


drop table users if exists;
drop table authorities if exists;

create table users(
    username varchar_ignorecase(50) not null primary key,
    password varchar_ignorecase(50) not null,
    enabled boolean not null
);

create table authorities (
    username varchar_ignorecase(50) not null,
    authority varchar_ignorecase(50) not null,
    constraint fk_authorities_users foreign key(username) references users(username)
);
create unique index ix_auth_username on authorities (username,authority);

insert into users(username, password, enabled) values ('foodb', 'changeit', true);
insert into authorities(username, authority) values ('foodb', 'ROLE_USER');

src/main/webapp/WEB-INF/spring/security-context.xml


    <security:authentication-manager>
        <security:authentication-provider>
            <security:password-encoder ref="passwordEncoder" />
            <security:jdbc-user-service data-source-ref="datasource" />
        </security:authentication-provider>
    </security:authentication-manager>

Advanced JDBC Module - Groups

src/main/webapp/WEB-INF/spring/security-context.xml


    <security:authentication-manager>
        <security:authentication-provider>
            <security:password-encoder ref="passwordEncoder" />
            <security:jdbc-user-service data-source-ref="datasource"
                group-authorities-by-username-query="select g.id, g.group_name, ga.authority
                    from groups g, group_members gm, group_authorities ga
                    where gm.username = ? and g.id = ga.group_id and g.id = gm.group_id" />
        </security:authentication-provider>
    </security:authentication-manager>

src/main/resources/initdb.sql add the Group Authorities tables


create table groups (
    id bigint generated by default as identity(start with 0) primary key,
    group_name varchar_ignorecase(50) not null
);

create table group_authorities (
    group_id bigint not null,
    authority varchar(50) not null,
    constraint fk_group_authorities_group foreign key(group_id) references groups(id)
);

create table group_members (
    id bigint generated by default as identity(start with 0) primary key,
    username varchar(50) not null,
    group_id bigint not null,
    constraint fk_group_members_group foreign key(group_id) references groups(id)
);

And remove the 'insert into authorities' and instead insert into group authorities tables.


insert into users(username, password, enabled) values ('foodb', 'changeit', true);
--insert into authorities(username, authority) values ('foodb', 'ROLE_USER');
insert into groups(id, group_name) values (1, 'Admin');
insert into group_authorities(group_id, authority) values (1, 'ROLE_USER');
insert into group_members(id, username, group_id) values (1, 'foodb', 1);

Hash Algorithm

https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/crypto/password/PasswordEncoder.html

LDAP Module

Will use The Apache Directory, which is written in Java.

Download Apache DS. Download Archive zip/tar.gz.

Apache Directory Studio. Download Archive zip/tar.gz.

Unzip both zip/tar.gz to your desktop.


$ cd /home/magnuskkarlsson/bin/apacheds-2.0.0.AM25/bin
$ ./apacheds.sh start
Using ADS_HOME:    /home/magnuskkarlsson/bin/apacheds-2.0.0.AM25
Using JAVA_HOME:   

Starting ApacheDS instance 'default'...

Now start your 'ApacheDirectoryStudio'. Goto view 'LDAP Servers', click new and add ApacheDS 2.0.0 server. Then stop your apacheds server.


$ ./apacheds.sh stop

Return to studio and right click on you ApacheDS server and choose 'Create a Connection' and right click again and choose 'Run'.

Now we need to add a new partition for your database. Switch to LDAP Servers and double click on your local ldap, in the main space click Partitions and click Add.

After editing click Save. Then stop you local ldap and then start. After restarted double click on Connection and you will see your new partition.

Now we are going to import our users. Right click on Root DSE and choose Import and LDIF Import.

src/test/resources/spring-security-ldap.ldif


dn: dc=magnuskkarlsson,dc=se
objectclass: top
objectclass: domain
objectclass: extensibleObject
dc: magnuskkarlsson

dn: ou=groups,dc=magnuskkarlsson,dc=se
objectclass: top
objectclass: organizationalUnit
ou: groups

dn: ou=people,dc=magnuskkarlsson,dc=se
objectclass: top
objectclass: organizationalUnit
ou: people


dn: uid=ben,ou=people,dc=magnuskkarlsson,dc=se
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Ben Alex
sn: Alex
uid: ben
userPassword: changeit

dn: uid=bob,ou=people,dc=magnuskkarlsson,dc=se
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Bob Hamilton
sn: Hamilton
uid: bob
userPassword: changeit


dn: cn=user,ou=groups,dc=magnuskkarlsson,dc=se
objectclass: top
objectclass: groupOfUniqueNames
cn: user
uniqueMember: uid=ben,ou=people,dc=magnuskkarlsson,dc=se
uniqueMember: uid=bob,ou=people,dc=magnuskkarlsson,dc=se

dn: cn=admin,ou=groups,dc=magnuskkarlsson,dc=se
objectclass: top
objectclass: groupOfUniqueNames
cn: admin
uniqueMember: uid=ben,ou=people,dc=magnuskkarlsson,dc=se

Now configure Spring Security LDAP, but first we need to add maven dependency.


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

src/main/webapp/WEB-INF/spring/security-context-ldap.xml


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:security="http://www.springframework.org/schema/security"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">

    <security:http auto-config="true" use-expressions="false">
        <security:intercept-url pattern="/**" access="ROLE_USER" />
        <security:logout logout-success-url="/login" />
    </security:http>

    <security:authentication-manager>
        <security:ldap-authentication-provider server-ref="ldapServer" 
            user-dn-pattern="uid={0},ou=people" group-search-base="ou=groups">
        </security:ldap-authentication-provider>
    </security:authentication-manager>

    <security:ldap-server id="ldapServer" 
        url="ldap://localhost:10389/dc=magnuskkarlsson,dc=se" 
        manager-dn="uid=admin,ou=system" manager-password="secret" />
</beans>

Expression-Based Access Control/Spring Expression Language(SPEL)

First you need to declare SPEL bean then change 'use-expressions' to true. Then you can use your expression.

https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#el-access


    <bean class="org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler" />

    <security:http auto-config="true" use-expressions="true">
        
        <security:intercept-url pattern="/**" access="hasRole('ROLE_USER') and hasIpAddress('192.168.1.0/24')" />
        ...
    </security:http>

Spring Security Taglib


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

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

https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#taglibs

Example in your JSP page.


<sec:authorize access="isAuthenticated()">
    Welcome 
    <sec:authentication property="principal.firstName"/> 
    <sec:authentication! property="principal.lastName"/>
</sec:authorize>

<sec:authorize access="hasRole('ROLE_ADMIN')">
    TOP SECRET
</sec:authorize>

Access Control List, ACL

The ACL is used to grant access to specific person and/or rule to specfic instances of a object.

Example. You have reports and some reports (db with primary key e.g. 1 and 3) should only be accessed by user (db primary key user e.g. 1, 5). That can you enforce with ACL.

Or specific reports should only be granted read access, that can also be enforced with ACL.

The downside with ACL is management of this finegrained access control.

https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#dbschema-acl

https://www.baeldung.com/spring-security-acl

CSRF

Use spring security form taglib


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

<form:form ...>
</form>

Eitherwise you need to manually add it.


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

<form ...>
    <sec:csrfInput />
</form>

Java Configuration Part

So far I have configured Spring Security through XML, but today in the spring community is moving to writing java code instead. My opinion is that XML is more concisely and more easy to overview, but XML has a bad reputation in the spring community.

Start class.


package se.magnuskkarlsson.example.springmvc;

import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;

public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {

    public SecurityWebApplicationInitializer() {
        super(SecurityConfig.class);
    }
}

Then the actual authentication and authorization code.


package se.magnuskkarlsson.example.springmvc;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
@ImportResource("/WEB-INF/spring/application-context.xml")
@ComponentScan("se.magnuskkarlsson.example")
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("foojava").password("changeit").roles("USER");
    }
}

November 13, 2018

Getting Started with Spring MVC

The OLD XML Configuration

pom.xml. The jstl and servlet-api is only need if you use JSTL in your JSP pages.


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>se.magnuskkarlsson.examples</groupId>
    <artifactId>example-springmvc-xml</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.build.outputEncoding>UTF-8</project.build.outputEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <failOnMissingWebXml>false</failOnMissingWebXml>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <!-- embedded Jetty server, for testing -->
            <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>9.2.11.v20150529</version>
                <configuration>
                    <scanIntervalSeconds>10</scanIntervalSeconds>
                    <webApp>
                        <contextPath>/</contextPath>
                    </webApp>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

web.xml. The old school, but is good to know, since there are several old references to the XML way.


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    version="3.1">

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/application-context.xml</param-value>
    </context-param>

    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value></param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

/WEB-INF/spring/application-context.xmlIn Spring you can split the Spring XML configuration into several files, but I tend to think that using several configuration files, will only make you wander lost in configuration, so I prefer one configuration file.


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="se.magnuskkarlsson.example.springmvc.controller" />

    <mvc:annotation-driven />

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

Now the actual "app". Spring MVC design is much like Struts with one Servlet that dispatch request. HelloController


package se.magnuskkarlsson.example.springmvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class HelloController {

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String hello(@RequestParam(value = "name", required = false, defaultValue = "World") String name,
            Model model) {

        model.addAttribute("name", name);
        return "hello";
    }
}

And your app view - WEB-INF/view/hello.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello Spring MVC</title>
</head>
<body>
    <h2>Hello Java ${name}!</h2>
</body>
</html>

And finally lets test it by running 'mvn jetty:run' and open http://localhost:8080/hello?name=foo.


$ mvn clean install; mvn jetty:run

The NEW Java Configuration

Now we delete web.xml and /WEB-INF/spring/application-context.xml. And manually write code that do the same thing.


package se.magnuskkarlsson.example.springmvc;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.context.support.GenericWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

public class MainWebAppInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext container) throws ServletException {
        // Create the 'root' Spring application context
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.scan("se.magnuskkarlsson");

        // Manage the lifecycle of the root application context
        container.addListener(new ContextLoaderListener(rootContext));

        // Register and map the dispatcher servlet
        ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher",
                new DispatcherServlet(new GenericWebApplicationContext()));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");
    }
}

package se.magnuskkarlsson.example.springmvc;

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.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@EnableWebMvc
@Configuration
@ComponentScan(basePackages = { "se.magnuskkarlsson.example.springmvc.controller" })
public class AppConfig implements WebMvcConfigurer {

    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver bean = new InternalResourceViewResolver();
        bean.setPrefix("/WEB-INF/view/");
        bean.setSuffix(".jsp");
        return bean;
    }
}

November 11, 2018

TestNG

Comparison with JUnit

TestNG is a direct competitor with JUnit. But that may change with JUnit 5.

The main advantage of TestNG compared with JUnit 4, is that TestNG has build in support of Data Provider and Parallel support.

Below follows a summary of feature in TestNG.

Setup

Maven


<dependency>
    <groupId>org.testng</groupId>
    <artifactId>testng</artifactId>
    <version>6.14.3</version>
    <scope>test</scope>
</dependency>

Eclipse

Open Eclipse and click on Help menu and Install New Software. Enter http://beust.com/eclipse

And then next and finish plugin installation.

TestNG Annotations


    @BeforeSuite
    @AfterSuite

    @BeforeTest
    @AfterTest

    @BeforeClass
    @AfterClass

    @BeforeMethod
    @AfterMethod

    @Test

    // order, but each test method should be independent
    @Test(priority=0)

Grouping Related Test Methods


    // group test method, so they are executed logical together
    @Test(groups = "cars")

Used for test suite, annotate with attribute group and call group in test suite xml.

TestNG Assert


    org.testng.Assert
        assertTrue
        assertFalse
        fail
        assertEquals
        assertNotNull
        assertNull
        assertSame
        assertNotSame

Running a Test Suite


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="tests">
    <test name="backend">
        <classes>
            <class name="se.magnuskkarksson.testng.SimpleTest" />
        </classes>
    </test>
</suite>

To run, right click on xml file and choose TestNG Suite

See also for more example of test suite. http://websystique.com/java/testing/testng-suites-example/

For Maven Surefire Plugin see http://maven.apache.org/surefire/maven-surefire-plugin/examples/testng.html

Dependent Test Methods


@Test(dependsOnMethods = {"test1"})
public void test1() throws Exception { }

@Test(dependsOnMethods = {"test2"})
public void test2() throws Exception { }

Disable and Timeout Test


@Test(enabled = false)
public void testEnabled() throws Exception { }

// The maximum number of milliseconds
@Test(timeOut = 1000)
public void testTimeConstraint() throws Exception { }

Providing Test Data from XML file


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="tests">
    <test name="backend">
        <parameter name="param1" value="value1" />
        <parameter name="param2" value="value2" />
        <parameter name="param3" value="value3" />
        <classes>
            <class name="se.magnuskkarksson.testng.SimpleTest" />
        </classes>
    </test>
</suite>

@BeforeClass
@Parameters({ "param1", "param2" })
public void beforeClass(String param1, String param2) throws Exception { }

@Test
@Parameters({ "param1" })
public void test(String param1) throws Exception { }

Running Tests in Parallel


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="tests" parallel="tests" thread-count="2">
 
    <test name="front-end">
        <packages>
            <package name="se.magnuskkarlsson.testng.frontend.*" />
        </packages>
    </test>
    <test name="back-end">
        <packages>
            <package name="se.magnuskkarlsson.testng.backend.*" />
        </packages>
    </test>
</suite>

Data Providers


package se.magnuskkarksson.testng;

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class DataProviderTest {

    @Test(dataProvider = "testData")
    public void test(String param1, String param2) throws Exception {
        System.out.println("param1: " + param1 + ", param2: " + param2);
    }

    @DataProvider(name = "testData")
    public Object[][] getTestData() {
        return new Object[][] { //
                { "foo1", "bar1" }, //
                { "foo2", "bar2" } //
        };
    }
}

To reuse testdata move data provider to seperate class.


package se.magnuskkarksson.testng;

import org.testng.annotations.DataProvider;

public class TestData {

    @DataProvider(name = "testData")
    public Object[][] getTestData() {
        return new Object[][] { //
                { "foo1", "bar1" }, //
                { "foo2", "bar2" } //
        };
    }
}

Then modify @Test annotation attribute


package se.magnuskkarksson.testng;

import org.testng.annotations.Test;

public class DataProviderTest {

    @Test(dataProvider = "testData", dataProviderClass = TestData.class)
    public void test(String param1, String param2) throws Exception {
        System.out.println("param1: " + param1 + ", param2: " + param2);
    }
}

TestNG Listeners


org.testng.ITestResult 
org.testng.IInvokedMethodListener
org.testng.ITestListener
org.testng.ISuiteListener

TestNG Reporter Logs and HTML Reports

To create HTML TestNG report add org.testng.Reporter#log() logging to your unit test file. E.g.


@Test
public void aFastTest() {
    Assert.assertTrue(true);
    Reporter.log("Logging.....");
}

Then create test suite xml file and run test suite. Then will a test-output directory be created with a HTML report in it.

TestNG Selenium

Install chrome web browser. On Fedora 28 'yum install google-chrome-stable'

Download chrome webdriver from selenium web page - https://www.seleniumhq.org/download/. Which links to https://chromedriver.storage.googleapis.com/index.html?path=2.43/.

Download zip file and unzip somewhere on disk.

Add selenium for java maven dependency.


<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>3.141.5</version>
    <scope>test</scope>
</dependency>

Write test unit test.


package se.magnuskkarksson.testng;

import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.openqa.selenium.chrome.ChromeDriver;

public class SeleniumParallelTest {

    private String baseUrl;

    private WebDriver driver;

    @BeforeClass
    public void beforeClass() throws Exception {
        baseUrl = "https://www.google.com/";
        System.setProperty("webdriver.chrome.driver",
                "/home/magnuskkarlsson/bin/selenium/chromedriver_linux64/chromedriver");
        driver = new ChromeDriver();
        driver.get(baseUrl);
    }

    @AfterClass
    public void afterClass() throws Exception {
        driver.quit();
    }

    @Test
    public void test() throws Exception {
        String title = driver.getTitle();
        System.out.println("Title: " + title);
        Assert.assertEquals(title, "Google");
    }
}