SPRING IN ACTION 第4版笔记-第九章Securing web applications-002-把用户数据存在memory里(AuthenticationManagerBuilder、 UserDetailsManagerConfigurer.UserDetailsBuilder)

Spring Security is extremely flexible and is capable of authenticating users against virtually any data store. Several common user store situations—such as in-memory, relational database, and LDAP —are provided out of the box. But you can also create and plug in custom user store implementations.Spring Security’s Java configuration makes it easy to configure one or more data store options.

一、Working with an in-memory user store

1.Since your security configuration class extends WebSecurityConfigurerAdapter , the easiest way to configure a user store is to override the configure() method that takes an AuthenticationManagerBuilder as a parameter. AuthenticationManagerBuilder has several methods that can be used to configure Spring Security’s authentication

support. With the inMemoryAuthentication() method, you can enable and configure and optionally populate an in-memory user store.

 1 package spitter.config;
 2 import org.springframework.beans.factory.annotation.Autowired;
 3 import org.springframework.context.annotation.Configuration;
 4 import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
 5 import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
 6 import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity;
 7 
 8 @Configuration
 9 @EnableWebMvcSecurity
10 public class SecurityConfig extends WebSecurityConfigurerAdapter {
11     @Override
12     protected void configure(AuthenticationManagerBuilder auth)
13     throws Exception {
14         auth
15             .inMemoryAuthentication() //Enable an in-memory user store. 
16             .withUser("user").password("password").roles("USER").and()
17             .withUser("admin").password("password").roles("USER", "ADMIN");
18     }
19 }

calling inMemoryAuthentication() will enable an in-memory user store. But you’ll also need some users in there, or else it’s as if you have no user store at all.Therefore, you need to call the withUser() method to add a new user to the in-
memory user store. The parameter given is the username. withUser() returns a UserDetailsManagerConfigurer.UserDetailsBuilder ,which has several methods for further configuration of the user, including password() to set the user’s password and roles() to give the user one or more role authorities.

2. UserDetailsManagerConfigurer.UserDetailsBuilder支的全部操作

值得注意的是,role()是调用authrities()实现的,上述代码与如下代码等效:

1 auth
2     .inMemoryAuthentication()
3     .withUser("user").password("password")
4     .authorities("ROLE_USER").and()
5     .withUser("admin").password("password")
6     .authorities("ROLE_USER", "ROLE_ADMIN");
原文地址:https://www.cnblogs.com/shamgod/p/5250013.html