DZone
Java Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Java Zone > Auto-Generating Spring Security: Custom JDBC Realms

Auto-Generating Spring Security: Custom JDBC Realms

In this post we take a look at a handy bit of code to help generate Spring Security classes, in this case using custom JDBC realms. Read on to find out more!

Martin Farrell user avatar by
Martin Farrell
·
Nov. 14, 16 · Java Zone · Tutorial
Like (5)
Save
Tweet
7.49K Views

Join the DZone community and get the full member experience.

Join For Free

This post builds on the set of spring-security posts I have done, and particularly my last post on Default JDBC Realms. The code is available on GitHub, and spring-security-generator and the instructions to run the application are contained in the previous tutorial.

We also have a requirement to use a custom JDBC realm with the structure:

USER PASSWORD ROLES
customadmin customadmin ROLE_CUSTOM_ADMIN

Custom JDBC Tables

The tables Ive used in this example are renamed versions of the default tables -

create table custom_users (
  username varchar(256),
  password varchar(256),
  enabled boolean
);
create table custom_authorities (
  username varchar(256),
  authority varchar(256)
);
With inserts - 

insert into custom_users (username, password, enabled) values ('customadmin', 'customadmin', true);
insert into custom_authorities (username, authority) values ('customadmin', 'ROLE_CUSTOM_ADMIN');

Spring-Security-Generator

Using spring-security-generator we now select “JDBC Realm (Custom)” and supply the queries:

select username, password, enabled from custom_users where username = ?
select username, authority from custom_authorities where username = ?

The screen configuration is then:

screen-shot-2016-11-07-at-21-00-50

We then generate the code:

package com.glenware.springboot;

import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth)
            throws Exception {
         auth
             .jdbcAuthentication()
                 .dataSource(dataSource)
                   .usersByUsernameQuery(
                   "select username, password, enabled from custom_users where username = ?")
                   .authoritiesByUsernameQuery(
                   "select username, authority from custom_authorities where username = ?");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/webjars/**","/about.html","/rest/**").permitAll()
                .antMatchers("/admin/**").hasAnyRole("CUSTOM_ADMIN")
                .anyRequest().authenticated()
            .and()
                .formLogin()
                    .loginPage("/login")
                    .defaultSuccessUrl("/admin/admin.html")
                    .failureUrl("/login")
                    .permitAll()
             .and()
                .logout()
                    .logoutSuccessUrl("/")
                    .permitAll()
                    ;
    }

}


The key difference between this tutorial and the previous is that we supply the SQL directly to the usersByUsernameQuery and authoritiesByUsernameQuery.

We can now copy this code to the parkrunpb applicaiton, and login using customadmin/customadmin.

Spring Security

Published at DZone with permission of Martin Farrell, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Building HIPAA Compliant APIs
  • How to Gain Competitive Advantage in Software Development With Innovative Technology?
  • Troubleshooting HTTP 502 Bad Gateway in AWS EBS
  • API Security Weekly: Issue 165

Comments

Java Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo