Tuesday, June 21, 2016

Angular 2 Exceptions: TypeError: Cannot read property 'annotations' of undefined

After playing with the newest incarnation of the Angular 2 Router (version 3.0.0-alpha.7) on a seperate test branch, I came back to my mainline branch and cleared my node_modules, build, tmp, and typings directories just to be safe. After reinstalling my npm modules (npm install), I received this gem, "TypeError: Cannot read property 'annotations' of undefined". Knowing that it was working prior to creating my test branch, and after some frustration examined the error a bit closer and saw that the html template causing the issue was related to the the routerLink directive, or more generally the Angular Router package. Digging into it a bit more I discovered that my npm semver for @angular/router-deprecated was "^2.0.0-rc.1" instead of "2.0.0-rc.1" and therefore was installing the Angular 2 RC-2 version of the deprecated router and was causing the error. After correcting the package, more specifcially the semver, for router-deprecated to 2.0.0-rc.1 and re-running npm install, all was well with the world.

The full exception is:

Friday, June 17, 2016

Angular 2 Exceptions: TypeError: (msg || "").replace is not a function

While performing tdd using the Angular CLI, I have come across this exception a few times. In most cases this is caused by a missing import.  The Angular CLI kicks off a test before an import has been added to the component (or service, etc).  If you have the benefit of an IDE, check that it has not highlighted a problem with one of your imports.

The full exception is:

Tuesday, April 5, 2016

Grails 3 war file naming issues in Jenkins

Correcting the war file/artifact/package name in grails package

By default my Jenkins build server puts its projects into a directory called 'workspace' so when I run grails package it creates a war/jar called workspace-0.1.war/jar.  In order to generate the correct jar/war file name, you can create a file called settings.gradle in the root of the project with a single property and specify the name you would like:

and when you run grails package it will create the appropriate my-project-0.1.jar/war



Saturday, January 23, 2016

Spring Cloud - Config Server

Setting up the Spring Cloud Config Server

In this post we will be setting up a Spring Cloud Config Server to externalize configuration properties for future Grails 3 applications.  This will be a bare bones application without security for now.


The easiest method to get started is to create a Spring Boot application from the Spring Initializr and include the Spring Cloud Config Server.  I will be using a Gradle project and Spring Boot 1.3.2.  Enter your desired group (com.morkenbarware) and artifact (config) in the Spring Initializr and download a new project.

Spring Initializr


Configuration changes to this ConfigApplication will be pretty minimal as most of the default Boot application settings will be sufficient for now, but we do need to add an annotation and a few config settings to enable the configuration endpoints.


In order to enable the configuration endpoints that other applications will use, we need to add one annotation to the Application class (ConfigApplication) in the application.

Add the import import; and the annotation @EnableConfigServer to the Application (ConfigApplication) class as follows:

Configuration Settings:

Spring Cloud Config Server primarily uses Git repositories to store properties, so we first need to create a new Git repository to hold our application properties.

Create Local Git Repository (to hold our external properties)

In production this would probably be a web-based Git repo or at least a remote repo, but for simplicity, I will create a local repo to hold my configuration information.  I keep all of my development projects in a projects folder under my user directory, so my config repo will be in /home/me/projects/config.  In this directory, create a file or application.yml depending on your configuration preference.

In addition to the or yml file create another file called or example.yml depending on your configuration preference.
Once these two files have been created, commit the changes (git commit -am 'initial properties') to the Git repo.

By adding an file to the repo, any Cloud Config Client application that connects to this Config Server will receive these properties unless overriden by a more specific property/yml file.  In our case, when we specify:
 audit.config.source = cloud in the application.yml and
 audit.config.source = cloud example in the example.yml file,
if we create an application called example, it will receive "cloud example" because the example.yml file is more specific to that application. (application.yml > example.yml > example-production.yml)

Config Server Settings:

Next, we need to configure the actual Config Server Application.  We need to "connect" to our local Git repo using and expose the config server on the conventional cloud config port 8888 using server.port. Your should look like the following.

With that done... let's fire up the config server and see what we have accomplished.
./gradlew bootRun

After executing the gradle task, you should see a lot of output and eventually something that says:
Tomcat started on port 8888.  If you go to the running application and change the url to http://localhost:8888/example/development/ you should see two different property values for audit.config.source and if you go to http://localhost:8888/someapp/development/ you will only see one audit.config.source from that applies to all applications.

Next, we will create a Grails 3 application to connect to our Cloud Config Server and see how they work together.


Tuesday, August 18, 2015

Grails 3 and Spring Security Plugin

A huge thanks to Burt Beckwith and others for their work on the Spring Security Plugin for Grails 3!

For more information, see the Grails documentation or the github repository

Friday, May 29, 2015

Grails 3 App with Security (Part 3) - Password Encoding with Bcrypt

This is the third post in the Grails 3 App with Security series, so if you have questions about dependencies, please consult the the first and second posts. In this post we will be adding BCrypt password encoding to our GORM-based user and authentication provider. As for the previous steps, my github repository for this series contains a tag ('GORM-based auth with bcrypt') with this code below.

To demonstrate that the application is encoding the password with BCrypt we will use the dbConsole provided in Grails. However, this interface uses frames and does not handle CSRF tokens, so we need to do a little configuration to display the dbConsole. I would suggest reverting these changes if you plan to put your application into production as they disable CSRF and frame protection. With those warnings in place, let's make the changes.


At this point, when you run the app you should be able to navigate to http://localhost:8080/dbconsole/ and see the H2 web-client. Change the JDBC URL if necessary to connect to the in-memory database (Mine is jdbc:h2:mem:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE) and connect. Now inside the H2 client, when you look at the records in the USER table, you will see the passwords are stored in plain-text. That is not good, but easily fixed.

Adding Password Encoding (BCrypt)

In order to add password encoding to our application, we need to do 3 things:

  1. Create a password encoder bean
  2. Add code to encode our passwords when creating/updating user's passwords
  3. Tell our authentication provider what password encoding we are using, so it can appropriately match existing passwords

Create a Password Encoding bean

Spring Security already comes with a BCrypt password encoder, so we just need to wire it up in our Spring beans. Add the following code to resources.groovy


Encode passwords when creating/updating user's passwords

Next, we need to utilize this bean when creating a user or updating a user's password. Again, we will raid the Spring-Security-Core plugin from Grails 2, and add some code to the insert and update hooks provided by GORM to encode the user's password before saving/updating the user object.


Configure Authentication Provider

Finally, we need to tell the authentication provider what password encoding we are using, so it can appropriately match the user credentials when they try to authenticate. Fortunately, all we have to do is add a few lines to the SecurityConfiguration and we are done.


Monday, May 11, 2015

Grails 3 App with Security (Part 2) - Gorm-based authentication

This is the second post in the Grails 3 App with Security series, so if you have questions about dependencies, please consult the first post. In this post we will setting up Spring Security in Grails 3 using Gorm-based authentication and after finishing, I'll think be happily surprised at just how easy it is to add Gorm. Unfortunately, my laptop crashed while creating this post, so if you come across any issues with the code samples or have found a better method for anything I have presented, please provide a comment at the bottom. The github repository with this code will be updated shortly.

Before we begin, let's get some clean up out of the way. Grails 3 (or more specifically Spring Boot) will scream at you about having second level cache enabled, but not configured after you add the Gorm classes, so let's just disable second level cache for now. I added the following just before the datasource properties, but you are welcome to add it anywhere in application.yml or configure second level cache as needed.



        use_second_level_cache: false
        use_query_cache: false


With that out of the way, let's begin by adding our Gorm domain classes (User, Authority, and UserAuthority). If you have been using Spring-Security-Core plugin for any length of time, the following classes should look pretty familiar because I basically copied from the Grails 2 plugin.


package example

class User {

    String username
    String password
    boolean enabled = true
    boolean accountExpired
    boolean accountLocked
    boolean credentialsExpired

    static constraints = {
        username blank: false, unique: true
        password blank: false

    static mapping = {
        password column: '`password`'

    Set getAuthorities() {
        UserAuthority.findAllByUser(this).collect { it.authority }

} // Blogger really wants to close the authority 'tag', so here go Blogger 


package example

class Authority {

    String authority

    static mapping = {
        cache true

    static constraints = {
        authority blank: false, unique: true


package example

import org.apache.commons.lang.builder.HashCodeBuilder

class UserAuthority implements Serializable {

    private static final long serialVersionUID = 1

    User user
    Authority authority

    boolean equals(other) {
        if (!(other instanceof UserAuthority)) {
            return false

        other.user?.id == user?.id &&
            other.authority?.id == authority?.id

    int hashCode() {
        def builder = new HashCodeBuilder()
        if (user) builder.append(
        if (authority) builder.append(

    static UserAuthority get(long userId, long authorityId) {
        UserAuthority.where {
            user == User.load(userId) &&
            authority == Authority.load(authorityId)

    static boolean exists(long userId, long authorityId) {
        UserAuthority.where {
            user == User.load(userId) &&
            authority == Authority.load(authorityId)
        }.count() > 0

    static UserAuthority create(User user, Authority authority, boolean flush = false) {
        def instance = new UserAuthority(user: user, authority: authority) flush, insert: true)

    static boolean remove(User u, Authority r) {
        if (u == null || r == null) return false

        int rowCount = UserAuthority.where {
            user == User.load( &&
                    authority == Authority.load(

        rowCount > 0

    static void removeAll(User u) {
        if (u == null) return

        UserAuthority.where {
            user == User.load(

    static void removeAll(Authority r) {
        if (r == null) return

        UserAuthority.where {
            authority == Authority.load(

    static constraints = {
        authority validator: { Authority r, UserAuthority ur ->
            if (ur.user == null) return
            boolean existing = false
            UserAuthority.withNewSession {
                existing = UserAuthority.exists(,
            if (existing) {
                return 'userAuthority.exists'

    static mapping = {
        id composite: ['authority', 'user']
        version false

With the domain classes for our principal/user and authorities/roles in place, let's load two users, user and admin. You could add these in the SecurityConfiguration class, but since most people reading this will be more familiar with Bootstrap, we'll go that route.


import example.*
import grails.util.Environment

class BootStrap {

    def init = { servletContext ->

        switch (Environment.current) {
            case Environment.DEVELOPMENT:

                def user = new User(username: 'user', password: 'user', enabled: true, accountExpired: false, accountLocked: false, credentialsExpired: false ).save(failOnError: true)
                def admin = new User(username: 'admin', password: 'admin', enabled: true, accountExpired: false, accountLocked: false, credentialsExpired: false ).save(failOnError: true)

                def roleUser = new Authority(authority: 'ROLE_USER').save(failOnError: true)
                def roleAdmin = new Authority(authority: 'ROLE_ADMIN').save(failOnError: true)

                UserAuthority.create(user, roleUser, true)
                UserAuthority.create(admin, roleUser, true)
                UserAuthority.create(admin, roleAdmin, true)

            case Environment.PRODUCTION:

    def destroy = {

At this point, we have not accomplished much in terms of authentication, so let's change that now. In order to use the domain classes above, we need to:

  • Create a custom UserDetails class,
  • Create a custom UserDetailsService,
  • Add a bean for userDetailsService in resources.groovy, and
  • Configure authentication with the bean in the SecurityConfiguration class

First, let's create a GrailsUser that will do little more than extend Spring Security User class. The one thing it adds is the `id` field that will hold the Gorm identifier for the User class. Again, we will raid the Spring-Security-Core plugin from Grails 2:


package example;


import java.util.Collection;

public class GrailsUser extends User {

    private static final long serialVersionUID = 1;

    private final Object id;

     * Constructor.
     * @param username the username presented to the
     *        DaoAuthenticationProvider
     * @param password the password that should be presented to the
     *        DaoAuthenticationProvider
     * @param enabled set to true if the user is enabled
     * @param accountNonExpired set to true if the account has not expired
     * @param credentialsNonExpired set to true if the credentials have not expired
     * @param accountNonLocked set to true if the account is not locked
     * @param authorities the authorities that should be granted to the caller if they
     *        presented the correct username and password and the user is enabled. Not null.
     * @param id the id of the domain class instance used to populate this
    public GrailsUser(String username,
                      String password,
                      boolean enabled,
                      boolean accountNonExpired,
                      boolean credentialsNonExpired,
                      boolean accountNonLocked,
                      Collection authorities,
                      Object id) {
        super(username, password, enabled, accountNonExpired, credentialsNonExpired,
                accountNonLocked, authorities); = id;

     * Get the id.
     * @return the id
    public Object getId() {
        return id;

Next, we will create our custom UserDetailsService. Like the domain classes and UserDetails class, there is no point writing something that someone else has already done better, so we will use the UserDetailsService from the Spring-Security-Core plugin in Grails 2.


package example

import grails.transaction.Transactional

class GormUserDetailsService implements UserDetailsService {

    @Transactional(readOnly = true, noRollbackFor = [IllegalArgumentException, UsernameNotFoundException])
    UserDetails loadUserByUsername(String username, boolean loadRoles) throws UsernameNotFoundException {

        def user = User.findWhere(username: username)
        if (!user) {
            log.warn "User not found: $username"
            throw new UsernameNotFoundException('User not found')

        Collection authorities = loadAuthorities(user, username, loadRoles)
        createUserDetails user, authorities

    UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        loadUserByUsername username, true

    protected Collection loadAuthorities(user, String username, boolean loadRoles) {
        if (!loadRoles) {
            return []

        Collection userAuthorities = user.authorities
        def authorities = userAuthorities.collect { new SimpleGrantedAuthority(it.authority) }
        return authorities ?: [NO_ROLE]

    protected UserDetails createUserDetails(user, Collection authorities) {
        new GrailsUser(user.username, user.password, user.enabled, !user.accountExpired, !user.credentialsExpired,
                !user.accountLocked, authorities,
}  //Blogger now wants to close the GrantedAuthority 'tag', so 

Next, let's add a userDetailsService bean to resources.groovy for the GormUserDetailsService. Adding a bean to resources.groovy will take care of adding a Hibernate session and transaction to the service and allow us to use Gorm classes in the service.


import example.GormUserDetailsService
import simpleappwithsecurity.SecurityConfiguration

beans = {

Finally, let's replace the code for in-memory authentication:


    protected void globalConfigure(AuthenticationManagerBuilder auth) throws Exception {

with our shiny GormUserDetailsService


    UserDetailsService userDetailsService
    protected void configure(HttpSecurity http) throws Exception {  
                .antMatchers('/home/**').hasAnyRole('USER', 'ADMIN')  
    protected void globalConfigure(AuthenticationManagerBuilder auth) throws Exception {

Now fire up the app and you should be able to authenticate against the Gorm domain classes

Adding Password Encoding

The next post handles adding a password encoder (BCrypt) to the application