1
1
.
.
2
2
.
.
4
4
A
A
P
P
I
I
-
-
c
c
o
o
n
n
f
f
i
i
g
g
u
u
r
r
e
e
(
(
)
)
I
I
n
n
f
f
o
o
[
[
G
G
]
]
This tutorial shows how to use API to specify multiple Users by (application.properties can only specify single User)
extending WebSecurityConfigurerAdapter
overriding Method configure() (AuthenticationManagerBuilder auth)
{noop} stands for No-Operation and it instructs Spring to store password as is (without encryption).
Application Schema [Results]
Users
USERNAME
PASSWORD
ROLES
myadmin
myadminpassword
ADMIN
myuser
myuserpassword
USER
Spring Boot Starters
GROUP
DEPENDENCY
DESCRIPTION
Web
Spring Web
Enables @RequestMapping and Tomcat
Security
Spring Security
Enables Spring Security
SecurityConfig
Tomcat
hello()
Browser
MyController
P
P
r
r
o
o
c
c
e
e
d
d
u
u
r
r
e
e
Create Project: springboot_security_class2 (add Spring Boot Starters from the table)
Create Package: controllers (inside main package)
Create Class: MyController.java (inside controllers package)
Create Package: config (inside main package)
Create Class: SecurityConfig.java (inside config package)
MyController.java
package com.ivoronline.springboot_security_class2.controllers;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MyController {
@ResponseBody
@RequestMapping("/Hello")
public String hello() {
return "Hello from Controller";
}
}
SecurityConfig.java
package com.ivoronline.springboot_security_class2.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//ADD ADMIN
auth.inMemoryAuthentication()
.withUser("myadmin")
.password("{noop}myadminpassword")
.roles ("ADMIN");
//ADD USER
auth.inMemoryAuthentication()
.withUser("myuser")
.password("{noop}myuserpassword")
.roles ("USER");
}
}
R
R
e
e
s
s
u
u
l
l
t
t
s
s
http://localhost:8080/Hello
You get redirected to http://localhost:8080/login
Username: myuser
Password: myuserpassword
Sign in
You get redirected back to http://localhost:8080/Hello
http://localhost:8080/logout
Log Out
http://localhost:8080/login (JSESSIONID Cookie is stored in the Browser)
Redirects to http://localhost:8080/Hello