1
1
.
.
2
2
.
.
3
3
A
A
P
P
I
I
-
-
u
u
s
s
e
e
r
r
D
D
e
e
t
t
a
a
i
i
l
l
s
s
S
S
e
e
r
r
v
v
i
i
c
c
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 userDetailsService()
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
P
P
r
r
o
o
c
c
e
e
d
d
u
u
r
r
e
e
Create Project: springboot_security_class (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)
SecurityConfig
Tomcat
hello()
Browser
MyController
MyController.java
package com.ivoronline.springboot_security_class.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_class.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
@Override
protected UserDetailsService userDetailsService() {
//ADMIN
UserDetails admin = User.withDefaultPasswordEncoder()
.username("myadmin")
.password("myadminpassword")
.roles ("ADMIN")
.build();
//USER
UserDetails user = User.withDefaultPasswordEncoder()
.username("myuser")
.password("myuserpassword")
.roles ("USER")
.build();
return new InMemoryUserDetailsManager(admin, 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
http://localhost:8080/logout (Redirects to http://localhost:8080/login)