Spring Security provides a lot of permission control by default, but a good framework must be extensible, and Spring Security is very extensible. You can use the way Spring Security provides for authorization, You can also customize the authorization logic. In short, you can play it any way you want!
Today, Songo takes a look at four common permission controls in Spring Security.
- Expression controls URL path permissions
- Expression control method permissions
- Use filter annotations
- Dynamic permissions
Four ways. Let’s look at them separately.
This is the 30th article in the Spring Security series, and reading the previous articles will help you understand it better:
- Dig a big hole and Spring Security will do it!
- How to decrypt the password
- A step-by-step guide to customizing form logins in Spring Security
- Spring Security does front and back separation, so don’t do page jumps! All JSON interactions
- Authorization in Spring Security used to be so simple
- How does Spring Security store user data into the database?
- Spring Security+Spring Data Jpa, Security management is only easier!
- Spring Boot + Spring Security enables automatic login
- Spring Boot automatic login. How to control security risks?
- How is Spring Security better than Shiro in microservices projects?
- Two ways for SpringSecurity to customize authentication logic (advanced play)
- How can I quickly view information such as the IP address of the login user in Spring Security?
- Spring Security automatically kicks out the previous login user.
- How can I kick out a user who has logged in to Spring Boot + Vue?
- Spring Security comes with a firewall! You have no idea how secure your system is!
- What is a session fixed attack? How do I defend against session fixation attacks in Spring Boot?
- How does Spring Security handle session sharing in a clustered deployment?
- Songgo hand in hand to teach you in SpringBoot CSRF attack! So easy!
- Learn to learn thoroughly! Spring Security CSRF defense source code parsing
- Two poses for password encryption in Spring Boot!
- How to learn Spring Security? Why must we study systematically?
- Spring Security has two different resource release policies. Do not use them incorrectly.
- Spring Boot + CAS single sign-on
- Spring Boot is the third way to implement single sign-on!
- How do I Connect to the Database in Spring Boot+CAS SINGLE Sign-on?
- Spring Boot+CAS default login page is too ugly, how to do?
- How to carry Token in request header with Swagger
- Summary of three cross-domain scenarios in Spring Boot
- How to implement HTTP authentication in Spring Boot?
1. Expressions control URL path permissions
Let’s start with the first one, which is controlling URL path permissions through expressions, which Songo actually talked about in a previous article, so let’s go over it a little bit.
Spring Security supports the use of SpEL expressions for URL and method permission control. If the expression returns true, the corresponding permission is required; otherwise, the corresponding permission is not required. The class that provides the expression is SecurityExpressionRoot:
SecurityExpressionRoot has two implementation classes, representing the extension of SpEL to handle URL permission control and method permission control. For example, hasIpAddress is added to handle URl-path-based permission control.
Let’s take a look at the most basic spELS defined in the SecurityExpressionRoot class:
As you can see, these are all expressions for this class, and I’ll explain them a little bit:
expression | note |
---|---|
hasRole | A user has a role to access resources |
hasAnyRole | A user can access resources with any of multiple roles |
hasAuthority | Similar to hasRole |
hasAnyAuthority | Similar to hasAnyRole |
permitAll | All access |
denyAll | Deny all access |
isAnonymous | Check whether the user is anonymous |
isAuthenticated | Check whether the authentication is successful |
isRememberMe | Determine whether or not to remember what I logged in to |
isFullyAuthenticated | Check whether the user name or password is used to log in |
principle | The current user |
authentication | User object extracted from SecurityContext |
That’s the basic, and in its inheritance class, there’s a little bit of extension, but I’m not going to go over that again.
If the permission is controlled by URL, you only need to configure it as follows:
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("admin")
.antMatchers("/user/**").hasAnyRole("admin"."user")
.anyRequest().authenticated()
.and()
...
}
Copy the code
The admin role is required to access the /admin/** path, and the admin or user role is required to access the /user/** path.
2. Expression control method permission
Of course, we can also control permissions by adding annotations to methods.
To add annotation control to a method, we first need to enable the use of annotations and add the following to the Spring Security configuration class:
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {... . }Copy the code
This configuration enables three annotations, which are:
- @preauthorize: Check the permissions of methods before executing them
- @postauthorize: Verify permissions after methods are executed
- @secured: Similar to @preauthorize
These three can be used in combination with SpEL in a very flexible way. Here are a few demos to share with you.
@Service
public class HelloService {
@PreAuthorize("principal.username.equals('javaboy')")
public String hello(a) {
return "hello";
}
@PreAuthorize("hasRole('admin')")
public String admin(a) {
return "admin";
}
@Secured({"ROLE_user"})
public String user(a) {
return "user";
}
@PreAuthorize("#age>98")
public String getAge(Integer age) {
returnString.valueOf(age); }}Copy the code
- The first hello method, annotated with the constraint that only the user currently logged in with the name javaboy can access the method.
- The second admin method, which indicates that the user accessing this method must have the admin role.
- The user of this method must have the user role, but note that the user role needs to be added
ROLE_
Prefix. - The fourth getAge method, which means that the age parameter to access the method must be greater than 98, or the request will not pass.
As you can see, the expression is still quite rich. If you want to refer to a method parameter, you can use a # to refer to either a primitive type parameter or an object parameter.
In addition to principal, the default object is authentication (see section 1).
3. Use filter annotations
Spring Security also has two filter functions, @prefilter and @postfilter, that automatically remove elements from a collection based on given conditions.
@PostFilter("filterObject.lastIndexOf('2')! = 1")
public List<String> getAllUser(a) {
List<String> users = new ArrayList<>();
for (int i = 0; i < 10; i++) {
users.add("javaboy:" + i);
}
return users;
}
@PreFilter(filterTarget = "ages",value = "filterObject%2==0")
public void getAllAge(List<Integer> ages,List<String> users) {
System.out.println("ages = " + ages);
System.out.println("users = " + users);
}
Copy the code
- In the getAllUser method, the collection is filtered and only elements with suffix 2 are returned, with filterObject representing the element object to be filtered.
- In the getAllAge method, because there are two collections, the filter object is specified using filterTarget.
4. Dynamic permissions
Dynamic permissions are mainly achieved by rewriting interceptors and decision makers, which I have described in detail in the document of VHR. You can obtain documents by replying 888 in the background of the public account [Jiangnan Bit of Yu]. I will not repeat the details.
5. Summary
Well, today we have a little chat about authorization in Spring Security. Of course, there are a lot of details here, and Songko will talk about them in detail later.
If you feel that you have gained something, remember to click on songko under the encouragement of watching oh ~