Book Image

SPRING COOKBOOK

Book Image

SPRING COOKBOOK

Overview of this book

Table of Contents (19 chapters)
Spring Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Authenticating users using a database


In this recipe, you'll learn how to use user credentials (username and password) from a database for authentication.

How to do it…

Here are the steps to use user credentials in a database for authentication:

  1. Add the Spring JDBC Maven dependency in pom.xml:

    <dependency> 
        <groupId>org.springframework</groupId> 
        <artifactId>spring-jdbc</artifactId> 
        <version>${spring.version}</version> 
    </dependency> 
  2. In the database, create the users and authorities tables:

    create table users(
      username varchar(50) not null,
      password varchar(50) not null,
      enabled boolean not null default true,
      primary key (username)
    );
    
    create table authorities (
        username varchar(50) not null,
        authority varchar(50) not null,
        constraint fk_authorities_users foreign key(username) references users(username)
    );
    
    create unique index ix_auth_username on authorities (username,authority);    
  3. In the database, add users and...