Spring Security: Check If a User Has a Role in Java – Spring Security:在Java中检查一个用户是否有一个角色

最后修改: 2020年 4月 26日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.绪论

In Spring Security, sometimes it is necessary to check if an authenticated user has a specific role. This can be useful to enable or disable particular features in our applications.

在Spring Security中,有时需要检查认证用户是否具有特定的角色。这对于在我们的应用程序中启用或禁用特定的功能很有用

In this tutorial, we’ll see various ways to check user roles in Java for Spring Security.

在本教程中,我们将看到在Java中为Spring Security检查用户角色的各种方法。

2. Checking User Role in Java

2.检查Java中的用户角色

Spring Security provides several ways to check user roles in Java code. We’ll look at each of them below.

Spring Security提供了几种方法来检查Java代码中的用户角色。我们将在下文中逐一介绍。

2.1. @PreAuthorize

2.1.@预授权

The first way to check for user roles in Java is to use the @PreAuthorize annotation provided by Spring Security. This annotation can be applied to a class or method, and it accepts a single string value that represents a SpEL expression.

在 Java 中检查用户角色的第一种方法是使用 Spring Security 提供的 @PreAuthorize 注解。该注解可应用于类或方法,它接受一个代表SpEL表达式的单一字符串值。

Before we can use this annotation, we must first enable global method security. This can be done in Java code by adding the @EnableGlobalMethodSecurity annotation to any configuration class.

在使用这个注解之前,我们必须首先启用全局方法安全。这可以在Java代码中通过向任何配置类添加@EnableGlobalMethodSecurity注解来实现。

Then, Spring Security provides two expressions we can use with the @PreAuthorize annotation to check user roles:

然后,Spring Security提供了两个表达式,我们可以使用@PreAuthorize注释来检查用户角色。

@PreAuthorize("hasRole('ROLE_ADMIN')")
@GetMapping("/user/{id}")
public String getUser(@PathVariable("id") String id) {
    ...
}

We can also check multiple roles in a single expression:

我们还可以在一个表达式中检查多个角色。

@PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_MANAGER')")
@GetMapping("/users")
public String getUsers() {
    ...
}

In this case, the request will be allowed if the user has any of the specified roles.

在这种情况下,如果用户有任何指定的角色,该请求将被允许。

If the method is called without having the proper role, Spring Security throws an exception and redirects to the error page.

如果该方法在没有适当角色的情况下被调用,Spring Security会抛出一个异常,并重定向到错误页面

2.2. SecurityContext

2.2.SecurityContext

The next way we can check for user roles in Java code is with the SecurityContext class.

我们在Java代码中检查用户角色的下一个方法是使用SecurityContext类。

By default, Spring Security uses a thread-local copy of this class. This means each request in our application has its security context that contains details of the user making the request.

默认情况下,Spring Security使用该类的线程本地副本。这意味着我们应用程序中的每个请求都有其安全上下文,其中包含了提出请求的用户的详细信息

To use it, we simply call the static methods in SecurityContextHolder:

要使用它,我们只需调用SecurityContextHolder中的静态方法。

Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null && auth.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("ADMIN"))) {
    ...
}

Note that we’re using the plain authority name here instead of the full role name.

注意,我们在这里使用的是普通的授权名称,而不是完整的角色名称。

This works well when we need more fine-grained checks — for example, a specific part of a single method. However, this approach will not work if we use the global context holder mode in Spring Security.

当我们需要更细粒度的检查时,这种方法很有效–例如,单个方法的特定部分。然而,如果我们使用Spring Security中的全局上下文保持者模式,这种方法将无法工作

2.3. UserDetailsService

2.3.UserDetailsService

The third way we can lookup user roles in Java code is by using the UserDetailsService. This a bean we can inject anywhere into our application and call it as needed:

我们在Java代码中查询用户角色的第三种方式是使用UserDetailsService。这个bean我们可以注入到我们的应用程序的任何地方,并根据需要调用它。

@GetMapping("/users")
public String getUsers() {
    UserDetails details = userDetailsService.loadUserByUsername("mike");
    if (details != null && details.getAuthorities().stream()
      .anyMatch(a -> a.getAuthority().equals("ADMIN"))) {
        // ...
    }
}

Again, we must use the authority name here, not the full role name with prefix.

同样,我们必须在这里使用授权名称,而不是带前缀的完整角色名称。

The benefit of this approach is that we can check roles for any user, not just the one who made the request.

这种方法的好处是,我们可以检查任何用户的角色,而不仅仅是提出请求的那个人。

2.4. Servlet Request

2.4.伺服机请求

If we’re using Spring MVC, we can also check user roles in Java using the HttpServletRequest class:

如果我们使用Spring MVC,我们还可以使用HttpServletRequest类在Java中检查用户角色。

@GetMapping("/users")
public String getUsers(HttpServletRequest request) {
    if (request.isUserInRole("ROLE_ADMIN")) {
        ...
    }
}

3. Conclusion

3.总结

In this article, we have seen several different ways to check for roles using Java code with Spring Security.

在这篇文章中,我们看到了使用Spring Security的Java代码检查角色的几种不同方法。

As always, the code examples from this article can be found over on GitHub.

一如既往,本文中的代码示例可以在GitHub上找到over