Spring boot security - create root user on startup - java

My Spring Boot web app uses form authentication with spring-boot-security.
I have two tables:
User
CREATE TABLE user
(
id INT(11) PRIMARY KEY NOT NULL AUTO_INCREMENT,
username VARCHAR(255) NOT NULL,
password CHAR(60) NOT NULL,
//...
);
Role
CREATE TABLE role
(
id INT(11) PRIMARY KEY NOT NULL AUTO_INCREMENT,
r_name VARCHAR(45) NOT NULL
);
CREATE UNIQUE INDEX sys_role_r_name_uindex ON sys_role (r_name);
Join table
CREATE TABLE ref_user_role
(
user_id INT(11) NOT NULL,
role_id INT(11) NOT NULL,
// ...
);
In order to add more users with other roles/priviledges, one has to be of role ROLE_ROOT in sys_role table. This root user has to exist before the add-more-users action, logically.
What I have tried is that
I ran a sql script containing the root-user-insertion statement before I deployed the app. Obviously, I had to also manually generate an encrypted password for this root user.
I grammatically run an sql script to insert the root credentials. My concern is that it might not be safe to include my ROOT user credentials in the data.sql file. If I put encrypted version of the password, I have to encrypt it beforehand.
Another way I can think of is that I can create a root-creation-page ONLY the first time the app starts. I will need a secret code(only the I and the app knows) in addition to the username and password so that no other random people can create the root account.
Are these the common ways to do this?
If not, what are some of the good ways?

If you're using Spring Boot, all you have to do is to place schema.sql and data.sql scripts within resources classpath.
The schema.sql will be in charge of creating your tables and associations between them, and the data.sql will be in charge of initializing your tables with data, so you can put there your insert into tables statements.
when you upload the service these scripts will be executed automatically by Spring Boot each upload.
for further reading take a look at:
http://docs.spring.io/spring-boot/docs/1.4.2.RELEASE/reference/htmlsingle/#howto-database-initialization

Related

Primary key is not loaded from PostgreSQL to JTable

I'm new to PostgreSQL and Java Swing.
In PostgreSQL company database, I have a users table and it has 4 fields: user_id, username, phone, and address.
CREATE TABLE users
(
user_id serial primary key,
username VARCHAR(40) not null,
phone VARCHAR(14) not null,
address VARCHAR(50)
);
I'm trying to load all fields from users table to JTable in Java Swing using Bound (Figure 1).
Then I bind the elements from the table (Figure 2).
As you can see in Figure 2, it shows only 3 fields except user_id. I need to load this user_id field as well because I need to perform CRUD data.
How can I achieve that?
I finally got the solution.
When I import the data from the database to the form, the Model (for example; Users.java) file is generated.
The problem was I firstly generated that file and later I added the user_id column to the database, so guess what, the Model file is somehow not updated and so the user_id is not there.
Therefore, I had manually added getter and setter for the user_id field, and now ok.

Not able to work with tables created with Flyway in H2 database

I am new to flyway and struggling a bit to create tables using flyway in H2 database
I have created tables in my oracle Database using flyway script.
Now I want to perform some Junit test and want to create tables using Flyway script but not in
oracle Database instead I want to create this in H2 database (For unit test).
Flyway script used in my case is different both script have slightly different table structure.
Below is my project structure and configuration used
Below is the configuration present in src/main/resources folder
V1.0.0.0.001__tables.sql
CREATE TABLE COMMAND_ACTION
(COMMAND_TYPE_CD VARCHAR2(50 BYTE) NOT NULL,
ACTION VARCHAR2(50 BYTE) NOT NULL,
ACTION_ORDER NUMBER(*,0) NOT NULL,
CONSTRAINT COMMAND_ACTION_PK PRIMARY KEY (COMMAND_TYPE_CD, ACTION_ORDER),
CONSTRAINT COMMAND_ACTION_FK FOREIGN KEY (ACTION) REFERENCES ACTION_DEFINITION(ACTION)
);
CREATE TABLE COMMAND_ACTION_CONFIGURATION
( COMMAND_TYPE_CD VARCHAR2(50 BYTE) NOT NULL,
ACTION VARCHAR2(50 BYTE) NOT NULL,
CONFIGURATION VARCHAR2(1024 BYTE) NOT NULL);
application.properties
spring.profiles.active=cca
spring.flyway.table=CCA_SCHEMA_VERSION
spring.flyway.baseline-on-migrate=true
spring.flyway.schemas=CCA
spring.flyway.user=cca
spring.flyway.password=cca
application-cca.properties
spring.datasource.url=jdbc:oracle:thin:#linux:8080:devdb
spring.datasource.jdbc-url=jdbc:oracle:thin:#linux:8080:devdb
spring.datasource.username=cca
spring.datasource.password=cca
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
Below is the configuration present in src/test/resources folder
V1.0.0.0.001__tables.sql
CREATE TABLE COMMAND_ACTION
(COMMAND_TYPE_CD VARCHAR2(50 BYTE) NOT NULL,
ACTION VARCHAR2(50 BYTE) NOT NULL,
ACTION_ORDER NUMBER(10,0) NOT NULL,
CONSTRAINT COMMAND_ACTION_PK PRIMARY KEY (COMMAND_TYPE_CD, ACTION_ORDER),
CONSTRAINT COMMAND_ACTION_FK FOREIGN KEY (ACTION) REFERENCES ACTION_DEFINITION(ACTION)
);
CREATE TABLE COMMAND_ACTION_CONFIGURATION
( COMMAND_TYPE_CD VARCHAR2(50 BYTE) NOT NULL,
ACTION VARCHAR2(50 BYTE) NOT NULL,
CONFIGURATION VARCHAR2(1024 BYTE) NOT NULL);
test.properties
spring.profiles.active=test
spring.flyway.table=CCA_SCHEMA_VERSION
spring.flyway.baseline-on-migrate=true
spring.flyway.user=
spring.flyway.password=
application-test.properties
spring.datasource.url=jdbc:h2:mem:DATABASE
spring.datasource.jdbc-url=jdbc:h2:mem:DATABASE
spring.datasource.username=
spring.datasource.password=
spring.database.driverClassName=org.h2.Driver
spring.flyway.locations=classpath:db/migration
spring.jpa.hibernate.ddl-auto=none
# Enabling H2 Console
spring.h2.console.enabled=true
I want that my junit should work independent of my src/resources but not able to achieve instead getting
below error whenever I run maven install
at java.lang.Thread.run(Thread.java:745) [?:1.8.0_66]
2020-02-27T12:45:22,000 DEBUG CommandService [pool-3-thread-1] Timer is started.
2020-02-27T12:45:22,001 ERROR CommandService [pool-3-thread-1] Error in processing command. Error :{}
org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "COMMAND_ACTION" not found; SQL statement:
select ca.command_type_cd, ca.action, cac.CONFIGURATION from command_action ca
left outer join command_action_configuration cac
on ca.command_type_cd = cac.command_type_cd and ca.action = cac.action
order by ca.command_type_cd, ca.action_order [42102-200]
Either some time I get checksum related error.

write persian or arabic alphabets in mysql

I am new in java and I am trying to do a simple project to get familiar with that.
So, I am working on a dynamic web application which I use tomcat as server and MySQL with hibernate provider.
I want to be able to write persian or arabic alphabets in my tables. but unfortunately I cannot.
I have written this query for my database tables:
DROP DATABASE IF EXISTS myDb;
CREATE DATABASE myDb CHARSET = utf8 COLLATE = utf8_general_ci;
USE myDb;
drop table if exists user;
drop table if exists resume;
create table resume(
resumeId INTEGER NOT NULL AUTO_INCREMENT,
resumeDescription NVARCHAR(255),
PRIMARY KEY (resumeId)
) charset = utf8;
create table user(
userId INTEGER NOT NULL AUTO_INCREMENT,
username NVARCHAR(40) NOT NULL,
password varchar(20) NOT NULL,
email varchar(50) NOT NULL,
resumeId INTEGER UNIQUE,
PRIMARY KEY (userId),
FOREIGN KEY (resumeId) REFERENCES resume(resumeId)
) charset = utf8;
I have tried to insert persian alphabets. I have created a form and made a servlet for that to handle the request. I've got parameters from the request and tested them. At that moment they were ok and they were shown properly. but when I insert them in database I face with this:
(the question marks are persian alphabets)
I dont know what to do and what is the problem.
I have searched for this problem on the internet and tested different ways but none of them worked in my case.
Can anyone please help me to write persian alphabets properly in mySql database?
by the way my connection url is this:
jdbc:mysql://localhost:3306/myDb?zeroDateTimeBehavior=convertToNull
Try using the following connection url:
jdbc:mysql://localhost:3306/myDb?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=UTF-8
This will force the driver to use UTF-8.

Save Values to Database Only Once in A Week

I have a situation, I want to generate a excel sheet through java program. I can generate excel sheet every time i execute the program. While i am executing program data saved to database, but I want to save data to database only once in a week.
I have Two tables:
CREATE TABLE PROJECTS
(id int(10) NOT NULL AUTO_INCREMENT,
project_name varchar(100) NOT NULL,
lastUpdated Date, PRIMARY KEY (id));
CREATE TABLE PROJECT_DATA
(id int(10) NOT NULL AUTO_INCREMENT,
project_id int(10),
rca_field varchar(50),
environment varchar(50),
dateCreated Date,
endDate Date,
dataValue int(10),
PRIMARY KEY (id),
FOREIGN KEY (`project_id`) REFERENCES PROJECTS(`id`));
Can any body suggest me a way to do this in JAVA Program?
Thanks
It sounds like you want to run a periodic service automatically, without requiring a human executing your application. If this is the case, you have a few main options:
On Windows, you can setup a scheduled task
On Posix, you can use cron
Using pure Java (personally recommended), you can use JavaEE's timer service. This will require an application server running, such as RedHat's JBoss, or Oracle's Glassfish: http://docs.oracle.com/javaee/6/tutorial/doc/bnboy.html
1-For Creating excel sheet you can call a Servlet which will generate the excel sheet.(use java POI).
2- For inserting values into DB you can schedule a cronjob which will save the data into db weekly.

Programming User registration in web application Java Spring MVC

I am building web application where i am building the first stage with user registration and login.
I am thinking of
class User
{
private userid;
private firstname
.........
//getters and setters
}
class UserService {
public boolean authenticate(username, password) {}
public addUser()
public saveuser()
public ConfirmEmail()
public resetPassword()
......
}
I have few questions
Is my approach correct?
Also i have diff function in front end and for backend admin user, so should i put all in one class or, i have to make diff for front end and backend?
As this is the most common thing which every organisation requires, so is it possible to find it from internet so that i can see how enterprise people approach this?
First thing, I'd look at whether you can use another authentication system like Google or Facebook, or Open ID (StackOverflow uses these and more).
Secondly, I'd look into using a security framework like Spring Security.
Finally, if you want/need to do it on your own from scratch, here are some pointers
Always store passwords using a 1-way hashing mechanism e.g. SHA
Use salt when hashing your password - you should have a random salt value per password (see this SO question for it's length)
You can also have a constant application-wide salt value that is not stored next to the password
Give the users roles. This will solve your front end/back end users problem
I'm assuming you're using a database. Here's an example schema (MySQL)
CREATE TABLE users (
id INTEGER UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT
mail VARCHAR(255) NOT NULL,
name VARCHAR(255) NOT NULL,
enc_password VARCHARCHAR(64) NOT NULL,
salt CHAR(8) NOT NULL,
is_mail_authenticated TINYINT(1) UNSIGNED NOT NULL DEFAULT 0,
UNIQUE KEY (mail)
) ENGINE = InnoDB;
CREATE TABLE roles (
id INTEGER UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT
name VARCHAR(32) NOT NULL,
UNIQUE KEY (name)
) ENGINE = InnoDB;
CREATE TABLE users_roles (
user_id NTEGER UNSIGNED NOT NULL,
role_id NTEGER UNSIGNED NOT NULL,
FOREIGN KEY (user_id) REFERENCES users (id),
FOREIGN KEY (roel_id) REFERENCES roles (id),
) ENGINE = InnoDB;
That'll do it for a very basic user model. You'll need a tool to generate your salt. I'd use randomAlphanumeric from Apache commons lang.
You may want to add some stuff to lock user accounts after too many failed login attempts. And you may want to track the IP with which they've logged in from. This is left as an exercise to the reader :)
I added the is_mail_authenticated field to track whether the user had authenticated their mail. This is usually accomplished by clicking a link from one's email.
I think, Spring provides very good approach for creating user with role assignment and authenticating the user powerfully, and also maintaining the security or your application. No need to implement whole as our own application, you can use spring security.
http://static.springsource.org/spring-security/site/start-here.html
Either you can create users by your own do the authentication using above security plugins.

Categories

Resources