Spring Security Tutorial

0
67
spring framework download, spring framework, interview questions, hibernate framework, spring wiki, spring javatpoint, spring version history, spring framework maven, mechanical spring

I assume you know the basics of Spring MVC (Creating a dispatcher and controller). In this article, we will configure Spring and Spring Security using XML.

Project creation

We create a new Maven project and as a project type we choose Web Application.

After creating the project we have to find the pom.xml file. This is a configuration file for Maven.

What is pom.xml now?

We must now indicate the dependencies of the project, which libraries we will use.

We find sections of dependencies.

In me it looks like:

<dependencies>

< groupId> javaxgroupId>

<artifactId> javaee-web-apiartifactId>

<version> 7.0version>

<scope> providedscope>

dependency>

dependencies>

There is one dependency (javaee-web-api dependency block). We now add the dependencies for Spring MVC:

<

groupId> org.springframeworkgroupId>

<artifactId> spring-coreartifactId>

<version> 4.2.0.RELEASEversion>

dependency>

<dependency>

<groupId> org.springframeworkgroupId>

<artifactId> spring-webartifactId>

<version> 4.2.0.RELEASEversion>

dependency>

<dependency>

<groupId> org.springframeworkgroupId>

<artifactId> spring-webmvcartifactId>

<version> 4.2. 0.RELEASEversion>

dependency>

At this time we have a base library for Spring MVC. We will now add a dispatcher and a simple controller to see if everything works as expected.

In the webapp folder we add the WEB-INF folder in which we will place our pages and the Spring configuration files. The physical structure of the project should now be as follows:

Then in the WEB-INF folder we create a web.xml file and put it there:

version = “1.0”  encoding = “UTF-8”?>

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

dispatcher

org.springframework.web.servlet.DispatcherServlet
1
dispatcher
/
30

Now we create a dispatcher-servlet.xml next to the web.xml files with its initial content:

xml version = “1.0” encoding = “UTF-8″?>

<beans xmlns = ” http://www.springframework.org/schema/beans ”

xmlns: xsi = ” http://www.w3.org/2001 / XMLSchema-instance ”

xsi: schemaLocation =” http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.3.xsd

“>

beans

Dispatcher-servlet.xml configuration

I now specify where our jsp files will be located and defining controllers using annotations.

version = “1.0”  encoding = “UTF-8”?>

xmlns = ” http://www.springframework.org/schema/beans ”

xmlns : xsi = ” http://www.w3.org/2001/XMLSchema- instance ”

xmlns : c =” http://www.springframework.org/schema/c ”

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-3.2.xsd

http: // www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.2.xsd

http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring- mvc-3.2.xsd

“>

base-package =” com.mycompany.springsecuritytutorial “/>

class =” org.springframework.web.servlet.view.InternalResourceViewResolver “>

name =” prefix ”  value =” / WEB-INF / jsp / “/>

name =” suffix ”  value =”. jsp “/>

We are adding a controller in the com.mycompany.springsecuritytutorial package.

I add a Hello.java class and create a controller in it

package com.mycompany.springsecuritytutorial;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.RequestMapping;

@Controller

public class  Hello  {

@RequestMapping (“/ index”)

public String helloController (Model  model ) {

return “index”;

}

}

The effect should be:

Spring Security Dependency

Now we will add the necessary libraries for Spring Security

  • spring-security-web
  • spring-security-config

org.springframework.security

spring-security-web

3.2.8.RELEASE

org.springframework.security

spring-security-config

3.2.8.RELEASE

Next, to the web.xml file we will create a spring-secutity.xml file.

In this file, we will place the configuration for Spring Security. We will determine who has access to what and with what rights. The underlying template for this file is as follows:

xmlns = ” http://www.springframework.org/schema/security ”

xmlns : beans = ” http://www.springframework.org/schema/beans ”

xmlns : xsi = ” http://www.w3.org / 2001 / XMLSchema-instance ”

xsi : schemaLocation =”

http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd

http: // www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd “>

Although we have defined the configuration file for Spring security to spring, it does not know that it should be used. We will inform you about it in the web.xml file.

Before the declaration of our dispatcher, we indicate where the file is located within the context of the application. As a reminder, in the Application Context, we put the necessary configuration for the application. Because our application can also consist of other modules in addition to the web layer itself.

contextConfigLocation

/WEB-INF/spring-security.xml

org.springframework.web.context.ContextLoaderListener

Spring Security filters the urls that are supposed to pass through Springa. Spring supplies ready-made classes for this purpose.

MojFiltr

org.springframework.web.filter.DelegatingFilterProxy

MojFiltr

/ *

The above code means that all addresses referred by the client will be checked. We will place the more exact configuration in the spring-security.xml file. The entire web.xml file is as follows:

version = “1.0”  encoding = “UTF-8”?>

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

contextConfigLocation

/WEB-INF/spring-security.xml, /WEB-INF/applicationContext.xml

org.springframework.web.context.ContextLoaderListener

dispatcher

org.springframework.web.servlet.DispatcherServlet

1

dispatcher

/

SpringSecurityFilterChain

org.springframework.web.filter.DelegatingFilterProxy

springSecurityFilterChain

/ *

30

Now let’s go to the configuration file spring-security.xml

Spring-security.xml configuration

Basically, we need to create two sections to work.

  • http
  • authentication-manager

In the first section (http) we will determine how to log in and what addresses are to be checked. In the second section (authentication-manager) we will define login data and user roles. First, we will put the user on “rigid” and then we will do something more practical, ie we will authenticate by the database. We will start by configuring the http section

Configure http section

Please enter the following code in the security file.

auto-config = “true”>

pattern = “/ user / *”  access = “ROLE_USER” />

The auto-config = “true” attribute is a shortcut.

All three tags need to be configured.

  • form-login

For this tag we can assign what the login url should be, where should be redirected after successful login, and where to send the user in case of error at login. Example configuration of these attributes

<form-login

</ form-login
login-page = ‘/ login.do’

default-target-url = “/ start.do”

authentication-failure-url = “/ login.do?error=true” />

  • login-page – your login address
  • default-target-url – redirect if successful login
  • authentication-failure-url – redirect in case of an error
  • http-basic

If a form-login to Spring tag is defined, it will not take into account the http-basic tag. If there is no login form in our configuration, then the login will take place through the browser and it will look like this:

 

  • logout

Use this tag to sign out. You can add a logout-success-url attribute in which we determine where we redirect the user after a successful survey.

logout-success-url = “/ login.do” />

We will be at the default configuration so our spring-security.xml file looks like this:

xmlns = ” http://www.springframework.org/schema/security ”

xmlns : beans = ” http://www.springframework.org/schema/beans ”

xmlns : xsi = ” http://www.w3.org / 2001 / XMLSchema-instance ”

xsi : schemaLocation =”

http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd

http: // www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd “>

auto-config =” true “>

Intercept-url

Using the intercept-url tag we will determine who has access to what url. Let’s assume that for the time being we will need to log in for all addresses starting with / user **.

auto-config = “true”>

pattern = “/ user / *”  access = “ROLE_USER” />

In the pattern attribute we specify the url, and in the access attribute required permissions.

Configure the authentication-manger section

We still need to define users for our application:

name = “user”  password = “user123”  authorities = “ROLE_USER” />

At this time we are interested in the user-service section in which we define users. Now let’s see if everything works, so add a controller in Hello.java that will require authorization.

 

Pay attention to the structure of directories. In the jsp folder we added a user folder and index.jsp file

After firing the application and logging in for such url:  http: // localhost: 9090 / SpringSecurityTutorial / user /  should redirect you to  http: // localhost: 9090 / SpringSecurityTutorial / spring_security_login

and the effect will be as follows:

Now let’s try to log in using data

Login: user

Password: abc

Of course, the login will fail and the result will be:

 

Now enter the correct login information, ie, as defined in the spring-security.xml file, and we should be logged in and successfully redirected.

It is also worth noting that Spring has placed a cookie with the identifier of our session.

Now let’s add an additional user to an admin role (ROLE_ADMIN). Let’s also add an additional intercept-url, with an additional controller and view.

First, we add entries to spring-security.xml

auto-config = “true”>

pattern = “/ user / *”  access = “ROLE_USER” />

pattern = “/ admin / *”  access = “ROLE_ADMIN” />

name = “user”  password = “user123”  Authorities = “ROLE_USER” />

name = “admin”  password = “admin1”  Authorities = “ROLE_ADMIN” />

Then add the additional controller:

@RequestMapping (“/ admin / *”)

public String admin (Model model) {

return “admin / index”;

}

And we add a folder to the view. Of course everything can be in one folder, but we care about the order in our application.

Let’s now go to  http: // localhost: 9090 / SpringSecurityTutorial / admin /  and let’s try to log in as a regular user.

We get 403 or no powers. Now let’s remove our cookie from Spring or restart the server. Then login as admin:

 

Custom login form

We will start by modifying the spring-security.xml file:

auto-config = “true”>

the login-page = “/ login”

authentication-failure-url = “/ login? error”

username-parameter = “username”

password-parameter = “password”

/>

pattern = “/ user / * ”  access =” ROLE_USER “/>

pattern =” / admin / * ”  access =” ROLE_ADMIN “/>

I added here two additional attributes: from-login:

  • username-parameter – the name of the user field of the html code
  • password-parameter – the field name of the html code field

We indicated to Spring that the login will take place via login / login. So let’s create a controller that will handle this request:

@RequestMapping (value = “/ login”, method = RequestMethod GET )

public ModelAndView login (

@RequestParam (value = “error” required =  false ) String error,

@RequestParam (value = “logout” required =  false ) String logout) {

ModelAndView = new model ModelAndView ( “login”);

if (error! =  null ) {

model.addObject (“error”, “invalid username or password”);

}

If (logout! =  Null ) {

model.addObject ( “logout”, “You have successfully logged out!”);

}

Return model;

}

As you can see, we need to handle two incoming parameters here.

  • error – if login error occurs
  • logout – if someone logs out

These are just plain text variables, so I’m going to introduce the Polish message names here and send them to the viewer.

Now in the jsp folder we create a login.jsp file with the following content:

<% @page  contentType = “text / html” pageEncoding = “UTF-8″%>

<% @ taglib uri = ” http://java.sun.com/jsp/jstl/core ” prefix = “c”%>

http-equiv = “Content-Type”  content = “text / html; charset = UTF-8”>

class = “loginbox”>

Please login:

test = “$ {not empty error}”>

class = “error”> $ {error}
name = ‘loginForm’

action = “”  method = ‘POST’>

Login: type = “text”  name = “username” />

password: type = “password”  name = “password” />

Name = “submit”  type = “submit”  value = “submit” />

In the div block with the class (css) login box I check whether I have to display an error message. If so, I show it.

test = “$ {not empty error}”>

class = “error”> $ {error}
The second important thing is to set the target url of the form. We get the url from spring in the form of a variable.

We must remember to set the appropriate name attribute for the form fields. In this case, it is a username and a password, as we did in the spring-security.xml file

username-parameter = “username”

password-parameter = “password”

The jstl tag library is added to the pom.xml file. Let’s add this dependency:

jstl

jstl

1.1.0

Now we have to build the project with and fire it.

Upon entering  http: // localhost: 9090 / SpringSecurityTutorial / user /

 

In case of incorrect login data:

 

After logging in correctly:

 

Integration of Spring Security with database

In this article, we will use the Oracle database, but there is nothing to prevent you from using other databases such as MySQL or MSSQL.

1.See driver for database communication

We complement our pom.xml with an additional dependency that is our database driver

com.oracle

ojdbc6

11.2.0.3

2. Create an application context

Next, in the web.xml file, we add the context-param section to the extra file. This should now look like this:

contextConfigLocation

/WEB-INF/spring-security.xml, /WEB-INF/applicationContext.xml

So we added an additional file with the context of the application. In the context of the application, we put any Spring bean. You will notice that in the dispatcher-servlet.xml file we have already placed the bean and why not try inserting other beans. Now the dispatcher-servlet.xml file is marked as a regular servlet there we do not set up the entire application configuration, only inform m. In. about jsp file location.

3. Create the applicationContext.xml file

Now we will create our application context in the WEB-INF folder.

The whole should look like this:

version = “1.0”  encoding = “UTF-8”?>

xmlns = ” http://www.springframework.org/schema/beans ”

xmlns: xsi = ” http://www.w3.org/2001/XMLSchema- instance ”

xsi: schemaLocation =” http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd

“>

id =” dataSource ”  class = “oracle.jdbc.pool.OracleDataSource”>

name = “dataSourceName”  value = “ds” />

name = “URL”  value = “jdbc: oracle: thin: @localhost: 1521:xe “/>

name =” user ”  value= “training” />

name = “password”  value = “password” />

Before creating a bean I suggest building a project with dependencies. We’ll get some hints when creating the bean.

The bean has been bolded. We need to specify what type our bean will be (the class attribute), and set its id, which is the name we will refer to (the id attribute).

Then set the connection properties, ie

  • URL – the address we are connecting to. In this case it is localhost on port 1521 and sid base is car
  • user – username in the database. In this case training
  • password – user password for the database.

WARNING! The names of such properties may vary depending on the class used (in this case, oracle.jdbc.pool.OracleDataSource). For other drivers, the user field can be called username

4. Create the appropriate tables in the database

Spring Security logs two queries. First, the login data is correct and the second one is the user’s credentials.

I created the following table in the database for users:

 

Required fields are login, pass, active. Spring always checks if the user has activated.

I also created a second table with user permissions:

 

I included information about the user ID and its role.

Now time for the data for the table users:

Data for authorization table:

 

Note that roles are written according to the Spring Security roles.

5. Spring-security update

Now we are updating the spring-security.xml file. We’re throwing our rigidly created user-service and adding jdbc-user-service. This should look like this:

<authentication <span = “”> -manager >

<authentication <span = “”> -provider >

<jdbc <span = “”> -user-service  data-source-ref = “dataSource”

users-to-username-query =

“select login, pass, active from users where login =?”

Authorities-by-username-query =

“select username, role permissions from users join born in a u.user_id = ur.user_id where username =?” />

</ jdbc <> </ authentication <> -provider >

</ authentication < manager >

  • data-source-ref – we provide the ID of our bean with the connection to the database. Our name was from DataSource.
  • users-by-username-query – This query retrieves login, password and user activity status
  • authorities-by-username-query – This query checks user permissions. Warning! Spring always needs a login and a user role, so we need to join here.

What is important in these inquiries?

Asking users-by-username-query to always return 3 columns; The first is the login, the second is the password, and the third is the user’s activity. You may have broken this data after several tables, but your task is to write a query that will return exactly three such columns.

For example, if you do not care about user activity, instead of the active column, we would simply insert one.

select login, pass, ‘1’ from users where login =?

The adequate situation with the second query. You must provide spring login and user role. Where are the data and how are they distributed?

After firing, the login effect should be the same. We are now logging on to the database.