1
1
.
.
4
4
.
.
8
8
A
A
u
u
t
t
h
h
o
o
r
r
i
i
t
t
i
i
e
e
s
s
-
-
a
a
p
p
p
p
l
l
i
i
c
c
a
a
t
t
i
i
o
o
n
n
.
.
p
p
r
r
o
o
p
p
e
e
r
r
t
t
i
i
e
e
s
s
I
I
n
n
f
f
o
o
[
[
G
G
]
]
This tutorial shows how to use Authorities to Authorize access to Endpoints.
User and Profiles (their authorities) are defined in application.properties (for simplicity so that we don't need to use DB).
The main part of this tutorial is @Service class AccountService implements UserDetailsService { .. }.
It @Overrides loadUserByUsername(String username) which is automatically called by Login Form with entered username
Inside this method we create User Object with authorities specified by spring.security.user.profile = USER.
application.properties
# SECURITY
spring.security.user.name = myuser
spring.security.user.password = mypassword
spring.security.user.profile = USER
# PROFILE AUTHORITIES - CRUD
profile.user = book.read
profile.admin = book.create, book.read, book.update, book.delete
SecurityConfig.java To enable @PreAuthorize
@EnableGlobalMethodSecurity(prePostEnabled = true)
MyController.java CRUD DB Operations
@PreAuthorize("hasAuthority('book.create')")
@PreAuthorize("hasAuthority('book.read')")
@PreAuthorize("hasAuthority('book.update')")
@PreAuthorize("hasAuthority('book.delete')")
Application Schema [Results]
Spring Boot Starters
GROUP
DEPENDENCY
DESCRIPTION
Web
Spring Web
Enables @Controller, @RequestMapping and Tomcat Server
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_authorization_authorities (add Spring Boot Starters from the table)
Edit File: application.properties (specify Username, Password, Role)
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)
Create Package: services (inside main package)
Create Class: AccountService.java (inside services package)
SecurityConfig
http://localhost:8080/ReadBook
readBook()
MyController
Browser
Tomcat
application.properties
# SECURITY
spring.security.user.name = myuser
spring.security.user.password = mypassword
spring.security.user.profile = USER
# PROFILE AUTHORITIES
profile.user = book.read
profile.admin = book.create,book.read,book.update,book.delete
AccountService.java
package com.example.springboot_security_authorization_authorities.services;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
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.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Service
public class AccountService implements UserDetailsService {
//LOAD PROPERTIES (from application.properties file)
@Value("${spring.security.user.profile}") private String userProfile;
@Value("${profile.user}") private String profileUser;
@Value("${profile.admin}") private String profileAdmin;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//GET AUTHORITIES FOR GIVEN USER PROFILE
String userAuthorities = "";
if(userProfile.equals("USER") ) { userAuthorities = profileUser; }
if(userProfile.equals("ADMIN")) { userAuthorities = profileAdmin; }
//GET AUTHORITIES FROM STRING PROPERTY
String[] authoritiesArray = userAuthorities.split(", ");
List<String> authoritiesList = Arrays.asList(authoritiesArray);
//CREATE AUTHORITIES (FOR USER OBJECT)
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (String authority : authoritiesList) {
authorities.add(new SimpleGrantedAuthority(authority.trim()));
}
//CREATE USER
User user = new User("myuser", "mypassword", true, true, true, true, authorities);
//RETURN USER
return user;
}
}
SecurityConfig.java
package com.example.springboot_security_authorization_authorities.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
PasswordEncoder passwordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.formLogin();
}
}
MyController.java (Authorities represent DB CRUD operations)
package com.example.springboot_security_authorization_authorities.controllers;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MyController {
@ResponseBody
@PreAuthorize("hasAuthority('book.create')")
@RequestMapping("/CreateBook")
public String createBook() {
return "Only ADMIN can create Book"; }
@ResponseBody
@PreAuthorize("hasAuthority('book.read')")
@RequestMapping("/ReadBook")
public String readBook() {
return "ADMIN and USER can read Book";
}
@ResponseBody
@PreAuthorize("hasAuthority('book.update')")
@RequestMapping("/UpdateBook")
public String updateBook() {
return "Only ADMIN can update Book";
}
}