官术网_书友最值得收藏!

Setting up AuthenticationManager

There are number of built-in AuthenticationManager in Spring Security that can be easily used in your application. Spring Security also has a number of helper classes, using which you can set up AuthenticationManager. One helper class is AuthenticationManagerBuilder. Using this class, its quite easy to set up UserDetailsService against a database, in memory, in LDAP, and so on. If the need arises, you could also have your own custom UserDetailsService (maybe a custom single sign-on solution is already there in your organization).

You can make an AuthenticationManager global, so it will be accessible by your entire application. It will be available for method security and other WebSecurityConfigurerAdapter instances. WebSecurityConfigurerAdapter is a class that is extended by your Spring configuration file, making it quite easy to bring Spring Security into your Spring application. This is how you set up a global AuthenticationManager using the @Autowired annotation:

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
public void confGlobalAuthManager(AuthenticationManagerBuilder auth) throws
Exception {
auth
.inMemoryAuthentication()
.withUser("admin").password("admin@password").roles("ROLE_ADMIN");
}
}

You can also create local AuthenticationManager, which is only available for this particular WebSecurityConfigurerAdapterby overriding the configure method, as shown in the following code:

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("admin").password("admin@password").roles("ROLE_ADMIN");
}
}

Another option is to expose the AuthenticationManager bean by overriding authenticationManagerBean method, as shown here:

@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}

You can also expose various AuthenticationManager, AuthenticationProvider, or UserDetailsService as beans which will override the default ones.

In the preceding code examples we have used AuthenticationManagerBuilder to configure in-memory authentication. More mechanisms of the AuthenticationManagerBuilder class will be used in the subsequent examples in this chapter.

主站蜘蛛池模板: 德保县| 高阳县| 吴忠市| 邢台市| 桓台县| 资中县| 广德县| 永川市| 如东县| 牟定县| 墨竹工卡县| 弋阳县| 富源县| 赤城县| 鄂托克前旗| 永福县| 乌鲁木齐县| 江阴市| 随州市| 沿河| 张掖市| 库尔勒市| 渭源县| 贵定县| 绵阳市| 江北区| 荆州市| 阳春市| 门头沟区| 浦江县| 哈密市| 宁远县| 卫辉市| 呼伦贝尔市| 大关县| 普定县| 盐城市| 张家界市| 浑源县| 桓台县| 都匀市|